text
stringlengths
8
6.88M
#include "aumelsec.h" #include "aulibdefs.h" #include "auplcdrive.h" #include "autag.h" #include "auplc.h" #include "aubase.h" #include <QString> #include <QTcpSocket> #include <QTimer> #include <QDataStream> #include <QFile> AuMelsec::AuMelsec(AuBase &base,quint16 index, QObject *parrent): AuPlcDrive(base,index,parrent), nPort(5002) ,nC(0),plcAddr(1) // кноструктор, треба уточнити { linkOk=false; // з'єднання сигналі і слотів переписано на новий стиль Qt5, старий стиль залишено закоментареним // теймер паузи між спробами встановити нове з’єднання connWait=new QTimer(this); connWait->setInterval(10000); //connect(connWait,SIGNAL(timeout()),this,SLOT(slotNewConnect())); connect(connWait,&QTimer::timeout,this,&AuMelsec::slotNewConnect); // таймер для відліку таймайту з’єднання connTimeout=new QTimer(this); connTimeout->setInterval(10000); //connect(connTimeout,SIGNAL(timeout()),this,SLOT(slotTimeout())); connect(connTimeout,&QTimer::timeout,this,&AuMelsec::slotTimeout); // сокет для здійснення обміну даними pS=new QTcpSocket(this); //connect(pS,SIGNAL(connected()),this,SLOT(slotConnected())); connect(pS,&QTcpSocket::connected,this,&AuMelsec::slotConnected); //connect(pS,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slotError(QAbstractSocket::SocketError))); connect(pS,&QAbstractSocket::errorOccurred,this,&AuMelsec::slotError); //connect(pS,SIGNAL(readyRead()),this,SLOT(slotRead())); connect(pS,&QTcpSocket::readyRead,this,&AuMelsec::slotRead); //connect(pS,SIGNAL(disconnected()),this,SLOT(slotDisconnect())); connect(pS,&QTcpSocket::disconnected,this,&AuMelsec::slotDisconnect); //qDebug() << myName; setObjectName(myName); loadList(base[iX].fileList());// завантажити список тегів і сформувати чергу запитів для отримання даних з контролера // підключаємось до бази для сигналізації про отримання свіжих даних з контролера connect(this,static_cast<void (AuMelsec::*)()>(&AuMelsec::updateData),&base,&AuBase::slotUpdateData); connect(this,static_cast<void (AuMelsec::*)()>(&AuMelsec::updateData),&base[iX],&AuPlc::setData); foreach (AuTag *tag, base[iX].tags()) { // підключаємось до тегів для відправки даних в контролер connect(tag,QOverload<qint32,QVector<qint16> &>::of(&AuTag::sendData),this,&AuMelsec::setData); } base[iX].setActive(true); // встановити прапор активного обміну це потрібно для передачі шкал в мережу cmdpref["D"]=qint8(0xA8); cmdpref["X"]=qint8(0x9C); cmdpref["Y"]=qint8(0x9D); cmdpref["M"]=qint8(0x90); cmdpref["L"]=qint8(0x92); // десь тут ще потрібно сформувати пакунок на запити } AuMelsec::~AuMelsec() // поки-що тривіальний деструктор { pS->close(); } void AuMelsec::slotConnected () // приєдналися { //connSend->start(); connTimeout->start(); nLen=0; qDebug() << "Connected to host" << myName; // slotSend(); // розпочати обмін pS->write(query_list[0]); // qDebug() << "query_list[0]" << query_list[0].size(); nC=0; emit Alert(QString("Connected to PLC: %1:%2").arg(myName).arg(nPort)); linkOk=true; } void AuMelsec::slotNewConnect() { connWait->stop(); pS->connectToHost(myName,nPort); } void AuMelsec::slotTimeout() // таймаут отримання даних від сервера { // connSend->stop(); connTimeout->stop(); connWait->start(); pS->close(); emit Alert(QString("Connection to PLC lost: %1:%2").arg(myName).arg(nPort)); // qDebug() << QString("Connection to PLC lost: %1:%2").arg(myName).arg(nPort); } void AuMelsec::slotDisconnect() // відєднання зі сторони сервера { //connSend->stop(); // зупинити таймер, коли від’єднано немає сенсу слати запити pS->close(); } void AuMelsec::slotError(QAbstractSocket::SocketError) { //connSend->stop(); connTimeout->stop(); connWait->start(); //qDebug() << "Connection error"; emit Alert(QString("Connection to PLC error: %1:%2. %3").arg(myName).arg(nPort).arg(pS->errorString())); pS->close(); } // виявилося що не получається виконувавти асинхронні запити до контролера I-8000, це не дуже добре. /* void AuMelsec::slotSend() { #ifdef ASYNC //qDebug() << "Start -------------------------------------------------------------------------------"; if(1>local_read[0]) { pS->write(query_list[0]); local_read[0]=query_read[0]; } local_read[0]--; nC=0; #else // асинхронне виконання //qDebug() << "slotSend"; for(int i=1;i<query_list.size();++i) { if(1>local_read[i]) { //qDebug() << i; pS->write(query_list[i]); local_read[i]=query_read[i]; } local_read[i]--; } #endif } */ void AuMelsec::slotRead() { QDataStream in(pS); qint16 v16; quint8 v8; in.setByteOrder(QDataStream::LittleEndian); // встановити порядок байт // qDebug() << "slotRead()" << pS->bytesAvailable() ; for(;;) { if(nLen==0) // читати заголовок { if(pS->bytesAvailable()<9) // якщо тут мало байт { break; } // вичитати мусор, можливо воно щось означає... in >> v8; in >> v16; in >> v16; in >> v16; in >> v16; // вичитати довжину nLen=v16; // зкорегувати та зберегти довжину // qDebug() << "nLen" << nLen; } if(pS->bytesAvailable()<nLen) { break; } in >> v16; // знову мусор // отримано весь пакунок, розібрати на частини //qDebug() << "Start packet proccess Index" << Index << "nLen" << nLen << "as " << as << "fc" << fc; //тепер тут є чотири варіанти // 1 - отримано певну кількісит слів, котрі є регістрами D // 2 - отримано певну кількість тетрад (спакованих в байти) котрі є бітами // 3 - нічого не отримано, якщо перед цим була передача даних // 4 - отримано якесь повідомлення про помилку у відповідь на передачу даних. if(nC<query_list.size()) // якщо попереду був пакунок із query_list { // тоді треба зберегти отримані від контролера дані if(quint8(query_list[nC][18])==0xA8) // що то за дані якщо 0xA8 згачить D-регістри { for(int i=0;i<(nLen-2)/2;++i) // читати слова { in >> v16; plcData[Index[nC]+i]=v16; } } else // інакще там біти { for(int i=0;i<nLen-2;++i) { in >> v8; plcData[Index[nC]+i*2]=v8&0x10?-1:0; // якось так. plcData[Index[nC]+i*2+1]=v8&0x1?-1:0; } } } else // інакще щоб там не було споржнити до кінця { while(!in.atEnd()) // чи це спрацює ? треба ретельно перевірити.... in >> v8; } #ifdef ASYNC //qDebug() << "nC " << nC << "query_list.size()" << query_list.size() ; // відправити наступний запит ++nC; while(nC<query_list.size()) { local_read[nC]--; if(1>local_read[nC]) { pS->write(query_list[nC]); local_read[nC]=query_read[nC]; break; } ++nC; } if(nC==query_list.size()) // при виконанні кругу запитів на отримання даних смикнути про отримання даних це потенційно мало б зменшити проморгування індикаторів при введенні даних { emit updateData(); emit updateData(plcData); } if(! (nC < query_list.size())) { //qDebug() << "Process query queue" ; if(query_queue.isEmpty()) // перевірити чергу при умові що інших запитів немає. { pS->write(query_list[0]); nC=0; } else pS->write(query_queue.dequeue()); // якщо не пуста, передати } #endif nLen=0; } connTimeout->stop(); connTimeout->start(); // qDebug() << plcData; } int AuMelsec::loadList(QString fileName) { QFile f(fileName); int i; QString s; QStringList sl; QString type,type_old; int wc=0, wc_last=0; // лічильник слів qint16 next_addr=0,current_addr=0; //адреси qint16 current_len=0,packet_len=0; // поточна довжина qint16 current_rf=0,last_rf=0; // прапори читання // qint16 current_ft=0; // пити полів, для виявлення EBOOL QByteArray query; QDataStream qry(&query,QIODevice::WriteOnly); qry.setByteOrder(QDataStream::LittleEndian); QHash<QString,QString> tag_scale; // тут будуть теги, які шкалюються по іншому параметру QStringList ft; ft << "Integer" << "Bool" << "Real" << "Timer" << "Long" << "EBOOL" ; //qDebug() << "file " << fileName; // очистити все на випадок повторного завантаження // tags.clear(); query_list.clear(); query_read.clear(); local_read.clear(); if(f.open(QIODevice::ReadOnly)) { for(i=0;!f.atEnd();++i) { s=QString::fromUtf8(f.readLine()).trimmed(); //читати //qDebug() << i << s; sl= s.split("\t"); // розбити на поля if(sl.size()>4) // якщо є всі поля { s= sl[0]; // назва тега //qDebug() << s; type_old=type; type=sl[1].left(1); if(type=="X" || type=="Y") // це кодується в 16-й системі current_addr=sl[1].right(sl[1].size()-1).toInt(0,16); else current_addr=sl[1].right(sl[1].size()-1).toInt(); // індекс, тут би для повного щася треба б було перевірити чи воно правильно перетворилося на число //tags[s] << wc // 0-index // << current_addr ; // 1- address current_rf=sl[3].toInt(); wc_last=wc; // це потрібно для правильного формування поля id транзакції яке містить зміщення індексу в масиві даних // метод не зовсім стандартний, на інших контролерах може і не буде працювати // розпізнати типи даних if(type=="D") { if(sl[2]=="Integer" ) { ++wc; current_len=1; } else if (sl[2]=="Real" || sl[2]=="Timer" || sl[2]=="Long" ) { wc+=2; current_len=2; } else { qDebug() << tr("Unknown data type") << sl[2] << sl; ::exit(1); } } else if(type=="M" || type=="L" || type=="X" || type=="Y") // це точно байт { ++wc; current_len=1; // тут треба зімітувати дірку } else // невідомий тип даних { qDebug() << tr("Unknown data type") << type << sl[2] << sl; ::exit(1); } //current_ft=ft.indexOf(sl[2]); packet_len+=current_len; if( // packet_len>124 || current_addr>next_addr || // виявити дірки, current_rf!=last_rf || // межі пакунків, type != type_old ) // зміна типу // (current_ft==5 && last_ft!=5) || // кратність читання // (current_ft!=5 && last_ft==5)) // чи зміну типу { // Зберегти індекс в масиві даних Index << wc_last; if(query.size()) // якщо щось є, { query_list << query; // зберегти dataLen << packet_len; //qDebug() << packet_len-current_len; // //qDebug() << query; } // підготуватися до нового запиту qry.device()->seek(0); query.clear(); // сформувати заголовок packet_len=current_len; // сформувати запит qry << qint8(0x50) << qint8(0) // subheader << qint8(1) // netv No << plcAddr // Addres PLC << qint8(0xFF) << qint8(0x03) << qint8(0x0) // не знаю що це << qint8(0x0c) << qint8(0x0) // data length << qint8(0x30) << qint8(0x0) // timer << qint8(0x01) << qint8(0x4) // command << (type=="D" ?qint8(0x0):qint8(1)) << qint8(0x0) // subcommand << current_addr << qint8(0x0) // start // адреса задається в трома байтами, тут старший завжди нуль, відповідно можна отримати тільки 65536 слів << cmdpref[type] ; // Data type //<< qint16(0x0); // len //^^^^^^^^^^^^^^^^^^^^^^ можливо для інших контролерів цей декримент непотрібен //qDebug() << qint16(wc_last) << qint16(0) << qint16(6) << qint8(1) << qint8(sl[2]=="EBOOL"?GETMCR:GETMHR) << qint16(current_addr-1); query_read << current_rf; //прапор read на пакунок local_read << 0; } else // в іншому разі поновити дані про довжину. { qry.device()->seek(query.size()-2); } qry << packet_len; //додати довжину пакунка next_addr=current_addr+current_len; // розрахувати новий наступний очікуваний адрес last_rf=current_rf; //last_ft=current_ft; // цей код би винести в окремий клас } } if(query.size()) // зберегти останній запит. { query_list << query; dataLen << packet_len; //qDebug() << packet_len; query_read << current_rf; } f.close(); return i; } else { return 0; } } void AuMelsec::setHostName(QString hostName) { myName=hostName; setObjectName(hostName); } void AuMelsec::setPort(int Port) { nPort=Port; } int AuMelsec::start() { // тут би треба зробити якісь додаткові перевірки pS->connectToHost(myName,nPort); return 0; } void AuMelsec::setData(qint32 addr,QVector<qint16> &v) { QByteArray q; QDataStream qry(&q,QIODevice::WriteOnly); qry.setByteOrder(QDataStream::LittleEndian); QVector<qint8> vp; // масив, у якому будуть підгтовані для передачі дані qint16 pLen,vLen=v.size(); union { struct { quint8 type; quint8 symType; qint16 address; } ; qint32 val; }tAddr ; tAddr.val=addr; if(tAddr.type!=0xA8) // якщо D-регістер { if(tAddr.type==0x9C) // якщ там X-регісти return; // далі можна не продовжувати if(v.size()%2) // кількість змінних має бути парною, інакше буде проблема v << 0; // дописати нуль, контролер його проігнорує for(int i=0;i<v.size();i+=2) vp << qint8( (v[i]?0x10:0 )| (v[i+1]?0x01:0) ); pLen=vp.size(); // qDebug() << "vp" << vp; } else { pLen=v.size()*2; } //qDebug() << tag << QString("%1").arg(qint32(tags[tag][6])&0xff,2,16,QChar('0')) << v; qry << qint8(0x50) << qint8(0) // subheader << qint8(1) // netv No << plcAddr // Addres PLC << qint8(0xFF) << qint8(0x03) << qint8(0x0) // не знаю що це << qint16(pLen+12) // data length << qint8(0x30) << qint8(0x0) // timer << qint8(0x01) << qint8(0x14) // command << ( tAddr.type==0xA8 ?qint8(0x0):qint8(1)) << qint8(0x0) // subcommand // << qint8(0x1) << qint8(0x0) // subcommand << qint16(tAddr.address) << qint8(0x0) // start // адреса задається в трома байтами, тут старший завжди нуль, відповідно можна отримати тільки 65536 слів << qint8(tAddr.type) // Data type << vLen ; // Розмір масиву з даними. if(tAddr.type==0xA8) { foreach(qint16 t,v) { qry << t; // завантажити дані } } else { foreach(qint8 t,vp) { qry << t; // завантажити дані } } query_queue.enqueue(q); // поставити в чергу на відправку в контролер }
#pragma once #include <vector> #include <iostream> #include <map> #include <algorithm> #include <functional> #include "Cell.h" #include "Board.h" #include "CellsStateStatistic.h" #include <thread> Board::Board() : size(0) { } Board::Board(int size) : size(size) { this->createBoard(); this->initAliveCells(); this->initCellStats(); } void Board::initAliveCells() { this->boardPtr[1][0].cellStatus = 0; this->boardPtr[1][2].cellStatus = 0; this->boardPtr[2][1].cellStatus = 0; this->boardPtr[2][2].cellStatus = 0; this->boardPtr[3][1].cellStatus = 0; } void Board::initCellStats() { for (int i = 0; i <= Cell::DEAD; i++) { this->StateStatisticVector.push_back(CellsStateStatistic(i)); } } void Board::incrementStateObjectByState(short state) const { std::vector<CellsStateStatistic>::iterator elementToUpdate = std::find_if( StateStatisticVector.begin(), StateStatisticVector.end(), [&](CellsStateStatistic CellsStateStat) { return CellsStateStat.cellId == state; } ); multiThreadMutex.lock(); (*elementToUpdate).amount += 1; multiThreadMutex.unlock(); } void Board::clearCellStats() const { for (int i = 0; i <= Cell::DEAD; i++) { this->StateStatisticVector[i].amount = 0; } } void Board::createBoard() { this->boardPtr.resize(this->size); for (int i = 0; i < this->size; i++) { this->boardPtr[i].resize(this->size); for (int j = 0; j < this->size; j++) { this->boardPtr[i].push_back(Cell()); } } } void Board::printBoard() const { for (int i = 0; i < this->size; i++) { for (int j = 0; j < this->size; j++) { std::cout << boardPtr[i][j].checkCellStatus(); std::cout << " "; } std::cout << std::endl; } } void Board::printCellAmountByAge() const { std::cout << "----------------------------------------------" << std::endl; for (int i = 0; i < this->StateStatisticVector.size(); i++) { std::cout << this->StateStatisticVector[i].cellName << ": \t" << this->StateStatisticVector[i].amount << std::endl; } std::cout << "----------------------------------------------" << std::endl; } void Board::syncStateOfCellBoards() const { for (int i = 0; i < this->size; i++) { for (int j = 0; j < this->size; j++) { this->boardPtr[i][j].cellStatus = this->boardPtr[i][j].nextStatus; } } } void call_from_thread(int tid) { std::cout << "Launched by thread " << tid << std::endl; } void Board::calcElementAmountByAge() const { std::mutex printMutex; auto calcElementAmountByAgeRow = [&](int rowIdx) { printMutex.lock(); std::cout << "Thread with id: " << std::this_thread::get_id() << " calculate it's part." << std::endl; printMutex.unlock(); for (int j = 0; j < this->size; j++) { incrementStateObjectByState(this->boardPtr[rowIdx][j].cellStatus); } }; for (int i = 0; i < this->size; i++) { this->threadVector[i] = std::thread(calcElementAmountByAgeRow, i); } for (int i = 0; i < this->size; i++) { this->threadVector[i].join(); } } void Board::sortStateStatisticVector() const { std::sort( this->StateStatisticVector.begin(), this->StateStatisticVector.end(), std::greater<CellsStateStatistic>() ); } void Board::calcAndPrintBoardCellStatists() const { this->clearCellStats(); this->calcElementAmountByAge(); this->sortStateStatisticVector(); this->printCellAmountByAge(); }
#ifndef TurnBanksH #define TurnBanksH #pragma once #include "RiverTree.h" #include "..\..\..\..\Util\FileSwapping.h" #include "..\..\..\..\Util\FileRec64.h" #include "..\..\..\..\Util\Matrix.h" #include "..\..\Source\defaultType.h" #include "..\..\..\..\NeuroNet\NeuroNet.h" #include "..\..\..\..\Util\\AnyType.h" #ifdef COMP_C #define FILE_RIVER_PREPARE "c:\\Data\\riverPrepare.bin" #define DIR_BANK_RIVER "c:\\data\\RiverBank\\" #define PATH_BANK_RIVER "c:\\data\\RiverBank\\FileRiverBank" #define FILE_TURN_PREPARE "c:\\Data\\turnsPrepare.bin" #define FILE_FLOP_PREPARE "c:\\Data\\flopPrepare.bin" #define FILE_PREFLOP_PREPARE "c:\\Data\\PreflopPrepare.bin" #define FILE_TURN_BANK "c:\\data\\TurnBank\\FileTurnBank" #define DIR_TURN_BANK "c:\\data\\TurnBank\\" #define DIR_FLOP_BANK "c:\\data\\FlopBank\\" #define FILE_FLOP_BANK "c:\\data\\FlopBank\\FileFlopBank" #define TURN_NODE_BANK "c:\\data\\TurnBank\\FileTurnNodeBank" #define FLOP_NODE_BANK "c:\\data\\FlopBank\\FileFlopNodeBank" #define PREFLOP_NODE_BANK "c:\\data\\PreFlopBank\\FilePreflopNodeBank" #define FILE_PREFLOP_BANK "c:\\data\\PreFlopBank\\FilePreflopBank.bnk" #else #define FILE_RIVER_PREPARE "d:\\Data\\riverPrepare.bin" #define DIR_BANK_RIVER "d:\\data\\RiverBank\\" #define PATH_BANK_RIVER "d:\\data\\RiverBank\\FileRiverBank" #define FILE_TURN_PREPARE "d:\\Data\\turnsPrepare.bin" #define FILE_FLOP_PREPARE "d:\\Data\\flopPrepare.bin" #define FILE_PREFLOP_PREPARE "d:\\Data\\PreflopPrepare.bin" #define FILE_TURN_BANK "d:\\data\\TurnBank\\FileTurnBank" #define DIR_TURN_BANK "d:\\data\\TurnBank\\" #define DIR_FLOP_BANK "d:\\data\\FlopBank\\" #define FILE_FLOP_BANK "d:\\data\\FlopBank\\FileFlopBank" #define TURN_NODE_BANK "d:\\data\\TurnBank\\FileTurnNodeBank" #define FLOP_NODE_BANK "d:\\data\\FlopBank\\FileFlopNodeBank" #define PREFLOP_NODE_BANK "d:\\data\\PreFlopBank\\FilePreflopNodeBank" #define FILE_PREFLOP_BANK "d:\\data\\PreFlopBank\\FilePreflopBank.bnk" #endif //#define RB_MAX_NEAR_DIST 0.15 //#define RB_STACK_SHIFT 1.2 // Должен быть больше 1 #define MAX_CN_HANDS 100 //--------------------------------------------------------------------------------------------------------------------------------------------------- struct tpPrepareRiverBd { int WriteFile(int handle) { _gset.WriteFile(handle); _dat.WriteFile(handle); return 0; } int ReadFile(int handle) { _gset.ReadFile(handle); _dat.ReadFile(handle); return 0; } size_t SizeInFile() { return _gset.SizeInFile() + _dat.SizeInFile(); } clInComeDataRoot _gset; clRiverDat _dat; }; class clRiverBankUnit { public: inline int WriteFile(int handle) { _dat.WriteFile(handle); WriteVectFile(handle, _ev[0]); WriteVectFile(handle, _ev[1]); return _root.WriteFile(handle); } inline int ReadFile(int handle) { _dat.ReadFile(handle); ReadVectFile(handle, _ev[0]); ReadVectFile(handle, _ev[1]); return _root.ReadFile(handle); } inline size_t SizeInFile() { return _dat.SizeInFile() + SizeVectFile(_ev[0]) + SizeVectFile(_ev[1]) + _root.SizeInFile(); } void CalcRoot(int cnCalc); clRiverDat _dat; vector <float> _ev[2]; clRootRiverTree _root; }; /*struct stRiverBankUnitInfo { int _nbRecord; tpFloat _stack; }; class clRiverBankCls { public: // clRiverBankOne(); // ~clRiverBankOne(); //bool CheckStack(tpFloat stack); //int NearestStackAlways(tpFloat stack, tpFloat &dist); //void AddStack(tpFloat stack); int WriteFile(int handle); int ReadFile(int handle); size_t SizeInFile(); clHandsGroupEx _gh[2]; clRiverDat _dat; clCard _board[5]; vector <stRiverBankUnitInfo> _info; };*/ class clRiverBankTreeInfo { public: tpFloat Distance(clRiverBankTreeInfo &treeInf) { return _dat.Distance(treeInf._dat); } static int FindNbCenterElement(vector <clRiverBankTreeInfo> arr); int WriteFile(int handle) { _dat.WriteFile(handle); _write(handle, &_maxDist, sizeof(_maxDist)); _write(handle, &_nbRecord, sizeof(_nbRecord)); return 0; } int ReadFile(int handle) { _dat.ReadFile(handle); _read(handle, &_maxDist, sizeof(_maxDist)); _read(handle, &_nbRecord, sizeof(_nbRecord)); return 0; } void Clear(){} clRiverDat _dat; double _maxDist; int _nbRecord; // nb RiverBankCls }; class clRiverBankFastTree : public clBinTree <clRiverBankTreeInfo> { public: clRiverBankFastTree() { clBinTree::clBinTree(); _handle = -1; } ~clRiverBankFastTree() { if(_handle != -1) _close(_handle); } void Init(vector<clRiverBankTreeInfo> &arr); bool IsInit() { return this->_left != NULL; } bool IsEnded() { return this->_left == NULL && this->_right == NULL; } int FastSearch(clRiverDat &dat, tpFloat &dist); clRiverBankFastTree *AddLeftBranch() { return (clRiverBankFastTree *)clBinTree <clRiverBankTreeInfo>::AddLeftBranch(); } clRiverBankFastTree *AddRightBranch() { return (clRiverBankFastTree *)clBinTree <clRiverBankTreeInfo>::AddRightBranch(); } clRiverBankFastTree *Left() { return (clRiverBankFastTree *)_left; } clRiverBankFastTree *Right() { return (clRiverBankFastTree *)_right; } void LoadFromFile() { if (_handle != -1) { _lseek(_handle, 0, SEEK_SET); ReadFile(_handle); } } void SaveToFile() { if (_handle != -1) { _lseek(_handle, 0, SEEK_SET); WriteFile(_handle); } } void GetCenters(int ur, vector <vector <int>> &cls); int _handle; }; struct tpUnfindRiverTree { double _dist; clFileRecT <clInComeDataRoot> _file; }; class clRiverBanks { public: void Create(char *path, int cnRecordU = 100); bool IsOpen() { return _fileUnit.IsOpen(); } bool OpenA(char *path, bool onlyRead, int memGB= SIZE_MB_DEF); void Close() { _fileUnit.CloseFile(); _close(_fastTree._handle); _fastTree._handle = -1; } //int ReadUnit(int nbRec, clRiverBankUnit *unit) { return _fileUnit.ReadRecord(nbRec, unit); } int NearestRiverCls(clRiverDat &dat, tpFloat &dist); //void NearestRiverMultiCls0(clRiverDat &dat, int cn, int *nb); void NearestRiverMultiCls(clRiverDat &dat, int cn, tpIntDouble *nb); clRiverBankUnit *LockBankUnit(int nb) { return _fileUnit.LockRecord(nb); } void UnLockBankUnit(int nb, clRiverBankUnit *unit) { _fileUnit.UnLockRecord(nb); } int FillRiverEVNet(clRootRiverTree *root, vector <float> *ev, clLayersBPNet &net); //int FillRiverEV_(clRootRiverTree *root, int nbHero, vector <float> &ev); int FillRiverEV_(clRootRiverTree *root, vector <float> *ev, tpUnfindRiverTree *ptr); bool FillRiverEV_IP(clRootRiverTree *root, vector <float> *ev, int level); int FillRiverEV_(int nbCls, clRiverDat &datIn, clRootRiverTree *root, vector <float> *ev); void InitFastTree(); int FastSearchR(clRiverDat &dat, double &dist); bool BuildTreeForRoot(clRoot &root, tpUnfindRiverTree *ptr); bool BuildTreeForRootIP(clRootRiverTree &root, int level, tpUnfindRiverTree *ptr); static double GetTreeForRoot(clRootRiverTree &root, clRootRiverTree &rBD, clHoldemTree &tree); static bool GetTreeBD(clRoot &rootIn, clRiverDat &datIn, clRootRiverTree &root, clRiverDat &dat, double mult); //double GetTreeForRoot(clRoot &root, tpUnfindRiverTree *ptr); bool CreateClsForAdd(vector <vector <int>> &cls); void CreateRiverDatMinBD(clRiverDat &dat10, clRiverDat &dat); clFileSwap <clRiverBankUnit> _fileUnit; clRiverBankFastTree _fastTree; vector <clRiverDat> _arr; clLayersBPNet _net; //bool _regNet; }; extern clRiverBanks glBankRiver; void RecalcNbGHForRiver(vector <tpRiverGHUnit> &vectIn, vector <tpRiverGHUnit> &vect, tpTableChangeNb &tab); void RiverBankReCalcEv(clRootRiverTree *root, int nbHero, clRiverDat &datIn, clRiverDat &dat, vector <float> &evIn, vector <float> &ev, double mult); //void FillTreeFromTree(clHoldemTree *nodeIn, clHoldemTree *node, double kSt, tpTableChangeNb *tab, double mult); //void ChangeTreeCls(clHoldemTree *tree, clHandsGroupEx *gh, tpTableChangeNb *tab, double kStack, double mult); //--------------------------------------------------------------------------------------------------------------------------------------------------- #endif
#include "FightingSprite.h" FightingSprite::FightingSprite(int resType, int index) { mCurrentFrame = 1; mImage = NULL; if (resType == DatLib::RES_ACP) // 怪物的 { mImage = (ResImage *)DatLib::GetRes(DatLib::RES_ACP, 3, index); } else if (resType == DatLib::RES_PIC) // 玩家角色的 { mImage = (ResImage*)DatLib::GetRes(DatLib::RES_PIC, 3, index); } else { printf("resType 有错."); } } FightingSprite::~FightingSprite() { if (NULL != mImage) { delete mImage; } } void FightingSprite::draw(Canvas *canvas) { mImage->draw(canvas, mCurrentFrame, mCombatX - mImage->getWidth() / 2, mCombatY - mImage->getHeight() / 2); } void FightingSprite::draw(Canvas *canvas, int x, int y) { mImage->draw(canvas, mCurrentFrame, x, y); } void FightingSprite::setCombatPos(int x, int y) { mCombatX = x; mCombatY = y; } void FightingSprite::move(int dx, int dy) { mCombatX += dx; mCombatY += dy; } int FightingSprite::getCombatX() { return mCombatX; } int FightingSprite::getCombatY() { return mCombatY; } int FightingSprite::getWidth() { return mImage->getWidth(); } int FightingSprite::getHeight() { return mImage->getHeight(); } int FightingSprite::getCurrentFrame() { return mCurrentFrame; } void FightingSprite::setCurrentFrame(int i) { mCurrentFrame = i; } int FightingSprite::getFrameCnt() { return mImage->getNumber(); }
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int s; cin>>s; if(s<1500) cout<<s+(0.1*s)+(0.9*s)<<endl; else cout<<s+500+(0.98*s)<<endl; } return 0; }
#include<iostream> #include<vector> #include<set> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { int size = board.size(); bool subBox[9][9]= {0}; for (int i = 0; i < size; i++) { //1.judge the row int row[9]= {0}; for (int j = 0; j < size; j++) { if (board[i][j] != '.') { int num=board[i][j]-'1'; if (row[num]== 1) return false; row[num]=1; } } //2.judge the column bool col[9]= {0}; for (int j = 0; j < size; j++) { if (board[j][i] != '.') { int num = board[j][i] - '1'; if (col[num] == 1) return false; col[num] = 1; } } //3.judge the cube for (int j = 0; j < size; j++) { if (board[i][j] != '.') { int cubeN = (i / 3) * 3 + j / 3; int num = board[i][j] - '1'; if (subBox[cubeN][num]==1) return false; subBox[cubeN][num] = 1; } }/*for k loop*/ }/*for i loop*/ return true; } };
#include <FastCG/Rendering/MaterialDefinitionRegistry.h> namespace FastCG { MaterialDefinitionRegistry *MaterialDefinitionRegistry::smpInstance = nullptr; }
//$Id: BatchEstimatorInv.cpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // BatchEstimatorInv //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/08/04 // /** * Batch least squares estimator using direct inversion */ //------------------------------------------------------------------------------ #include "BatchEstimatorInv.hpp" #include "MessageInterface.hpp" #include "EstimatorException.hpp" #include <sstream> #include "StringUtil.hpp" #include "DataWriter.hpp" //#define DEBUG_ACCUMULATION //#define DEBUG_ACCUMULATION_RESULTS //#define WALK_STATE_MACHINE //#define DEBUG_VERBOSE //#define DEBUG_WEIGHTS //#define DEBUG_O_MINUS_C //#define DEBUG_SCHUR //#define DEBUG_INVERSION //#define DEBUG_STM //------------------------------------------------------------------------------ // BatchEstimatorInv(const std::string &name) //------------------------------------------------------------------------------ /** * Default constructor * * @param name Name of the instance being constructed */ //------------------------------------------------------------------------------ BatchEstimatorInv::BatchEstimatorInv(const std::string &name): BatchEstimator ("BatchEstimatorInv", name) { objectTypeNames.push_back("BatchEstimatorInv"); } //------------------------------------------------------------------------------ // ~BatchEstimatorInv() //------------------------------------------------------------------------------ /** * Class destructor */ //------------------------------------------------------------------------------ BatchEstimatorInv::~BatchEstimatorInv() { } //------------------------------------------------------------------------------ // BatchEstimatorInv(const BatchEstimatorInv& est) //------------------------------------------------------------------------------ /** * Copy constructor * * @param est The object that is being copied */ //------------------------------------------------------------------------------ BatchEstimatorInv::BatchEstimatorInv(const BatchEstimatorInv& est) : BatchEstimator (est) { } //------------------------------------------------------------------------------ // BatchEstimatorInv& operator=(const BatchEstimatorInv& est) //------------------------------------------------------------------------------ /** * Assignment operator * * @param est The object providing configuration data for this object * * @return This object, configured to match est */ //------------------------------------------------------------------------------ BatchEstimatorInv& BatchEstimatorInv::operator=(const BatchEstimatorInv& est) { if (this != &est) { BatchEstimator::operator=(est); } return *this; } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * Object cloner * * @return Pointer to a new BatchEstimatorInv configured to match this one. */ //------------------------------------------------------------------------------ GmatBase* BatchEstimatorInv::Clone() const { return new BatchEstimatorInv(*this); } //--------------------------------------------------------------------------- // void Copy(const GmatBase* orig) //--------------------------------------------------------------------------- /** * Sets this object to match another one. * * @param orig The original that is being copied. */ //--------------------------------------------------------------------------- void BatchEstimatorInv::Copy(const GmatBase* orig) { operator=(*((BatchEstimatorInv*)(orig))); } //------------------------------------------------------------------------------ // void Accumulate() //------------------------------------------------------------------------------ /** * This method collects the data needed for estimation. */ //------------------------------------------------------------------------------ void BatchEstimatorInv::Accumulate() { #ifdef WALK_STATE_MACHINE MessageInterface::ShowMessage("BatchEstimator state is ACCUMULATING\n"); #endif #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("Entered BatchEstimatorInv::Accumulate()\n"); #endif // Measurements are possible! const MeasurementData *calculatedMeas = NULL; std::vector<RealArray> stateDeriv; // .mat file indices Integer matIndex; for (UnsignedInt i = 0; i < hTilde.size(); ++i) hTilde[i].clear(); hTilde.clear(); // Get state map, measurement models, and measurement data const std::vector<ListItem*> *stateMap = esm.GetStateMap(); modelsToAccess = measManager.GetValidMeasurementList(); // Get valid measurement models const ObservationData *currentObs = measManager.GetObsData(); // Get current observation data // Get ground station and measurement type from current observation data std::string gsName = currentObs->participantIDs[0]; std::string typeName = currentObs->typeName; std::string keyword = gsName + " " + typeName; bool found = false; UnsignedInt indexKey = 0; for (; indexKey < stationAndType.size(); ++indexKey) { if (stationAndType[indexKey] == keyword) { sumAllRecords[indexKey] += 1; // count for the total records found = true; break; } } if (!found) { // create a statistics record for a new combination of station and measuement type stationAndType.push_back(keyword); stationsList.push_back(gsName); measTypesList.push_back(typeName); sumAllRecords.push_back(1); // set total records to 1 at the first time sumAcceptRecords.push_back(0); sumResidual.push_back(0.0); sumResidualSquare.push_back(0.0); sumWeightResidualSquare.push_back(0.0); sumSERecords.push_back(0); sumSEResidual.push_back(0.0); sumSEResidualSquare.push_back(0.0); sumSEWeightResidualSquare.push_back(0.0); } // Set initial value for 2 statistics tables if (statisticsTable["TOTAL NUM RECORDS"].find(keyword) == statisticsTable["TOTAL NUM RECORDS"].end()) statisticsTable["TOTAL NUM RECORDS"][keyword] = 0.0; if (statisticsTable["ACCEPTED RECORDS"].find(keyword) == statisticsTable["ACCEPTED RECORDS"].end()) statisticsTable["ACCEPTED RECORDS"][keyword] = 0.0; if (statisticsTable["WEIGHTED RMS"].find(keyword) == statisticsTable["WEIGHTED RMS"].end()) statisticsTable["WEIGHTED RMS"][keyword] = 0.0; if (statisticsTable["MEAN RESIDUAL"].find(keyword) == statisticsTable["MEAN RESIDUAL"].end()) statisticsTable["MEAN RESIDUAL"][keyword] = 0.0; if (statisticsTable["STANDARD DEVIATION"].find(keyword) == statisticsTable["STANDARD DEVIATION"].end()) statisticsTable["STANDARD DEVIATION"][keyword] = 0.0; if (statisticsTable1["TOTAL NUM RECORDS"].find(typeName) == statisticsTable1["TOTAL NUM RECORDS"].end()) statisticsTable1["TOTAL NUM RECORDS"][typeName] = 0.0; if (statisticsTable1["ACCEPTED RECORDS"].find(typeName) == statisticsTable1["ACCEPTED RECORDS"].end()) statisticsTable1["ACCEPTED RECORDS"][typeName] = 0.0; if (statisticsTable1["WEIGHTED RMS"].find(typeName) == statisticsTable1["WEIGHTED RMS"].end()) statisticsTable1["WEIGHTED RMS"][typeName] = 0.0; if (statisticsTable1["MEAN RESIDUAL"].find(typeName) == statisticsTable1["MEAN RESIDUAL"].end()) statisticsTable1["MEAN RESIDUAL"][typeName] = 0.0; if (statisticsTable1["STANDARD DEVIATION"].find(typeName) == statisticsTable1["STANDARD DEVIATION"].end()) statisticsTable1["STANDARD DEVIATION"][typeName] = 0.0; // count total number of observation data for a pair of groundstation and measurement type statisticsTable["TOTAL NUM RECORDS"][keyword] += 1; statisticsTable1["TOTAL NUM RECORDS"][typeName] += 1; #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("StateMap size is %d\n", stateMap->size()); MessageInterface::ShowMessage("Found %d models\n", modelsToAccess.size()); MessageInterface::ShowMessage("Observation data O: epoch = %.12lf type = <%s>", currentObs->epoch, currentObs->typeName.c_str()); for(UnsignedInt i=0; i < currentObs->participantIDs.size(); ++i) MessageInterface::ShowMessage(" %s", currentObs->participantIDs[i].c_str()); MessageInterface::ShowMessage(" O = %.12lf", currentObs->value[0]); if ((currentObs->typeName == "DSNRange")||(currentObs->typeName == "DSNTwoWayRange")) MessageInterface::ShowMessage(" range modulo = %lf\n", currentObs->rangeModulo); MessageInterface::ShowMessage("\n"); #endif std::stringstream sLine; char s[1000]; std::string times; Real temp; // Verify measurement epoch is inside of EOP time range if ((currentObs->epoch < eopTimeMin) || (currentObs->epoch > eopTimeMax)) { if (warningCount == 0) MessageInterface::ShowMessage("Warning: measurement epoch %.12lf A1Mjd is outside EOP time range [%.12lf A1Mjd, %.12lf A1Mjd]\n", currentObs->epoch, eopTimeMin, eopTimeMax); ++warningCount; } // Write to report file iteration number, record number, and time: TimeConverterUtil::Convert("A1ModJulian", currentObs->epoch, "", "UTCGregorian", temp, times, 1); if (textFileMode == "Normal") { sprintf(&s[0], "%4d %6d %s ", iterationsTaken, measManager.GetCurrentRecordNumber(), times.c_str()); } else { Real timeTAI = TimeConverterUtil::Convert(currentObs->epoch, currentObs->epochSystem, TimeConverterUtil::TAIMJD); sprintf(&s[0], "%4d %6d %s %.12lf ", iterationsTaken, measManager.GetCurrentRecordNumber(), times.c_str(), timeTAI); } sLine << s; if (writeMatFile && (matWriter != NULL)) { std::string gregEpoch; Real taiEpoch; TimeConverterUtil::Convert("A1ModJulian", currentObs->epoch, "", "TAIModJulian", taiEpoch, gregEpoch, 1); TimeConverterUtil::Convert("A1ModJulian", currentObs->epoch, "", "UTCGregorian", temp, gregEpoch, 1); if (matEpochIndex == -1) { matIterationIndex = matData.AddRealContainer("IterationNumber"); matEpochIndex = matData.AddRealContainer("Epoch"); matObsIndex = matData.AddRealContainer("Observed"); matCalcIndex = matData.AddRealContainer("Calculated"); matOmcIndex = matData.AddRealContainer("ObsMinusCalc"); matElevationIndex = matData.AddRealContainer("Elevation"); matPartIndex = matData.AddStringContainer("Participants"); matTypeIndex = matData.AddStringContainer("Type"); matGregorianIndex = matData.AddStringContainer("UTCGregorian"); matObsEditFlagIndex = matData.AddStringContainer("ObsEditFlag"); matFrequencyIndex = matData.AddRealContainer("Frequency"); matFreqBandIndex = matData.AddRealContainer("FrequencyBand"); matDoppCountIndex = matData.AddRealContainer("DopplerCountInterval"); } matIndex = matData.AddPoint(); matData.elementStatus[matIndex] = 0.0; matData.realValues[matIterationIndex][matIndex] = iterationsTaken; matData.realValues[matEpochIndex][matIndex] = taiEpoch; matData.realValues[matObsIndex][matIndex] = currentObs->value[0]; std::string parties; for (UnsignedInt n = 0; n < currentObs->participantIDs.size(); ++n) parties = parties + currentObs->participantIDs[n] + (((n + 1) == currentObs->participantIDs.size()) ? "" : ","); matData.stringValues[matPartIndex][matIndex] = parties; matData.stringValues[matTypeIndex][matIndex] = currentObs->typeName; matData.stringValues[matGregorianIndex][matIndex] = gregEpoch; } std::string ss; if (textFileMode == "Normal") { // Write to report file measurement type name: sLine << GmatStringUtil::GetAlignmentString(currentObs->typeName, 19) + " "; // Write to report file all participants in signal path: ss = ""; for (UnsignedInt n = 0; n < currentObs->participantIDs.size(); ++n) ss = ss + currentObs->participantIDs[n] + (((n + 1) == currentObs->participantIDs.size()) ? "" : ","); sLine << GmatStringUtil::GetAlignmentString(GmatStringUtil::Trim(ss), pcolumnLen) + " "; } else { // Write to report file measurement type name and its unit: sLine << GmatStringUtil::GetAlignmentString(currentObs->typeName, 19) + " "; sLine << GmatStringUtil::GetAlignmentString(currentObs->unit, 6) << " "; // Write to report file all participants in signal path: ss = ""; for (UnsignedInt n = 0; n < currentObs->participantIDs.size(); ++n) ss = ss + currentObs->participantIDs[n] + (((n + 1) == currentObs->participantIDs.size()) ? "" : ","); sLine << GmatStringUtil::GetAlignmentString(ss, pcolumnLen) + " "; } if (modelsToAccess.size() == 0) { // Count number of records removed by measurement model unmatched numRemovedRecords["U"]++; measManager.GetObsDataObject()->inUsed = false; measManager.GetObsDataObject()->removedReason = "U"; if (textFileMode == "Normal") { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(measManager.GetObsDataObject()->removedReason, 4) + " "; // Write to report file O-value, C-value, O-C, and elevation angle sprintf(&s[0], "%21.6lf", currentObs->value[0]); sLine << s << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 20, GmatStringUtil::RIGHT) << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 6, GmatStringUtil::RIGHT); sLine << "\n"; } else { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(measManager.GetObsDataObject()->removedReason, 4, GmatStringUtil::LEFT) + " "; // Edit status // Write to report file O-value, C-value, O-C, unit, and elevation angle sprintf(&s[0], "%21.6lf %21.6lf", currentObs->value_orig[0], currentObs->value[0]); sLine << s << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // C-value sLine << GmatStringUtil::GetAlignmentString("N/A", 18, GmatStringUtil::RIGHT) << " "; // O-C sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // W sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // W*(O-C)^2 sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // sqrt(W)*|O-C| sLine << GmatStringUtil::GetAlignmentString("N/A", 18, GmatStringUtil::RIGHT) << " "; // elevation angle // fill out N/A for partial derivative for (int i = 0; i < stateMap->size(); ++i) sLine << GmatStringUtil::GetAlignmentString("N/A", 19, GmatStringUtil::RIGHT) << " "; // derivative if ((currentObs->typeName == "DSNTwoWayRange") || (currentObs->typeName == "DSNRange")) sprintf(&s[0], " %d %.15le %.15le N/A", currentObs->uplinkBand, currentObs->uplinkFreqAtRecei, currentObs->rangeModulo); else if ((currentObs->typeName == "DSNTwoWayDoppler")||(currentObs->typeName == "Doppler")||(currentObs->typeName == "Doppler_RangeRate")) sprintf(&s[0]," %d N/A N/A %.4lf", currentObs->uplinkBand, currentObs->dopplerCountInterval); else sprintf(&s[0]," N/A N/A N/A N/A"); sLine << s; sLine << "\n"; } } else { int count = measManager.Calculate(modelsToAccess[0], true); calculatedMeas = measManager.GetMeasurement(modelsToAccess[0]); // verify media correction to be in acceptable range. It is [0m, 60m] for troposphere correction and [0m, 20m] for ionosphere correction ValidateMediaCorrection(calculatedMeas); if (count == 0) { std::string ss = measManager.GetObsDataObject()->removedReason = calculatedMeas->unfeasibleReason; if (ss.substr(0,1) == "B") numRemovedRecords["B"]++; else numRemovedRecords[ss]++; if (textFileMode == "Normal") { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; // Write to report file O-value, C-value, O-C, unit, and elevation angle sprintf(&s[0], "%21.6lf", currentObs->value[0]); sLine << s << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 20, GmatStringUtil::RIGHT) << " "; // write elevation angle sprintf(&s[0], "%6.2lf", calculatedMeas->feasibilityValue); sLine << s; sLine << "\n"; } else { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; // Write C, O-C, W, W*(O-C)^2, sqrt(W)*(O-C), and elevation angle sprintf(&s[0], "%21.6lf %21.6lf", currentObs->value_orig[0], currentObs->value[0]); sLine << s << " "; sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // C-value sLine << GmatStringUtil::GetAlignmentString("N/A", 18, GmatStringUtil::RIGHT) << " "; // O-C sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // W sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // W*(O-C)^2 sLine << GmatStringUtil::GetAlignmentString("N/A", 21, GmatStringUtil::RIGHT) << " "; // sqrt(W)*|O-C| sprintf(&s[0], "%18.12lf", calculatedMeas->feasibilityValue); sLine << s << " "; // elevation angle // fill out N/A for partial derivative for (int i = 0; i < stateMap->size(); ++i) sLine << GmatStringUtil::GetAlignmentString("N/A", 19, GmatStringUtil::RIGHT) << " "; // derivative if ((currentObs->typeName == "DSNTwoWayRange")||(currentObs->typeName == "DSNRange")) sprintf(&s[0]," %d %.15le %.15le N/A", currentObs->uplinkBand, currentObs->uplinkFreqAtRecei, currentObs->rangeModulo); else if ((currentObs->typeName == "DSNTwoWayDoppler")||(currentObs->typeName == "Doppler")||(currentObs->typeName == "Doppler_RangeRate")) sprintf(&s[0]," %d N/A N/A %.4lf", currentObs->uplinkBand, currentObs->dopplerCountInterval); else sprintf(&s[0]," N/A N/A N/A N/A"); sLine << s; sLine << "\n"; } } else // (count >= 1) { // Currently assuming uniqueness; modify if more than 1 possible here // Case: ((modelsToAccess.size() > 0) && (measManager.Calculate(modelsToAccess[0], true) >= 1)) // It has to make correction for observation value before running data filter if ((iterationsTaken == 0)&&((currentObs->typeName == "DSNTwoWayRange")||(currentObs->typeName == "DSNRange"))) { // value correction is only applied for DSNTwoWayRange and it is only performed at the first time for (Integer index = 0; index < currentObs->value.size(); ++index) measManager.GetObsDataObject()->value[index] = ObservationDataCorrection(calculatedMeas->value[index], currentObs->value[index], currentObs->rangeModulo); } bool isReUsed = DataFilter(); #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("iterationsTaken = %d inUsed = %s\n", iterationsTaken, (measManager.GetObsDataObject()->inUsed ? "true" : "false")); #endif if (measManager.GetObsDataObject()->inUsed == false) { // Specify removed reason and count number of removed records std::string ss = measManager.GetObsDataObject()->removedReason; //currentObs->removedReason; if (ss.substr(0,1) == "B") numRemovedRecords["B"]++; else numRemovedRecords[ss]++; Real ocDiff = currentObs->value[0]-calculatedMeas->value[0]; Real weight; if ((*(calculatedMeas->covariance))(0,0) != 0.0) weight = 1.0 / (*(calculatedMeas->covariance))(0,0); else weight = 1.0; if (textFileMode == "Normal") { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; // Write O-value, C-value, and O-C sprintf(&s[0], "%21.6lf %21.6lf %20.6lf ", currentObs->value[0], calculatedMeas->value[0], ocDiff); sLine << s << " "; // write elevation angle sprintf(&s[0], "%6.2lf", calculatedMeas->feasibilityValue); sLine << s; sLine << "\n"; } else { // Write to report file edit status: sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; // Write C, O-C, W, W*(O-C)^2, sqrt(W)*(O-C), and elevation angle sprintf(&s[0], "%21.6lf %21.6lf %21.6lf %18.6lf %21.12le %21.12le %21.12le %18.12lf", currentObs->value_orig[0], currentObs->value[0], calculatedMeas->value[0], ocDiff, weight, ocDiff*ocDiff*weight, sqrt(weight)*abs(ocDiff), calculatedMeas->feasibilityValue); sLine << s << " "; // fill out N/A for partial derivative for (int i = 0; i < stateMap->size(); ++i) sLine << GmatStringUtil::GetAlignmentString("N/A", 19, GmatStringUtil::RIGHT) << " "; // derivative if ((currentObs->typeName == "DSNTwoWayRange")||(currentObs->typeName == "DSNRange")) sprintf(&s[0]," %d %.15le %.15le N/A", currentObs->uplinkBand, currentObs->uplinkFreqAtRecei, currentObs->rangeModulo); else if ((currentObs->typeName == "DSNTwoWayDoppler")||(currentObs->typeName == "Doppler")||(currentObs->typeName == "Doppler_RangeRate")) sprintf(&s[0]," %d N/A N/A %.4lf", currentObs->uplinkBand, currentObs->dopplerCountInterval); else sprintf(&s[0]," N/A N/A N/A N/A"); sLine << s; sLine << "\n"; } // Write the .mat data if (writeMatFile && (matWriter != NULL)) { matData.realValues[matCalcIndex][matIndex] = calculatedMeas->value[0]; matData.realValues[matOmcIndex][matIndex] = ocDiff; matData.stringValues[matObsEditFlagIndex][matIndex] = ss; } // Reset value for removed reason for all reuseable data records if (isReUsed) { measManager.GetObsDataObject()->inUsed = true; measManager.GetObsDataObject()->removedReason = "N"; } } else { RealArray hTrow; hTrow.assign(stateSize, 0.0); UnsignedInt rowCount = calculatedMeas->value.size(); for (UnsignedInt i = 0; i < rowCount; ++i) hTilde.push_back(hTrow); // Now walk the state vector and get elements of H-tilde for each piece for (UnsignedInt i = 0; i < stateMap->size(); ++i) { if ((*stateMap)[i]->subelement == 1) { #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage( " Calculating ddstate(%d) for %s, subelement %d of %d, " "id = %d\n", i, (*stateMap)[i]->elementName.c_str(), (*stateMap)[i]->subelement, (*stateMap)[i]->length, (*stateMap)[i]->elementID); MessageInterface::ShowMessage("object = <%p '%s'>\n", (*stateMap)[i]->object, (*stateMap)[i]->object->GetName().c_str()); #endif // Partial derivatives at measurement time tm stateDeriv = measManager.CalculateDerivatives( (*stateMap)[i]->object, (*stateMap)[i]->elementID, modelsToAccess[0]); // Fill in the corresponding elements of hTilde for (UnsignedInt j = 0; j < rowCount; ++j) for (UnsignedInt k = 0; k < (*stateMap)[i]->length; ++k) hTilde[j][i+k] = stateDeriv[j][k]; // hTilde is partial derivates at measurement time tm (not at aprioi time t0) #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage(" Result:\n "); for (UnsignedInt l = 0; l < stateDeriv.size(); ++l) { for (UnsignedInt m = 0; m < (*stateMap)[i]->length; ++m) MessageInterface::ShowMessage("%.12lf ", stateDeriv[l][m]); MessageInterface::ShowMessage("\n "); } MessageInterface::ShowMessage("\n"); #endif } } // Apply the STM #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("Applying the STM\n"); #endif RealArray hRow; // Temporary buffer for non-scalar measurements; hMeas is used to build // the information matrix below. std::vector<RealArray> hMeas; #ifdef DEBUG_STM MessageInterface::ShowMessage("STM:\n"); for (UnsignedInt j = 0; j < stateMap->size(); ++j) { MessageInterface::ShowMessage(" ["); for (UnsignedInt k = 0; k < stateMap->size(); ++k) { MessageInterface::ShowMessage(" %le ", (*stm)(j,k)); } MessageInterface::ShowMessage("]\n"); } #endif Real entry; for (UnsignedInt i = 0; i < hTilde.size(); ++i) { hRow.assign(stateMap->size(), 0.0); // hRow is partial derivaties at apriori time t0 for (UnsignedInt j = 0; j < stateMap->size(); ++j) { entry = 0.0; for (UnsignedInt k = 0; k < stateMap->size(); ++k) { entry += hTilde[i][k] * (*stm)(k, j); } hRow[j] = entry; } hAccum.push_back(hRow); // each element of hAccum is a vector partial derivative hMeas.push_back(hRow); #ifdef DEBUG_ACCUMULATION_RESULTS MessageInterface::ShowMessage(" Htilde = ["); for (UnsignedInt l = 0; l < stateMap->size(); ++l) MessageInterface::ShowMessage( " %.12lf ", hTilde[i][l]); MessageInterface::ShowMessage( "]\n"); MessageInterface::ShowMessage(" H accum = ["); for (UnsignedInt l = 0; l < stateMap->size(); ++l) MessageInterface::ShowMessage( " %.12lf ", hRow[l]); MessageInterface::ShowMessage( "]\n"); MessageInterface::ShowMessage(" H has %d rows\n", hAccum.size()); #endif } Real ocDiff; Real weight; #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("Accumulating the O-C differences\n"); MessageInterface::ShowMessage(" Obs size = %d, calc size = %d\n", currentObs->value.size(), calculatedMeas->value.size()); #endif for (UnsignedInt k = 0; k < currentObs->value.size(); ++k) { // Calculate residual O-C ocDiff = currentObs->value[k] - calculatedMeas->value[k]; #ifdef DEBUG_O_MINUS_C Real OD_Epoch = TimeConverterUtil::Convert(currentObs->epoch, TimeConverterUtil::A1MJD, TimeConverterUtil::TAIMJD, GmatTimeConstants::JD_JAN_5_1941); Real C_Epoch = TimeConverterUtil::Convert(calculatedMeas->epoch, TimeConverterUtil::A1MJD, TimeConverterUtil::TAIMJD, GmatTimeConstants::JD_JAN_5_1941); MessageInterface::ShowMessage("Observation data: %s %s %s Epoch = %.12lf O = %.12le; Calculated measurement: %s %s Epoch = %.12lf C = %.12le; O-C = %.12le frequency = %.12le\n", currentObs->typeName.c_str(), currentObs->participantIDs[0].c_str(), currentObs->participantIDs[1].c_str(), OD_Epoch, currentObs->value[k], calculatedMeas->participantIDs[0].c_str(), calculatedMeas->participantIDs[1].c_str(), C_Epoch, calculatedMeas->value[k], ocDiff, calculatedMeas->uplinkFreq); #endif measurementEpochs.push_back(currentEpoch); OData.push_back(currentObs->value[k]); CData.push_back(calculatedMeas->value[k]); measurementResiduals.push_back(ocDiff); measurementResidualID.push_back(calculatedMeas->uniqueID); // Calculate weight weight = 1.0; if (currentObs->noiseCovariance == NULL) { #ifdef DEBUG_WEIGHTS MessageInterface::ShowMessage("Measurement covariance(%d %d) " "is %le\n", k, k, (*(calculatedMeas->covariance))(k,k)); #endif // todo: Figure out why the covariances can be 0.0!?! if ((*(calculatedMeas->covariance))(k,k) != 0.0) // Weight is diag(1 / sigma^2), per Montebruck & Gill, eq. 8.33 // Covariance diagonal is ~diag(sigma^2) // If no off diagonal terms, inverse in 1/element along diagonal weight = 1.0 / (*(calculatedMeas->covariance))(k,k); else weight = 1.0; } else { weight = 1.0 / (*(currentObs->noiseCovariance))(k,k); #ifdef DEBUG_WEIGHTS MessageInterface::ShowMessage("Noise covariance(%d %d) " "is %le\n", k, k, (*(currentObs->noiseCovariance))(k,k)); #endif } Weight.push_back(weight); for (UnsignedInt i = 0; i < stateSize; ++i) { for (UnsignedInt j = 0; j < stateSize; ++j) //information(i,j) += hRow[i] * weight * hRow[j]; information(i,j) += hMeas[k][i] * weight * hMeas[k][j]; // the first term in open-close square bracket of equation 8-57 in GTDS MathSpec //residuals[i] += hRow[i] * weight * ocDiff; residuals[i] += hMeas[k][i] * weight * ocDiff; // the first term in open-close parenthesis of equation 8-57 in GTDS MathSpec } // Write report for this observation data for case data record is removed std::string ss = currentObs->removedReason; if (textFileMode == "Normal") { // Write to report file edit status: if (ss == "N") sLine << GmatStringUtil::GetAlignmentString("-", 4, GmatStringUtil::LEFT) + " "; else sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; // Write to report file O-value, C-value, O-C, sprintf(&s[0], "%21.6lf %21.6lf %20.6lf", currentObs->value[k], calculatedMeas->value[k], ocDiff); sLine << s << " "; // Write to report file elevation angle: sprintf(&s[0], "%6.2lf", calculatedMeas->feasibilityValue); sLine << s; sLine << "\n"; } else { // Write to report file edit status: if (ss == "N") sLine << GmatStringUtil::GetAlignmentString("-", 4, GmatStringUtil::LEFT) + " "; else sLine << GmatStringUtil::GetAlignmentString(ss, 4, GmatStringUtil::LEFT) + " "; sprintf(&s[0], "%21.6lf %21.6lf %21.6lf %18.6lf %21.12le %21.12le %21.12le %18.12lf", currentObs->value_orig[k], currentObs->value[k], calculatedMeas->value[k], ocDiff, weight, ocDiff*ocDiff*weight, sqrt(weight)*abs(ocDiff), calculatedMeas->feasibilityValue); sLine << s << " "; // fill out N/A for partial derivative for (UnsignedInt p = 0; p < hAccum[hAccum.size()-1].size(); ++p) { Real derivative = hAccum[hAccum.size()-1][p]; if ((*stateMap)[p]->elementName == "Cr_Epsilon") { Real Cr = (*stateMap)[p]->object->GetRealParameter("Cr") / (1 + (*stateMap)[p]->object->GetRealParameter("Cr_Epsilon")); derivative = derivative/ Cr; } else if ((*stateMap)[p]->elementName == "Cd_Epsilon") { Real Cd = (*stateMap)[p]->object->GetRealParameter("Cd") / (1 + (*stateMap)[p]->object->GetRealParameter("Cd_Epsilon")); derivative = derivative/Cd; } sLine << GmatStringUtil::GetAlignmentString(GmatStringUtil::RealToString(derivative, false, true, true, 10, 19), 19, GmatStringUtil::RIGHT) << " "; } if ((currentObs->typeName == "DSNTwoWayRange")||(currentObs->typeName == "DSNRange")) sprintf(&s[0]," %d %.15le %.15le N/A", currentObs->uplinkBand, currentObs->uplinkFreqAtRecei, currentObs->rangeModulo); else if ((currentObs->typeName == "DSNTwoWayDoppler")||(currentObs->typeName == "Doppler")||(currentObs->typeName == "Doppler_RangeRate")) sprintf(&s[0]," %d N/A N/A %.4lf", currentObs->uplinkBand, currentObs->dopplerCountInterval); else sprintf(&s[0]," N/A N/A N/A N/A"); sLine << s; sLine << "\n"; } } // Count number of observation data accepted for estimation calculation statisticsTable["ACCEPTED RECORDS"][keyword] += 1; statisticsTable["WEIGHTED RMS"][keyword] += weight*ocDiff*ocDiff; // sum of weighted residual square statisticsTable["MEAN RESIDUAL"][keyword] += ocDiff; // sum of residual statisticsTable["STANDARD DEVIATION"][keyword] += ocDiff*ocDiff; // sum of residual square statisticsTable1["ACCEPTED RECORDS"][typeName] += 1; statisticsTable1["WEIGHTED RMS"][typeName] += weight*ocDiff*ocDiff; // sum of weighted residual square statisticsTable1["MEAN RESIDUAL"][typeName] += ocDiff; // sum of residual statisticsTable1["STANDARD DEVIATION"][typeName] += ocDiff*ocDiff; // sum of residual square sumAcceptRecords[indexKey] += 1; // sum of all accepted records sumResidual[indexKey] += ocDiff; // sum of residual Real ocDiff2 = ocDiff*ocDiff; sumResidualSquare[indexKey] += ocDiff2; // sum of residual square sumWeightResidualSquare[indexKey] += weight*ocDiff2; // sum of weigth residual square #ifdef DEBUG_ACCUMULATION_RESULTS MessageInterface::ShowMessage("Observed measurement value:\n"); for (UnsignedInt k = 0; k < currentObs->value.size(); ++k) MessageInterface::ShowMessage(" %.12lf", currentObs->value[k]); MessageInterface::ShowMessage("\n"); MessageInterface::ShowMessage("Calculated measurement value:\n"); for (UnsignedInt k = 0; k < calculatedMeas->value.size(); ++k) MessageInterface::ShowMessage(" %.12lf",calculatedMeas->value[k]); MessageInterface::ShowMessage("\n"); MessageInterface::ShowMessage(" O - C = "); for (UnsignedInt k = 0; k < calculatedMeas->value.size(); ++k) MessageInterface::ShowMessage(" %.12lf", currentObs->value[k] - calculatedMeas->value[k]); MessageInterface::ShowMessage("\n"); MessageInterface::ShowMessage("Derivatives w.r.t. state (H-tilde):\n"); for (UnsignedInt k = 0; k < hTilde.size(); ++k) { for (UnsignedInt l = 0; l < hTilde[k].size(); ++l) MessageInterface::ShowMessage(" %.12lf",hTilde[k][l]); MessageInterface::ShowMessage("\n"); } MessageInterface::ShowMessage(" Information Matrix = \n"); for (Integer i = 0; i < estimationState->GetSize(); ++i) { MessageInterface::ShowMessage(" ["); for (Integer j = 0; j < estimationState->GetSize(); ++j) { MessageInterface::ShowMessage(" %.12lf ", information(i, j)); } MessageInterface::ShowMessage("]\n"); } MessageInterface::ShowMessage(" Residuals = ["); for (Integer i = 0; i < residuals.GetSize(); ++i) MessageInterface::ShowMessage(" %.12lf ", residuals[i]); MessageInterface::ShowMessage("]\n"); #endif if (writeMatFile && (matWriter != NULL)) { matData.elementStatus[matIndex] = 1.0; matData.realValues[matCalcIndex][matIndex] = calculatedMeas->value[0]; matData.realValues[matOmcIndex][matIndex] = ocDiff; } } // end of if (measManager.GetObsDataObject()->inUsed) } // end of if (count >= 1) } // end of if (modelsToAccess.size() == 0) if (writeMatFile && (matWriter != NULL)) { if (matData.stringValues[matObsEditFlagIndex][matIndex] == "N/A") matData.stringValues[matObsEditFlagIndex][matIndex] = currentObs->removedReason; if (calculatedMeas) matData.realValues[matElevationIndex][matIndex] = calculatedMeas->feasibilityValue; if ((currentObs->typeName == "DSNTwoWayRange")||(currentObs->typeName == "DSNRange")) { matData.realValues[matFreqBandIndex][matIndex] = currentObs->uplinkBand; matData.realValues[matFrequencyIndex][matIndex] = currentObs->uplinkFreqAtRecei; } else if ((currentObs->typeName == "DSNTwoWayDoppler") || (currentObs->typeName == "Doppler") || (currentObs->typeName == "Doppler_RangeRate")) { matData.realValues[matFreqBandIndex][matIndex] = currentObs->uplinkBand; matData.realValues[matDoppCountIndex][matIndex] = currentObs->dopplerCountInterval; } } linesBuff = sLine.str(); WriteToTextFile(currentState); // Accumulate the processed data #ifdef RUN_SINGLE_PASS #ifdef SHOW_STATE_TRANSITIONS MessageInterface::ShowMessage("BatchEstimator state is ESTIMATING at " "epoch %.12lf\n", currentEpoch); #endif #endif #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("Advancing to the next measurement\n"); #endif // Advance to the next measurement and get its epoch bool isEndOfTable = measManager.AdvanceObservation(); if (isEndOfTable) currentState = ESTIMATING; else { nextMeasurementEpoch = measManager.GetEpoch(); FindTimeStep(); if (currentEpoch <= (nextMeasurementEpoch + 5.0e-12)) // It needs to add 5.0e-12 in order to avoid accuracy limit of double currentState = PROPAGATING; else currentState = ESTIMATING; } #ifdef DEBUG_ACCUMULATION MessageInterface::ShowMessage("Exit BatchEstimatorInv::Accumulate()\n"); #endif } //------------------------------------------------------------------------------ // void Estimate() //------------------------------------------------------------------------------ /** * This method solves the normal equations using direct inversion */ //------------------------------------------------------------------------------ void BatchEstimatorInv::Estimate() { #ifdef WALK_STATE_MACHINE MessageInterface::ShowMessage("BatchEstimator state is ESTIMATING\n"); #endif // Plot all residuals if (showAllResiduals) PlotResiduals(); // Display number of removed records for each type of filters if (!numRemovedRecords.empty()) { MessageInterface::ShowMessage("Number of Records Removed Due To:\n"); MessageInterface::ShowMessage(" . No Computed Value Configuration Available : %d\n", numRemovedRecords["U"]); MessageInterface::ShowMessage(" . Out of Ramp Table Range : %d\n", numRemovedRecords["R"]); MessageInterface::ShowMessage(" . Signal Blocked : %d\n", numRemovedRecords["B"]); MessageInterface::ShowMessage(" . Initial RMS Sigma Filter : %d\n", numRemovedRecords["IRMS"]); MessageInterface::ShowMessage(" . Outer-Loop Sigma Editor : %d\n", numRemovedRecords["OLSE"]); } MessageInterface::ShowMessage("Number of records used for estimation: %d\n", measurementResiduals.size()); if (measurementResiduals.size() < esm.GetStateMap()->size()) { std::stringstream ss; ss << "Error: For Batch estimator " << GetName() << ", there are " << esm.GetStateMap()->size() << " solve-for parameters, and only " << measurementResiduals.size() << " valid observable records remaining after editing. Please modify data editing criteria or provide a better a-priori estimate.\n"; throw EstimatorException(ss.str()); } // Apriori state (initial state for 0th iteration) and initial state for current iteration: if (iterationsTaken == 0) initialEstimationState = (*estimationState); oldEstimationState = (*estimationState); // Convert previous state from GMAT internal coordinate system to participants' coordinate system GetEstimationStateForReport(previousSolveForState); // Specify previous, current, and the best weighted RMS: // Calculate RMSOLD: if (iterationsTaken > 0) oldResidualRMS = newResidualRMS; // old value is only valid from 1st iteration // Calculate RMS: Equation 8-184 GTDS MathSpec newResidualRMS = 0.0; if (useApriori) { // The last term of RMSP in equation 8-185 in GTDS MathSpec GmatState currentEstimationState = (*estimationState); Rmatrix Pdx0_inv; try { Pdx0_inv = stateCovariance->GetCovariance()->Inverse(); // inverse of the initial estimation error covariance matrix //MessageInterface::ShowMessage("Apriori covariance matrix:\n["); //for (Integer row = 0; row < Pdx0_inv.GetNumRows(); ++row) //{ // for (Integer col = 0; col < Pdx0_inv.GetNumColumns(); ++col) // MessageInterface::ShowMessage("%le ", Pdx0_inv.GetElement(row, col)); // if (row < Pdx0_inv.GetNumRows() - 1) // MessageInterface::ShowMessage("\n"); //} //MessageInterface::ShowMessage("]\n"); } catch (...) { MessageInterface::ShowMessage("Apriori covariance matrix:\n["); for (Integer row = 0; row < stateCovariance->GetDimension(); ++row) { for (Integer col = 0; col < stateCovariance->GetDimension(); ++col) MessageInterface::ShowMessage("%le ", stateCovariance->GetCovariance()->GetElement(row, col)); if (row < stateCovariance->GetDimension() - 1) MessageInterface::ShowMessage("\n"); } MessageInterface::ShowMessage("]\n"); throw EstimatorException("Error: Apriori covariance matrix is singular. GMAT cannot take inverse of that matrix.\n"); } for (UnsignedInt i = 0; i < stateSize; ++i) { for (UnsignedInt j = 0; j < stateSize; ++j) newResidualRMS += (currentEstimationState[i] - initialEstimationState[i])*Pdx0_inv(i, j)*(currentEstimationState[j] - initialEstimationState[j]); // The second term inside square brackets of equation 8-184 GTDS MathSpec } } for (int i = 0; i < measurementResiduals.size(); ++i) newResidualRMS += measurementResiduals[i] * measurementResiduals[i]*Weight[i]; if (useApriori) newResidualRMS = GmatMathUtil::Sqrt(newResidualRMS / (measurementResiduals.size()+1)); else newResidualRMS = GmatMathUtil::Sqrt(newResidualRMS / measurementResiduals.size()); // Calculate RMSB: if (iterationsTaken == 0) bestResidualRMS = newResidualRMS; else { //// Reset best RMS as needed // fix bug GMT-5711 //if (resetBestRMSFlag) // fix bug GMT-5711 //{ // fix bug GMT-5711 // if (estimationStatus == DIVERGING) // fix bug GMT-5711 // bestResidualRMS = oldResidualRMS; // fix bug GMT-5711 //} // fix bug GMT-5711 bestResidualRMS = GmatMathUtil::Min(bestResidualRMS, newResidualRMS); } // Solve normal equation #ifdef DEBUG_VERBOSE MessageInterface::ShowMessage("Accumulation complete; now solving the " "normal equations!\n"); MessageInterface::ShowMessage("\nEstimating changes for iteration %d\n\n", iterationsTaken+1); MessageInterface::ShowMessage(" Presolution estimation state:\n " "epoch = %.12lf\n [", estimationState->GetEpoch()); for (UnsignedInt i = 0; i < stateSize; ++i) MessageInterface::ShowMessage(" %.12lf ", (*estimationState)[i]); MessageInterface::ShowMessage("]\n"); MessageInterface::ShowMessage(" Information matrix:\n"); for (UnsignedInt i = 0; i < information.GetNumRows(); ++i) { MessageInterface::ShowMessage(" ["); for (UnsignedInt j = 0; j < information.GetNumColumns(); ++j) { MessageInterface::ShowMessage(" %.12lf ", information(i,j)); } MessageInterface::ShowMessage("]\n"); } #endif Rmatrix cov(information.GetNumRows(), information.GetNumColumns()); if (inversionType == "Schur") { Real *sum1; Integer arraysize; Integer iSize = information.GetNumColumns(); if (iSize != information.GetNumRows()) throw EstimatorException("Schur inversion requires a square information " "matrix"); arraysize = iSize * (iSize + 1) / 2; sum1 = new Real[arraysize]; // Fill sum1 with the upper triangle Integer index = 0; for (Integer i = 0; i < information.GetNumRows(); ++i) for (Integer j = i; j < information.GetNumColumns(); ++j) { sum1[index] = information(i,j); ++index; } #ifdef DEBUG_SCHUR MessageInterface::ShowMessage("Calling Schur with array size = %d\n" " Input vector: [", arraysize); for (Integer i = 0; i < arraysize; ++i) { if (i > 0) MessageInterface::ShowMessage(", "); MessageInterface::ShowMessage("%.12le", sum1[i]); } MessageInterface::ShowMessage("]\n"); #endif Integer schurRet = SchurInvert(sum1, arraysize); #ifdef DEBUG_SCHUR MessageInterface::ShowMessage(" Output vector: [", arraysize); for (Integer i = 0; i < arraysize; ++i) { if (i > 0) MessageInterface::ShowMessage(", "); MessageInterface::ShowMessage("%.12le", sum1[i]); } MessageInterface::ShowMessage("]\n"); #endif if (schurRet != 0) throw EstimatorException("Schur inversion failed"); // Now fill in cov // Fill sum1 with the upper triangle index = 0; for (Integer i = 0; i < information.GetNumRows(); ++i) for (Integer j = i; j < information.GetNumColumns(); ++j) { cov(i,j) = sum1[index]; ++index; if (i != j) cov(j,i) = cov(i,j); } delete [] sum1; } else if (inversionType == "Cholesky") { Real *sum1; Integer arraysize; Integer iSize = information.GetNumColumns(); if (iSize != information.GetNumRows()) throw EstimatorException("Cholesky inversion requires a symmetric positive definite " "information matrix"); arraysize = iSize * (iSize + 1) / 2; sum1 = new Real[arraysize]; // Fill sum1 with the upper triangle Integer index = 0; for (Integer i = 0; i < information.GetNumRows(); ++i) for (Integer j = i; j < information.GetNumColumns(); ++j) { sum1[index] = information(i,j); ++index; } if (CholeskyInvert(sum1, arraysize) != 0) throw EstimatorException("Cholesky inversion failed"); // Now fill in cov // Fill sum1 with the upper triangle index = 0; for (Integer i = 0; i < information.GetNumRows(); ++i) for (Integer j = i; j < information.GetNumColumns(); ++j) { cov(i,j) = sum1[index]; if (i != j) cov(j,i) = cov(i,j); ++index; } delete [] sum1; } else { try { cov = information.Inverse(); } catch (...) { #ifdef DEBUG_INVERSION MessageInterface::ShowMessage("Information matrix:\n"); for (UnsignedInt i = 0; i < cov.GetNumRows(); ++i) { MessageInterface::ShowMessage(" ["); for (UnsignedInt j = 0; j < information.GetNumColumns(); ++j) { MessageInterface::ShowMessage(" %.12lf ", information(i,j)); } MessageInterface::ShowMessage("]\n"); } #endif throw EstimatorException("Error: Normal matrix is singular.\n"); } } #ifdef DEBUG_VERBOSE MessageInterface::ShowMessage(" residuals: ["); for (UnsignedInt i = 0; i < stateSize; ++i) MessageInterface::ShowMessage(" %.12lf ", residuals(i)); MessageInterface::ShowMessage("]\n"); MessageInterface::ShowMessage(" covariance matrix:\n"); for (UnsignedInt i = 0; i < cov.GetNumRows(); ++i) { MessageInterface::ShowMessage(" ["); for (UnsignedInt j = 0; j < cov.GetNumColumns(); ++j) { MessageInterface::ShowMessage(" %.12lf ", cov(i,j)); } MessageInterface::ShowMessage("]\n"); } #endif // Calculate state change dx in equation 8-57 in GTDS MathSpec dx.clear(); Real delta; for (UnsignedInt i = 0; i < stateSize; ++i) { delta = 0.0; for (UnsignedInt j = 0; j < stateSize; ++j) delta += cov(i,j) * residuals(j); dx.push_back(delta); (*estimationState)[i] += delta; // Equation 8-24 GTSD MathSpec } esm.RestoreObjects(&outerLoopBuffer); // Restore solver-object initial state esm.MapVectorToObjects(); // update objects state to current state // Convert current estimation state from GMAT internal coordinate system to participants' coordinate system GetEstimationStateForReport(currentSolveForState); #ifdef DEBUG_VERBOSE MessageInterface::ShowMessage(" State vector change (dx):\n ["); for (UnsignedInt i = 0; i < stateSize; ++i) MessageInterface::ShowMessage(" %.12lf ", dx[i]); MessageInterface::ShowMessage("]\n"); MessageInterface::ShowMessage(" New estimation state:\n " "epoch = %.12lf\n [", estimationState->GetEpoch()); for (UnsignedInt i = 0; i < stateSize; ++i) MessageInterface::ShowMessage(" %.12lf ", (*estimationState)[i]); MessageInterface::ShowMessage("]\n"); #endif // Specify RMSP: equation 8-185 in GTDS MathSpec predictedRMS = 0; if (useApriori) { // The last term of RMSP in equation 8-185 in GTDS MathSpec GmatState currentEstimationState = (*estimationState); Rmatrix Pdx0_inv; try { Pdx0_inv = stateCovariance->GetCovariance()->Inverse(); // inverse of the initial estimation error covariance matrix } catch (...) { MessageInterface::ShowMessage("Apriori covariance matrix:\n["); for (Integer row = 0; row < stateCovariance->GetDimension(); ++row) { for (Integer col = 0; col < stateCovariance->GetDimension(); ++col) MessageInterface::ShowMessage("%le ", stateCovariance->GetCovariance()->GetElement(row, col)); if (row < stateCovariance->GetDimension()-1) MessageInterface::ShowMessage("\n"); } MessageInterface::ShowMessage("]\n"); throw EstimatorException("Error: Apriori covariance matrix is singular. GMAT cannot take inverse of that matrix.\n"); } for (UnsignedInt i = 0; i < stateSize; ++i) { for (UnsignedInt j = 0; j < stateSize; ++j) predictedRMS += (currentEstimationState[i] - initialEstimationState[i])*Pdx0_inv(i,j)*(currentEstimationState[j] - initialEstimationState[j]); // The second term inside square brackets of equation 8-185 GTDS MathSpec } } // The first term of RMSP in equation 8-185 in GTDS MathSpec for (UnsignedInt j = 0; j < hAccum.size(); ++j) // j presents for the index of the measurement jth { Real temp = 0; for(UnsignedInt i = 0; i < hAccum[j].size(); ++i) { temp += hAccum[j][i]*dx[i]; } predictedRMS += (measurementResiduals[j] - temp)*(measurementResiduals[j] - temp)*Weight[j]; // The first term in equation 8-185 in GTDS MathSpec } if (useApriori) predictedRMS = sqrt(predictedRMS / (measurementResiduals.size()+1)); else predictedRMS = sqrt(predictedRMS/measurementResiduals.size()); // Write to report initial state for current iteration WriteToTextFile(currentState); // Clear O, C, and W lists Weight.clear(); OData.clear(); CData.clear(); currentState = CHECKINGRUN; } Real BatchEstimatorInv::ObservationDataCorrection(Real cValue, Real oValue, Real moduloConstant) { Real delta = cValue - oValue; int N = (int)(delta/moduloConstant + 0.5); return (oValue + N*moduloConstant); } void BatchEstimatorInv::ValidateMediaCorrection(const MeasurementData* measData) { if (measData->isIonoCorrectWarning) { // Get measurement pass: std::stringstream ss1; ss1 << "{{"; for (Integer i = 0; i < measData->participantIDs.size(); ++i) { ss1 << measData->participantIDs[i] << (((i + 1) < measData->participantIDs.size()) ? "," : ""); } ss1 << "}," << measData->typeName << "}"; // if the pass is not in warning list, then display warning message if (find(ionoWarningList.begin(), ionoWarningList.end(), ss1.str()) == ionoWarningList.end()) { // generate warning message MessageInterface::ShowMessage("Warning: When running estimator '%s', ionosphere correction is %lf m for measurement %s at measurement time tag %.12lf A1Mjd. Media corrections to the computed measurement may be inaccurate.\n", GetName().c_str(), measData->ionoCorrectWarningValue * 1000.0, ss1.str().c_str(), measData->epoch); // add pass to the list ionoWarningList.push_back(ss1.str()); } } if (measData->isTropoCorrectWarning) { // Get measurement path: std::stringstream ss1; ss1 << "{{"; for (Integer i = 0; i < measData->participantIDs.size(); ++i) { ss1 << measData->participantIDs[i] << (((i + 1) < measData->participantIDs.size()) ? "," : ""); } ss1 << "}," << measData->typeName << "}"; // if the pass is not in warning list, then display warning message if (find(tropoWarningList.begin(), tropoWarningList.end(), ss1.str()) == tropoWarningList.end()) { // generate warning message MessageInterface::ShowMessage("Warning: When running estimator '%s', troposphere correction is %lf m for measurement %s at measurement time tag %.12lf A1Mjd. Media corrections to the computed measurement may be inaccurate.\n", GetName().c_str(), measData->tropoCorrectWarningValue * 1000.0, ss1.str().c_str(), measData->epoch); // add pass to the list tropoWarningList.push_back(ss1.str()); } } }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EXPONENTIALMATERIALLAW_HPP_ #define EXPONENTIALMATERIALLAW_HPP_ #include "AbstractIsotropicIncompressibleMaterialLaw.hpp" #include "Exception.hpp" /** * ExponentialMaterialLaw * * An exponential isotropic incompressible hyperelastic material law for finite * elasticity * * The law is given by a strain energy function * W(I_1,I_2,I_3) = a exp( b(I_1-3) ) - p/2 C^{-1} * in 3d, or * W(I_1,I_2,I_3) = a exp( b(I_1-2) ) - p/2 C^{-1} * in 2d. * * Here I_i are the principal invariants of C, the Lagrangian deformation tensor. * (I1=trace(C), I2=trace(C)^2-trace(C^2), I3=det(C)). * Note: only dimension equals 2 or 3 is permitted. */ template<unsigned DIM> class ExponentialMaterialLaw : public AbstractIsotropicIncompressibleMaterialLaw<DIM> { private: /** Parameter a. */ double mA; /** Parameter b. */ double mB; public: /** * @return the first derivative dW/dI1. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_dW_dI1(double I1, double I2); /** * @return the first derivative dW/dI2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_dW_dI2(double I1, double I2); /** * @return the second derivative d^2W/dI1^2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI1(double I1, double I2); /** * @return the second derivative d^2W/dI2^2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI2(double I1, double I2); /** * @return the second derivative d^2W/dI1dI2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI1I2(double I1, double I2); /** @return mA. */ double GetA(); /** @return mB. */ double GetB(); public: /** * Constructor, taking in the parameters a and b. a must be positive. * * @param a the parameter a * @param b the parameter b */ ExponentialMaterialLaw(double a, double b); }; #endif /*EXPONENTIALMATERIALLAW_HPP_*/
// This file has been generated by Py++. #ifndef TypeAliasIterator_hpp__pyplusplus_wrapper #define TypeAliasIterator_hpp__pyplusplus_wrapper void register_TypeAliasIterator_class(); #endif//TypeAliasIterator_hpp__pyplusplus_wrapper
//CS 325 Project 4: TSP //Alex Way, Kristin Swanson, Peter Rissberger //Build with: g++ -std=c++0x -g -o tsp tsp.cpp //Run with: tsp inFile.txt //Optionally, add 2 or 3 as a final argument. This will run the 2-opt or 3-opt //(respectively) until no more improvement can be found. Leave the 3rd //argument off for a faster (but perhaps less optimal) solution. #include <iostream> #include <fstream> #include <string> #include <cmath> #include <algorithm> using namespace std; //Global vars ifstream inFile; ofstream outFile; //Reads file, counts input, returns arrays to main int lineCount(char *infileName) { int lineCount = 0; //Create/open in/outFile inFile.open(infileName); string outfileName = infileName; outfileName += ".tour"; outFile.open(outfileName); //Count lines in file for (string line; getline(inFile, line); ++lineCount); cout << "Lines in file: " << lineCount << endl; inFile.clear(); inFile.seekg(0, ios::beg); // cout << "Lines: " << lineCount << endl; return lineCount; } //Populate Names, Xs, and Ys of arrays with inFile data int populateArrays(string names[], int xs[], int ys[], int lines) { string str; int i = 0; //cout << sizeof(xs); while (i < lines) { // cout << "Populating index " << i << endl; //Input city name inFile >> str; // cout << "Name = " << str << endl; names[i] = str; //Input city's x coordinate inFile >> str; // cout << "X = " << str << endl; xs[i] = stoi(str); //Input city's y coordinate inFile >> str; // cout << "Y = " << str << endl; ys[i] = stoi(str); i++; } } // Return true if test in arr bool isIn(int arr[], int test, int length){ for (int i = 0; i < length; i++) { if (arr[i] == test) return true; } return false; } // Returns distance between two points to the nearest integer int distance(float x1, float y1, float x2, float y2) { return (int) (sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)) + .5); } int tourLength(int xs[], int ys[], int order[], int points) { int length = 0; for (int i = 0; i < points - 1; i++) { length += distance(xs[order[i]], ys[order[i]], xs[order[i+1]], ys[order[i+1]]); } length += distance(xs[order[points - 1]], ys[order[points - 1]], xs[order[0]], ys[order[0]]); return length; } // Greedy algorithm for initial tour, returns the tour length int greedyTour(int xs[], int ys[], int order[], int points) { int length = 0, current, bestPoint = 0, bestDist, nextDist; bool firstDist; // For each point, compare it to each of the other points that have not // yet been done, picking the point with the smallest distance to be next // in order for (int i = 0; i < points; i++) { current = bestPoint; order[i] = current; firstDist = true; bestDist = 0; for (int j = 0; j < points; j++) { if (isIn(order, j, points)) continue; nextDist = distance(xs[current], ys[current], xs[j], ys[j]); if (nextDist < bestDist || firstDist) { bestDist = nextDist; bestPoint = j; firstDist = false; } } length += bestDist; } // Add the connection from the last point to the first length += distance(xs[order[points - 1]], ys[order[points - 1]], xs[order[0]], ys[order[0]]); cout << "Greedy tour length: " << length << endl; return length; } // 2-otp improvement from initial tour (as giving by order) int opt2Tour(int xs[], int ys[], int order[], int points, string names[]) { int length = 0, bestPointIdx, bestDist, nextDist; bool isChange; /* cout << "Greedy order: " << endl; for (int i = 0; i < points; i++) { cout << order[i] << endl; }*/ // For each point, consider switching it with each other point, storing the // best solution until you have compared it to each point. Once a point // is considered for all, it does not need to be considered again. for (int i = 0; i < points - 1; i++) { // Set best to the current distance and point bestDist = tourLength(xs, ys, order, points); bestPointIdx = i; for (int j = i+1; j < points; j++) { // Get the tour distance if we swapped order[i] with order[j] swap(order[i], order[j]); nextDist = tourLength(xs, ys, order, points); swap(order[i], order[j]); // if the new tour is shorter, store the point index j and the distance // of its tour as best option so far if (nextDist < bestDist) { bestDist = nextDist; bestPointIdx = j; } } // Swap points if a better tour was found if (bestPointIdx != i) { swap(order[i], order[bestPointIdx]); isChange = true; } } length = tourLength(xs, ys, order, points); cout << "Improved length: " << length << endl; /* cout << "Improved order: " << endl; for (int i = 0; i < points; i++) { cout << order[i] << endl; }*/ return length; } // 2-otp/3-opt improvement from initial tour (as giving by order) int opt3Tour(int xs[], int ys[], int order[], int points, string names[]) { int length = 0, bestPointIdx, bestPointIdx2, bestDist, nextDist; bool isChange; //Could use to re-run the entire algorithm if any swap was made /* cout << "Greedy order: " << endl; for (int i = 0; i < points; i++) { cout << order[i] << endl; } */ // For each point, consider switching it with each other point, storing the // best solution until you have compared it to each point. Once a point // is considered for all, it does not need to be considered again. for (int i = 0; i < points - 1; i++) { // Set best to the current distance and point bestDist = tourLength(xs, ys, order, points); bestPointIdx = i; bestPointIdx2 = i; for (int j = i+1; j < points; j++) { // Get the tour distance if we swapped order[i] with order[j] swap(order[i], order[j]); nextDist = tourLength(xs, ys, order, points); swap(order[i], order[j]); // if the new tour is shorter, store the point index j and the distance // of its tour as best option so far if (nextDist < bestDist) { bestDist = nextDist; bestPointIdx = j; bestPointIdx2 = i; } for (int k = j+1; k < points; k++) { // Get the tour distance if we swapped 123 to 231 swap(order[i], order[j]); //213 swap(order[j], order[k]); //231 nextDist = tourLength(xs, ys, order, points); swap(order[j], order[k]); swap(order[i], order[j]); // if the new tour is shorter, store the points to swap in order if (nextDist < bestDist) { bestDist = nextDist; bestPointIdx = j; bestPointIdx2 = k; } // Get the tour distance if we swapped 123 to 312 swap(order[i], order[k]); //321 swap(order[j], order[k]); //312 nextDist = tourLength(xs, ys, order, points); swap(order[j], order[k]); swap(order[i], order[k]); // if the new tour is shorter, store the points to swap in order if (nextDist < bestDist) { bestDist = nextDist; bestPointIdx = k; bestPointIdx2 = j; } } } // Swap points if a better tour was found if (bestPointIdx != i) { if (bestPointIdx2 != i) { swap(order[i], order[bestPointIdx]); swap(order[bestPointIdx], order[bestPointIdx2]); // cout << "Swapped 3 edges" << endl; } else { swap(order[i], order[bestPointIdx]); // cout << "Swapped 2 edges" << endl; } isChange = true; } // cout << "Current tour length: " << tourLength(xs, ys, order, points) << endl; } length = tourLength(xs, ys, order, points); cout << "Improved length: " << length << endl; /* cout << "Improved order: " << endl; for (int i = 0; i < points; i++) { cout << order[i] << endl; }*/ return length; } // Outputs tour length and order visited to file [input_file].tour void outputTour(int length, int order[], int points, string names[]) { outFile << "Length: " << length; for (int i = 0; i < points; i++) { string identifier = names[order[i]]; outFile << endl << identifier; } } int main(int argc, char *argv[]) { //Count lines in input file int lines = lineCount(argv[1]); // To find better solutions but taking more time int fast = 1; if (argc > 2) fast = atoi(argv[2]); //Populate arrays with cities and coordinates string names[lines]; int xs[lines]; int ys[lines]; int order[lines]; for (int i = 0; i < lines; i++) order[i] = -1; populateArrays(names, xs, ys, lines); int totalDist = greedyTour(xs, ys, order, lines); int tempDist; if (fast == 2) { do { tempDist = totalDist; totalDist = opt2Tour(xs, ys, order, lines, names); } while (tempDist != totalDist); } else if (fast == 3) { do { cout << "fast = " << fast; tempDist = totalDist; totalDist = opt3Tour(xs, ys, order, lines, names); } while (tempDist != totalDist); } else if (lines <= 250) { opt3Tour(xs, ys, order, lines, names); opt3Tour(xs, ys, order, lines, names); totalDist = opt3Tour(xs, ys, order, lines, names); } else if (lines <= 1000) { opt2Tour(xs, ys, order, lines, names); opt2Tour(xs, ys, order, lines, names); opt2Tour(xs, ys, order, lines, names); totalDist = opt2Tour(xs, ys, order, lines, names); } else if (lines <= 2000) { totalDist = opt2Tour(xs, ys, order, lines, names); } outputTour(totalDist, order, lines, names); return 0; }
#include "core.h" #include "log.h" #include <QFile> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJSValueIterator> static const QLatin1String s_countriesFileName("countries.json"); Core::Core(QObject *parent) : QObject(parent) { } QString Core::init() { if (!QFile::exists(s_countriesFileName)) return QString("File \"%1\" was not found").arg(s_countriesFileName); if (!readCountriesJson()) return QString("File \"%1\" has no valid data").arg(s_countriesFileName); return QString(); } bool Core::readCountriesJson() { QFile file(s_countriesFileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { WARNING_LOG "failure to open file:" << s_countriesFileName; return false; } const QByteArray data = file.readAll(); file.close(); const QJsonDocument jsonDocument = QJsonDocument::fromJson(data); const QJsonObject rootJsonObject = jsonDocument.object(); const QJsonValue jsonValue = rootJsonObject.value(QLatin1String("countries")); if (!jsonValue.isArray()) return false; QJsonArray jsonArray = jsonValue.toArray(); if (jsonArray.isEmpty()) return false; for (int i = 0; i < jsonArray.count(); ++i) { const QJsonObject countryJsonObject = jsonArray.at(i).toObject(); if (!countryJsonObject.contains(QLatin1String("code")) || !countryJsonObject.contains(QLatin1String("name"))) { jsonArray.removeAt(i); --i; } } m_countries = QVariant::fromValue(jsonArray.toVariantList()); return !jsonArray.isEmpty(); } bool Core::signUp(const QVariant &data) const { jsToVariantMap(data); /* For this test version it is all correct, but in release version registration actions will be requared here */ return true; } QVariantMap Core::jsToVariantMap(const QVariant &data) const { QVariantMap map; const QJSValue jsValue = data.value<QJSValue>(); QJSValueIterator it(jsValue); while (it.next()) { const QString name = it.name(); if (name != QLatin1String("length")) { const QJSValue jsValue2 = it.value(); QJSValueIterator it2(jsValue2); while (it2.next()) { const QString name = it2.name(); const QVariant value = it2.value().toVariant(); DEBUG_LOG name << value; map.insert(name, value); } } } return map; }
// // ImageProcessFunction.h // SMFrameWork // // Created by KimSteve on 2016. 12. 5.. // // 여러가지 Image process 함수들... #ifndef ImageProcessFunction_h #define ImageProcessFunction_h #include "ImageProcessor.h" #include <platform/CCImage.h> #include <2d/CCSprite.h> #include <base/ccTypes.h> class Intent; class ImageProcessFunction { public: ImageProcessFunction(); virtual ~ImageProcessFunction(); virtual bool onPreProcess(cocos2d::Node* node); virtual bool onProcessInBackground() = 0; virtual cocos2d::Sprite* onPostProcess(); Intent* getParam() {return _param;} virtual void onCaptureComplete(cocos2d::Texture2D* texture) {} protected: void setTask(ImageProcessor::ImageProcessTask* task); void onProgress(float progress); void setCaptureOnly() {_isCaptureOnly = true;} bool isCaptureOnly() {return _isCaptureOnly;} void initOutputBuffer(const int width, const int height, const int bpp); void setOutputImage(cocos2d::Image* image) {_outputImage = image;} cocos2d::Size getOutputSize() {return _outputSize;} cocos2d::Size getInputSize() {return _inputSize;} int getInputBpp() {return _inputBpp;} int getOutputBpp() {return _outputBpp;} cocos2d::Image* getOutputImage() {return _outputImage;} uint8_t* getInputData() {return _inputData;} uint8_t* getOutputData() {return _outputData;} size_t getInputDataLength() { return (size_t)(_inputSize.width*_inputSize.height*_inputBpp); } void releaseInputData(); void releaseOutputData(); Intent* initParam(); cocos2d::Texture2D* getCapturedTexture(); void setClearColor(const cocos2d::Color4F& clearColor) {_clearColor = clearColor;} protected: virtual bool startProcess(cocos2d::Node* node, const cocos2d::Size& canvasSize, const cocos2d::Vec2& position, const cocos2d::Vec2& anchorPoint, const float scaleX, const float scaleY); void interrupt() {_interrupt = true;} bool isInterrupt() {return _interrupt;} void onReadPixelsCommand(); protected: cocos2d::RenderTexture* _renderTexture; cocos2d::Size _inputSize; uint8_t* _inputData; int _inputBpp; private: Intent* _param; cocos2d::Size _outputSize; uint8_t* _outputData; cocos2d::Image* _outputImage; int _outputBpp; cocos2d::Color4F _clearColor; bool _interrupt; bool _isCaptureOnly; ImageProcessor::ImageProcessTask* _task; friend class ImageProcessor; }; #endif /* ImageProcessFunction_h */
// // Emulator - Simple C64 emulator // Copyright (C) 2003-2016 Michael Fink // /// \file Processor6510.cpp MOS6510 processor emulation // // includes #include "StdAfx.h" #include "Processor6510.hpp" #include "MemoryManager.hpp" #include <algorithm> using C64::Processor6510; using C64::AddressingMode; using C64::RegisterID; /// \brief cycle count for all opcodes /// from http://www.oxyron.de/html/opcodes02.html static BYTE g_abOpcodeCycles[256] = { 7, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 3, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 5, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, 2, 6, 0, 6, 4, 4, 4, 4, 2, 5, 2, 5, 5, 5, 5, 5, 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, 2, 5, 0, 5, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4, 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7 }; /// \brief constant with status register bits that are always set /// note: bit 5 (unused) and bit 4 (break) of the status register are always set const BYTE c_bStatusMaskAlwaysSet = (1 << static_cast<BYTE>(C64::flagUnused)) | (1 << static_cast<BYTE>(C64::flagBreak)); Processor6510::Processor6510(C64::MemoryManager& memoryManager) throw() :m_memoryManager(memoryManager), m_wProgramCounter(0), m_uiProcessedOpcodes(0), m_uiElapsedCycles(0), m_debugOutput(false) { memset(m_abRegister, 0, sizeof(m_abRegister)); // note: bit 5 (unused) and bit 4 (break) are always set m_abRegister[regSR] = c_bStatusMaskAlwaysSet; m_abRegister[regSP] = 0xff; } void Processor6510::AddProcessorCallback(C64::IProcessorCallback* pCallback) { ATLASSERT(pCallback != NULL); m_setCallbacks.insert(pCallback); } void Processor6510::RemoveProcessorCallback(C64::IProcessorCallback* pCallback) { ATLASSERT(pCallback != NULL); m_setCallbacks.erase(pCallback); } void Processor6510::SetFlag(C64::ProcessorFlag enFlag, bool bFlag) { ATLASSERT(enFlag < 8); BYTE iBit = static_cast<BYTE>(enFlag); m_abRegister[regSR] &= ~(1 << iBit); if (bFlag) m_abRegister[regSR] |= 1 << iBit; } bool Processor6510::GetFlag(C64::ProcessorFlag enFlag) { ATLASSERT(enFlag < 8); BYTE iBit = static_cast<BYTE>(enFlag); return (m_abRegister[regSR] & (1 << iBit)) != 0; } void Processor6510::Step() { #if 0 { #pragma warning(disable: 28159) // Consider using GetTickCount64 static DWORD dwT1 = GetTickCount(); static unsigned int uiLastProcessedCycles = 0; DWORD dwT2 = GetTickCount(); if (dwT2 - dwT1 > 1000) { // output some statistics ATLTRACE(_T("statistics: %u opcodes/s, %u cycles/s\n"), m_uiProcessedOpcodes, m_uiElapsedCycles - uiLastProcessedCycles); m_uiProcessedOpcodes = 0; uiLastProcessedCycles = m_uiElapsedCycles; dwT1 = dwT2; } #pragma warning(default: 28159) } #endif m_uiProcessedOpcodes++; // send notification of PC change std::for_each(m_setCallbacks.begin(), m_setCallbacks.end(), [](IProcessorCallback* callback) { callback->OnStep(); }); if (m_debugOutput) m_opcodeText.Format(_T("%04x "), m_wProgramCounter); BYTE bOpcode = m_memoryManager.Peek(m_wProgramCounter++); std::for_each(m_setCallbacks.begin(), m_setCallbacks.end(), [&](IProcessorCallback* callback) { callback->OnExecute(m_wProgramCounter - 1, 1); }); // count cycles m_uiElapsedCycles += g_abOpcodeCycles[bOpcode]; bool bProgramCounterChanged = false; switch (bOpcode) { // load opcodes case opLDA_imm: LoadRegister(regA, addrImmediate); break; case opLDA_zp: LoadRegister(regA, addrZeropage); break; case opLDA_zpx: LoadRegister(regA, addrZeropageIndexedX); break; case opLDA_izx: LoadRegister(regA, addrIndirectZeropageIndexedX); break; case opLDA_izy: LoadRegister(regA, addrIndirectZeropageIndexedY); break; case opLDA_abs: LoadRegister(regA, addrAbsolute); break; case opLDA_abx: LoadRegister(regA, addrAbsoluteIndexedX); break; case opLDA_aby: LoadRegister(regA, addrAbsoluteIndexedY); break; case opLDX_imm: LoadRegister(regX, addrImmediate); break; case opLDX_zp: LoadRegister(regX, addrZeropage); break; case opLDX_zpy: LoadRegister(regX, addrZeropageIndexedY); break; case opLDX_abs: LoadRegister(regX, addrAbsolute); break; case opLDX_aby: LoadRegister(regX, addrAbsoluteIndexedY); break; case opLDY_imm: LoadRegister(regY, addrImmediate); break; case opLDY_zp: LoadRegister(regY, addrZeropage); break; case opLDY_zpx: LoadRegister(regY, addrZeropageIndexedX); break; case opLDY_abs: LoadRegister(regY, addrAbsolute); break; case opLDY_abx: LoadRegister(regY, addrAbsoluteIndexedX); break; // store opcodes case opSTA_zp: StoreRegister(regA, addrZeropage); break; case opSTA_zpx: StoreRegister(regA, addrZeropageIndexedX); break; case opSTA_izx: StoreRegister(regA, addrIndirectZeropageIndexedX); break; case opSTA_izy: StoreRegister(regA, addrIndirectZeropageIndexedY); break; case opSTA_abs: StoreRegister(regA, addrAbsolute); break; case opSTA_abx: StoreRegister(regA, addrAbsoluteIndexedX); break; case opSTA_aby: StoreRegister(regA, addrAbsoluteIndexedY); break; case opSTX_zp: StoreRegister(regX, addrZeropage); break; case opSTX_zpy: StoreRegister(regX, addrZeropageIndexedY); break; case opSTX_abs: StoreRegister(regX, addrAbsolute); break; case opSTY_zp: StoreRegister(regY, addrZeropage); break; case opSTY_zpx: StoreRegister(regY, addrZeropageIndexedX); break; case opSTY_abs: StoreRegister(regY, addrAbsolute); break; // transfer opcodes case opTAX: TransferRegister(regA, regX); break; case opTXA: TransferRegister(regX, regA); break; case opTAY: TransferRegister(regA, regY); break; case opTYA: TransferRegister(regY, regA); break; case opTSX: TransferRegister(regSP, regX); break; case opTXS: TransferRegister(regX, regSP); break; // inc/dec opcodes case opDEC_zp: IncDecRegister(regA, addrZeropage, false); break; case opDEC_zpx: IncDecRegister(regA, addrZeropageIndexedX, false); break; case opDEC_abs: IncDecRegister(regA, addrAbsolute, false); break; case opDEC_abx: IncDecRegister(regA, addrAbsoluteIndexedX, false); break; case opDEX: IncDecRegister(regX, addrImplicit, false); break; case opDEY: IncDecRegister(regY, addrImplicit, false); break; case opINC_zp: IncDecRegister(regA, addrZeropage, true); break; case opINC_zpx: IncDecRegister(regA, addrZeropageIndexedX, true); break; case opINC_abs: IncDecRegister(regA, addrAbsolute, true); break; case opINC_abx: IncDecRegister(regA, addrAbsoluteIndexedX, true); break; case opINX: IncDecRegister(regX, addrImplicit, true); break; case opINY: IncDecRegister(regY, addrImplicit, true); break; // compare case opcodes case opCMP_imm: CompareRegister(regA, addrImmediate); break; case opCMP_zp: CompareRegister(regA, addrZeropage); break; case opCMP_zpx: CompareRegister(regA, addrZeropageIndexedX); break; case opCMP_izx: CompareRegister(regA, addrIndirectZeropageIndexedX); break; case opCMP_izy: CompareRegister(regA, addrIndirectZeropageIndexedY); break; case opCMP_abs: CompareRegister(regA, addrAbsolute); break; case opCMP_abx: CompareRegister(regA, addrAbsoluteIndexedX); break; case opCMP_aby: CompareRegister(regA, addrAbsoluteIndexedY); break; case opCPX_imm: CompareRegister(regX, addrImmediate); break; case opCPX_zp: CompareRegister(regX, addrZeropage); break; case opCPX_abs: CompareRegister(regX, addrAbsolute); break; case opCPY_imm: CompareRegister(regY, addrImmediate); break; case opCPY_zp: CompareRegister(regY, addrZeropage); break; case opCPY_abs: CompareRegister(regY, addrAbsolute); break; // branch opcodes case opBPL: case opBMI: case opBVC: case opBVS: case opBCC: case opBCS: case opBNE: case opBEQ: Branch(bOpcode); break; // arithmetic opcodes case opORA_imm: LogicalOperation(logicalOperationOra, addrImmediate); break; case opORA_zp: LogicalOperation(logicalOperationOra, addrZeropage); break; case opORA_zpx: LogicalOperation(logicalOperationOra, addrZeropageIndexedX); break; case opORA_izx: LogicalOperation(logicalOperationOra, addrIndirectZeropageIndexedX); break; case opORA_izy: LogicalOperation(logicalOperationOra, addrIndirectZeropageIndexedY); break; case opORA_abs: LogicalOperation(logicalOperationOra, addrAbsolute); break; case opORA_abx: LogicalOperation(logicalOperationOra, addrAbsoluteIndexedX); break; case opORA_aby: LogicalOperation(logicalOperationOra, addrAbsoluteIndexedY); break; case opAND_imm: LogicalOperation(logicalOperationAnd, addrImmediate); break; case opAND_zp: LogicalOperation(logicalOperationAnd, addrZeropage); break; case opAND_zpx: LogicalOperation(logicalOperationAnd, addrZeropageIndexedX); break; case opAND_izx: LogicalOperation(logicalOperationAnd, addrIndirectZeropageIndexedX); break; case opAND_izy: LogicalOperation(logicalOperationAnd, addrIndirectZeropageIndexedY); break; case opAND_abs: LogicalOperation(logicalOperationAnd, addrAbsolute); break; case opAND_abx: LogicalOperation(logicalOperationAnd, addrAbsoluteIndexedX); break; case opAND_aby: LogicalOperation(logicalOperationAnd, addrAbsoluteIndexedY); break; case opEOR_imm: LogicalOperation(logicalOperationEor, addrImmediate); break; case opEOR_zp: LogicalOperation(logicalOperationEor, addrZeropage); break; case opEOR_zpx: LogicalOperation(logicalOperationEor, addrZeropageIndexedX); break; case opEOR_izx: LogicalOperation(logicalOperationEor, addrIndirectZeropageIndexedX); break; case opEOR_izy: LogicalOperation(logicalOperationEor, addrIndirectZeropageIndexedY); break; case opEOR_abs: LogicalOperation(logicalOperationEor, addrAbsolute); break; case opEOR_abx: LogicalOperation(logicalOperationEor, addrAbsoluteIndexedX); break; case opEOR_aby: LogicalOperation(logicalOperationEor, addrAbsoluteIndexedY); break; case opADC_imm: ArithmeticOperation(arithmeticOperationAdc, addrImmediate); break; case opADC_zp: ArithmeticOperation(arithmeticOperationAdc, addrZeropage); break; case opADC_zpx: ArithmeticOperation(arithmeticOperationAdc, addrZeropageIndexedX); break; case opADC_izx: ArithmeticOperation(arithmeticOperationAdc, addrIndirectZeropageIndexedX); break; case opADC_izy: ArithmeticOperation(arithmeticOperationAdc, addrIndirectZeropageIndexedY); break; case opADC_abs: ArithmeticOperation(arithmeticOperationAdc, addrAbsolute); break; case opADC_abx: ArithmeticOperation(arithmeticOperationAdc, addrAbsoluteIndexedX); break; case opADC_aby: ArithmeticOperation(arithmeticOperationAdc, addrAbsoluteIndexedY); break; case opSBC_imm: ArithmeticOperation(arithmeticOperationSbc, addrImmediate); break; case opSBC_zp: ArithmeticOperation(arithmeticOperationSbc, addrZeropage); break; case opSBC_zpx: ArithmeticOperation(arithmeticOperationSbc, addrZeropageIndexedX); break; case opSBC_izx: ArithmeticOperation(arithmeticOperationSbc, addrIndirectZeropageIndexedX); break; case opSBC_izy: ArithmeticOperation(arithmeticOperationSbc, addrIndirectZeropageIndexedY); break; case opSBC_abs: ArithmeticOperation(arithmeticOperationSbc, addrAbsolute); break; case opSBC_abx: ArithmeticOperation(arithmeticOperationSbc, addrAbsoluteIndexedX); break; case opSBC_aby: ArithmeticOperation(arithmeticOperationSbc, addrAbsoluteIndexedY); break; // shift / roll opcodes case opASL_imp: ShiftOperation(shiftOperationAsl, addrImplicit); break; case opASL_zp: ShiftOperation(shiftOperationAsl, addrZeropage); break; case opASL_zpx: ShiftOperation(shiftOperationAsl, addrZeropageIndexedX); break; case opASL_abs: ShiftOperation(shiftOperationAsl, addrAbsolute); break; case opASL_abx: ShiftOperation(shiftOperationAsl, addrAbsoluteIndexedX); break; case opROL_imp: ShiftOperation(shiftOperationRol, addrImplicit); break; case opROL_zp: ShiftOperation(shiftOperationRol, addrZeropage); break; case opROL_zpx: ShiftOperation(shiftOperationRol, addrZeropageIndexedX); break; case opROL_abs: ShiftOperation(shiftOperationRol, addrAbsolute); break; case opROL_abx: ShiftOperation(shiftOperationRol, addrAbsoluteIndexedX); break; case opLSR_imp: ShiftOperation(shiftOperationLsr, addrImplicit); break; case opLSR_zp: ShiftOperation(shiftOperationLsr, addrZeropage); break; case opLSR_zpx: ShiftOperation(shiftOperationLsr, addrZeropageIndexedX); break; case opLSR_abs: ShiftOperation(shiftOperationLsr, addrAbsolute); break; case opLSR_abx: ShiftOperation(shiftOperationLsr, addrAbsoluteIndexedX); break; case opROR_imp: ShiftOperation(shiftOperationRor, addrImplicit); break; case opROR_zp: ShiftOperation(shiftOperationRor, addrZeropage); break; case opROR_zpx: ShiftOperation(shiftOperationRor, addrZeropageIndexedX); break; case opROR_abs: ShiftOperation(shiftOperationRor, addrAbsolute); break; case opROR_abx: ShiftOperation(shiftOperationRor, addrAbsoluteIndexedX); break; // push/pop case opPHP: if (m_debugOutput) m_opcodeText.AppendFormat(_T("PHP")); Push(GetRegister(regSR) | c_bStatusMaskAlwaysSet); break; case opPLP: if (m_debugOutput) m_opcodeText.AppendFormat(_T("PLP")); SetRegister(regSR, Pop() | c_bStatusMaskAlwaysSet); break; case opPHA: if (m_debugOutput) m_opcodeText.AppendFormat(_T("PHA")); Push(GetRegister(regA)); break; case opPLA: { if (m_debugOutput) m_opcodeText.AppendFormat(_T("PLA")); BYTE bValue = Pop(); SetRegister(regA, bValue); // set flags SetFlag(flagZero, bValue == 0); SetFlag(flagNegative, (bValue & 0x80) != 0); } break; // flags case opCLC: SetFlagOperation(flagCarry, false); break; case opSEC: SetFlagOperation(flagCarry, true); break; case opCLD: SetFlagOperation(flagDecimal, false); break; case opSED: SetFlagOperation(flagDecimal, true); break; case opCLI: SetFlagOperation(flagInterrupt, false); break; case opSEI: SetFlagOperation(flagInterrupt, true); break; case opCLV: SetFlagOperation(flagOverflow, false); break; // control flow opcodes case opJMP_abs: if (m_debugOutput) m_opcodeText.AppendFormat(_T("JMP ")); m_wProgramCounter = FetchAddress(addrAbsolute); bProgramCounterChanged = true; break; case opJMP_ind: if (m_debugOutput) m_opcodeText.AppendFormat(_T("JMP ")); m_wProgramCounter = FetchAddress(addrIndirect); if (m_debugOutput) m_opcodeText.AppendFormat(_T("(to $%04x)"), m_wProgramCounter); bProgramCounterChanged = true; break; case opJSR: { WORD wAddr = Load16(m_wProgramCounter); m_wProgramCounter++; Push(static_cast<BYTE>(m_wProgramCounter >> 8)); Push(static_cast<BYTE>(m_wProgramCounter & 0xff)); m_wProgramCounter++; m_wProgramCounter = wAddr; if (m_debugOutput) m_opcodeText.AppendFormat(_T("JSR $%04x"), m_wProgramCounter); bProgramCounterChanged = true; } break; case opRTS: if (m_debugOutput) m_opcodeText.AppendFormat(_T("RTS")); Return(); bProgramCounterChanged = true; break; case opBRK: if (m_debugOutput) m_opcodeText.AppendFormat(_T("BRK")); m_wProgramCounter++; Push(static_cast<BYTE>(m_wProgramCounter >> 8)); Push(static_cast<BYTE>(m_wProgramCounter & 0xff)); // note: bit 4 (break) set by this instruction explicitly; it's clear on non-BRK interrupts Push(GetRegister(regSR) | c_bStatusMaskAlwaysSet); // set interrupt bit, so that no further interrupts may occur SetFlag(C64::flagInterrupt, true); m_wProgramCounter = Load16(0xfffe); bProgramCounterChanged = true; break; case opRTI: if (m_debugOutput) m_opcodeText.AppendFormat(_T("RTI")); SetRegister(regSR, Pop() | c_bStatusMaskAlwaysSet); Return(); m_wProgramCounter--; // undo the increment in Return() bProgramCounterChanged = true; break; case opBIT_zp: BitOperation(addrZeropage); break; case opBIT_abs: BitOperation(addrAbsolute); break; case opNOP: // do nothing if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP")); break; // illegal opcodes case illNOP_1: case illNOP_2: case illNOP_3: case illNOP_4: case illNOP_5: case illNOP_6: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP")); break; case illNOP_imm_1: case illNOP_imm_2: case illNOP_imm_3: case illNOP_imm_4: case illNOP_imm_5: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP ")); FetchAddress(addrImmediate); break; case illNOP_abs: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP ")); FetchAddress(addrAbsolute); break; case illNOP_abx_1: case illNOP_abx_2: case illNOP_abx_3: case illNOP_abx_4: case illNOP_abx_5: case illNOP_abx_6: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP ")); FetchAddress(addrAbsoluteIndexedX); break; case illNOP_zp_1: case illNOP_zp_2: case illNOP_zp_3: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP ")); FetchAddress(addrZeropage); break; case illNOP_zpx_1: case illNOP_zpx_2: case illNOP_zpx_3: case illNOP_zpx_4: case illNOP_zpx_5: case illNOP_zpx_6: if (m_debugOutput) m_opcodeText.AppendFormat(_T("NOP ")); FetchAddress(addrZeropageIndexedX); break; default: ATLTRACE(_T("unknown opcode: %02x\n"), bOpcode); break; } //m_opcodeText.AppendFormat(_T(" \tA=%02x X=%02x Y=%02x P=%02x S=%02x"), // GetRegister(regA), // GetRegister(regX), // GetRegister(regY), // GetRegister(regSR), // GetRegister(regSP)); if (m_debugOutput) m_opcodeText.AppendFormat(_T("\n")); if (m_debugOutput) ATLTRACE(m_opcodeText); if (bProgramCounterChanged) { std::for_each(m_setCallbacks.begin(), m_setCallbacks.end(), [](IProcessorCallback* callback) { callback->OnProgramCounterChange(); }); } } void Processor6510::Return() { BYTE bRetLow = Pop(); BYTE bRetHigh = Pop(); m_wProgramCounter = LE2WORD(bRetLow, bRetHigh) + 1; } void Processor6510::Interrupt(C64::InterruptType enInterruptType) { ATLASSERT(enInterruptType == interruptTypeIRQ_VIC); // only VIC interrupt is supported enInterruptType; // push addr of next opcode WORD wAddr = m_wProgramCounter; Push(static_cast<BYTE>(wAddr >> 8)); Push(static_cast<BYTE>(wAddr & 0xff)); // note: bit 4 (break) is unset Push(GetRegister(regSR) | c_bStatusMaskAlwaysSet & (~C64::flagBreak)); // set interrupt bit, so that no further interrupts may occur SetFlag(C64::flagInterrupt, true); m_wProgramCounter = m_memoryManager.Peek16(0xfffe); } BYTE Processor6510::Load(WORD wAddr) { std::for_each(m_setCallbacks.begin(), m_setCallbacks.end(), [wAddr](IProcessorCallback* callback) { callback->OnLoad(wAddr); }); return m_memoryManager.Peek(wAddr); } void Processor6510::Store(WORD wAddr, BYTE bValue) { std::for_each(m_setCallbacks.begin(), m_setCallbacks.end(), [wAddr](IProcessorCallback* callback) { callback->OnStore(wAddr); }); m_memoryManager.Poke(wAddr, bValue); } WORD Processor6510::FetchAddress(AddressingMode enAddressingMode) { WORD wAddr = m_wProgramCounter++; BYTE bArg1 = Load(wAddr); switch (enAddressingMode) { case addrImmediate: //wAddr = wAddr; if (m_debugOutput) m_opcodeText.AppendFormat(_T("#$%02x"), bArg1); break; case addrZeropage: wAddr = static_cast<WORD>(bArg1); if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%02x"), bArg1); break; case addrAbsolute: wAddr = LE2WORD(bArg1, Load(m_wProgramCounter++)); if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%04x"), wAddr); break; case addrZeropageIndexedX: // zpx = $00,X // note: adding x wraps around on zeropage wAddr = (static_cast<WORD>(bArg1) + GetRegister(regX)) & 0xFF; if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%02x,x"), bArg1); break; case addrZeropageIndexedY: // zpy = $00,Y // note: adding y wraps around on zeropage wAddr = (static_cast<WORD>(bArg1) + GetRegister(regY)) & 0xFF; if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%02x,y"), bArg1); break; case addrIndirectZeropageIndexedX: // izx = ($00,X) wAddr = Load16((bArg1 + GetRegister(regX)) & 0xff); if (m_debugOutput) m_opcodeText.AppendFormat(_T("($%02x,x)"), bArg1); break; case addrIndirectZeropageIndexedY: // izy = ($00),Y wAddr = Load16(static_cast<WORD>(bArg1)) + GetRegister(regY); if (m_debugOutput) m_opcodeText.AppendFormat(_T("($%02x),y"), bArg1); break; case addrAbsoluteIndexedX: wAddr = LE2WORD(bArg1, Load(m_wProgramCounter++)); if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%04x,x"), wAddr); wAddr = wAddr + GetRegister(regX); break; case addrAbsoluteIndexedY: wAddr = LE2WORD(bArg1, Load(m_wProgramCounter++)); if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%04x,y"), wAddr); wAddr = wAddr + GetRegister(regY); break; case addrIndirect: { BYTE bArg2 = Load(m_wProgramCounter++); wAddr = LE2WORD(bArg1, bArg2); if (m_debugOutput) m_opcodeText.AppendFormat(_T("($%04x)"), wAddr); BYTE bArg3 = Load(wAddr++); if ((wAddr & 0xff) == 0) // on page boundary, fetch byte from previous page wAddr -= 0x0100; bArg2 = Load(wAddr); wAddr = LE2WORD(bArg3, bArg2); } break; case addrRelative: if (bArg1 < 0x80) wAddr = m_wProgramCounter + bArg1; else wAddr = m_wProgramCounter - (bArg1 ^ 0xff) - 1; break; default: ATLASSERT(false); break; } return wAddr; } void Processor6510::Push(BYTE bData) { BYTE bSP = GetRegister(regSP); Store(0x0100 + bSP, bData); SetRegister(regSP, (bSP - 1) & 0xff); } BYTE Processor6510::Pop() { BYTE bSP = GetRegister(regSP); bSP = (bSP + 1) & 0xff; SetRegister(regSP, bSP); BYTE bValue = Load(0x0100 + bSP); return bValue; } void Processor6510::LoadRegister(RegisterID enRegisterID, AddressingMode enAddressingMode) { if (m_debugOutput) { switch (enRegisterID) { case regA: m_opcodeText.AppendFormat(_T("LDA ")); break; case regX: m_opcodeText.AppendFormat(_T("LDX ")); break; case regY: m_opcodeText.AppendFormat(_T("LDY ")); break; default: ATLASSERT(false); break; }; } WORD wAddr = FetchAddress(enAddressingMode); BYTE bValue = Load(wAddr); // hide "from" addr in some addressing modes if (m_debugOutput) { if (enAddressingMode != addrImmediate && enAddressingMode != addrZeropage && enAddressingMode != addrAbsolute) m_opcodeText.AppendFormat(_T(" (from $%04x)"), wAddr); m_opcodeText.AppendFormat(_T(" (new value #$%02x)"), bValue); } SetRegister(enRegisterID, bValue); // set status flags SetFlag(flagZero, bValue == 0); SetFlag(flagNegative, (bValue & 0x80) != 0); // count cycles if (enRegisterID == regA) { // add extra cycle when page boundary is crossed if ((enAddressingMode == addrIndirectZeropageIndexedY && enRegisterID == regA) || (enAddressingMode == addrAbsoluteIndexedX && (enRegisterID == regA || enRegisterID == regY)) || (enAddressingMode == addrAbsoluteIndexedY && (enRegisterID == regA || enRegisterID == regX))) { BYTE bReg = GetRegister(enAddressingMode == addrAbsoluteIndexedX ? regX : regY); // page boundary was crossed while adding register? if ((wAddr & 0xff00) != ((wAddr - bReg) & 0xff00)) m_uiElapsedCycles++; } } } void Processor6510::StoreRegister(RegisterID enRegisterID, AddressingMode enAddressingMode) { ATLASSERT(enAddressingMode != addrImmediate); if (m_debugOutput) { switch (enRegisterID) { case regA: m_opcodeText.AppendFormat(_T("STA ")); break; case regX: m_opcodeText.AppendFormat(_T("STX ")); break; case regY: m_opcodeText.AppendFormat(_T("STY ")); break; default: ATLASSERT(false); break; }; } BYTE bValue = GetRegister(enRegisterID); WORD wAddr = FetchAddress(enAddressingMode); if (m_debugOutput) { // hide "to" addr in some addressing modes if (enAddressingMode != addrZeropage && enAddressingMode != addrAbsolute) m_opcodeText.AppendFormat(_T(" (to $%04x)"), wAddr); } Store(wAddr, bValue); } void Processor6510::TransferRegister(RegisterID enRegSource, RegisterID enRegTarget) { if (m_debugOutput) { m_opcodeText.AppendFormat( _T("T%c%c"), enRegSource == regA ? _T('A') : enRegSource == regX ? _T('X') : enRegSource == regY ? _T('X') : _T('S'), enRegTarget == regA ? _T('A') : enRegSource == regX ? _T('X') : enRegSource == regY ? _T('X') : _T('S')); } BYTE bValue = GetRegister(enRegSource); SetRegister(enRegTarget, bValue); // set status flags; not when stack pointer is target if (enRegTarget != regSP) { SetFlag(flagZero, bValue == 0); SetFlag(flagNegative, (bValue & 0x80) != 0); } } void Processor6510::IncDecRegister(RegisterID enRegister, AddressingMode enAddressingMode, bool bIncrease) { BYTE bValue; if (enRegister == regA) // accumulator really means "modify memory" { if (m_debugOutput) m_opcodeText.AppendFormat(bIncrease ? _T("INC ") : _T("DEC ")); // only some addressing modes are allowed ATLASSERT(enAddressingMode == addrZeropage || enAddressingMode == addrZeropageIndexedX || enAddressingMode == addrAbsolute || enAddressingMode == addrAbsoluteIndexedX); WORD wAddr = FetchAddress(enAddressingMode); bValue = Load(wAddr); bValue += bIncrease ? 1 : 0xFF; Store(wAddr, bValue); } else if (enRegister == regX || enRegister == regY) { ATLASSERT(enAddressingMode == addrImplicit); bValue = GetRegister(enRegister); bValue += bIncrease ? 1 : 0xFF; SetRegister(enRegister, bValue); if (m_debugOutput) { m_opcodeText.AppendFormat(_T("%s%c (new value #$%02x)"), bIncrease ? _T("IN") : _T("DE"), enRegister == regX ? _T('X') : _T('Y'), bValue); } } else { ATLASSERT(false); return; } // set status register SetFlag(flagZero, bValue == 0); SetFlag(flagNegative, (bValue & 0x80) != 0); } void Processor6510::CompareRegister(RegisterID enRegisterID, AddressingMode enAddressingMode) { BYTE bValueReg = GetRegister(enRegisterID); if (m_debugOutput) { switch (enRegisterID) { case regA: m_opcodeText.AppendFormat(_T("CMP ")); break; case regX: m_opcodeText.AppendFormat(_T("CPX ")); break; case regY: m_opcodeText.AppendFormat(_T("CPY ")); break; default: ATLASSERT(false); break; }; } // some addressing modes are not allowed for CPX and CPY if (enAddressingMode == addrZeropageIndexedX || enAddressingMode == addrIndirectZeropageIndexedX || enAddressingMode == addrIndirectZeropageIndexedY || enAddressingMode == addrAbsoluteIndexedX || enAddressingMode == addrAbsoluteIndexedY) ATLASSERT(enRegisterID == regA); // addressing mode not allowed with x or y register WORD wAddr = FetchAddress(enAddressingMode); BYTE bValue2 = Load(wAddr); // set flags BYTE bResult = bValueReg - bValue2; SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, bResult >= 0x80); SetFlag(flagCarry, bValueReg >= bValue2); if (enRegisterID == regA) { // count cycles; add extra cycle when page boundary is crossed if (enAddressingMode == addrIndirectZeropageIndexedY || enAddressingMode == addrAbsoluteIndexedX || enAddressingMode == addrAbsoluteIndexedY) { BYTE bReg = GetRegister(enAddressingMode == addrAbsoluteIndexedX ? regX : regY); // page boundary was crossed while adding register? if ((wAddr & 0xff00) != ((wAddr - bReg) & 0xff00)) m_uiElapsedCycles++; } } } void Processor6510::Branch(BYTE bOpcode) { WORD wLastPC = m_wProgramCounter; bool bNegate = false; C64::ProcessorFlag flag; if (m_debugOutput) { switch (bOpcode) { // branch opcodes case opBPL: m_opcodeText.AppendFormat(_T("BPL ")); break; case opBMI: m_opcodeText.AppendFormat(_T("BMI ")); break; case opBVC: m_opcodeText.AppendFormat(_T("BVC ")); break; case opBVS: m_opcodeText.AppendFormat(_T("BVS ")); break; case opBCC: m_opcodeText.AppendFormat(_T("BCC ")); break; case opBCS: m_opcodeText.AppendFormat(_T("BCS ")); break; case opBNE: m_opcodeText.AppendFormat(_T("BNE ")); break; case opBEQ: m_opcodeText.AppendFormat(_T("BEQ ")); break; default: ATLASSERT(false); return; } } switch (bOpcode) { // branch opcodes case opBPL: flag = flagNegative; bNegate = true; break; // branch when negative clear case opBMI: flag = flagNegative; break; // branch when negative set case opBVC: flag = flagOverflow; bNegate = true; break; case opBVS: flag = flagOverflow; break; case opBCC: flag = flagCarry; bNegate = true; break; case opBCS: flag = flagCarry; break; case opBNE: flag = flagZero; bNegate = true; break; // branch when zero clear case opBEQ: flag = flagZero; break; // branch when zero set default: ATLASSERT(false); return; } bool bBranch = GetFlag(flag); if (bNegate) bBranch = !bBranch; WORD wAddr = FetchAddress(addrRelative); if (m_debugOutput) m_opcodeText.AppendFormat(_T("$%04x"), wAddr); if (bBranch) { m_wProgramCounter = wAddr; // branch taken: add one cycle m_uiElapsedCycles++; // page crossed? then add another one if ((wLastPC && 0xff00) != (m_wProgramCounter & 0xff00)) m_uiElapsedCycles++; } else { if (m_debugOutput) m_opcodeText.AppendFormat(_T(" (not taken)")); } } void Processor6510::LogicalOperation(C64::LogicalOperation enLogicalOperation, AddressingMode enAddressingMode) { if (m_debugOutput) { switch (enLogicalOperation) { case logicalOperationOra: m_opcodeText.AppendFormat(_T("ORA ")); break; case logicalOperationAnd: m_opcodeText.AppendFormat(_T("AND ")); break; case logicalOperationEor: m_opcodeText.AppendFormat(_T("EOR ")); break; default: ATLASSERT(false); } } BYTE bOperand1 = GetRegister(regA); WORD wAddr = FetchAddress(enAddressingMode); BYTE bOperand2 = Load(wAddr); BYTE bResult; switch (enLogicalOperation) { case logicalOperationOra: bResult = bOperand1 | bOperand2; break; case logicalOperationAnd: bResult = bOperand1 & bOperand2; break; case logicalOperationEor: bResult = bOperand1 ^ bOperand2; break; default: ATLASSERT(false); return; } SetRegister(regA, bResult); // set flags SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, (bResult & 0x80) != 0); if (m_debugOutput) m_opcodeText.AppendFormat(_T(" (new value #$%02x)"), bResult); // count cycles; add extra cycle when page boundary is crossed if (enAddressingMode == addrIndirectZeropageIndexedY || enAddressingMode == addrAbsoluteIndexedX || enAddressingMode == addrAbsoluteIndexedY) { BYTE bReg = GetRegister(enAddressingMode == addrAbsoluteIndexedX ? regX : regY); // page boundary was crossed while adding register? if ((wAddr & 0xff00) != ((wAddr - bReg) & 0xff00)) m_uiElapsedCycles++; } } void Processor6510::ArithmeticOperation(C64::ArithmeticOperation enArithmeticOperation, AddressingMode enAddressingMode) { if (m_debugOutput) { switch (enArithmeticOperation) { case arithmeticOperationAdc: m_opcodeText.AppendFormat(_T("ADC ")); break; case arithmeticOperationSbc: m_opcodeText.AppendFormat(_T("SBC ")); break; default: ATLASSERT(false); } } BYTE bOperand1 = GetRegister(regA); WORD wAddr = FetchAddress(enAddressingMode); BYTE bOperand2 = Load(wAddr); BYTE bResult; switch (enArithmeticOperation) { case arithmeticOperationAdc: { WORD wResult; if (!GetFlag(flagDecimal)) { wResult = bOperand1 + bOperand2 + (GetFlag(flagCarry) ? 1 : 0); bResult = static_cast<BYTE>(wResult & 0xff); // set flags SetFlag(flagCarry, wResult > 0xff); // change of sign? bool bOverflow = !((bOperand1 ^ (bOperand2)) & 0x80) && ((bOperand1 ^ bResult) & 0x80); SetFlag(flagOverflow, bOverflow); SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, (bResult & 0x80) != 0); } else { // decimal mode // calculate the lower and upper nibbles separately BYTE bLow = (bOperand1 & 0x0f) + (bOperand2 & 0x0f) + (GetFlag(flagCarry) ? 1 : 0); BYTE bHigh = (bOperand1 >> 4) + (bOperand2 >> 4) + (bLow > 9 ? 1 : 0); // BCD fixup for lower nibble if (bLow > 9) bLow += 6; // set flags // zero flag is set just like in binary mode WORD wResultBin = bOperand1 + bOperand2 + (GetFlag(flagCarry) ? 1 : 0); SetFlag(flagZero, (wResultBin & 0xff) == 0); // negative and overflow flags are set with the same logic as in // binary mode, but after fixing the lower nibble SetFlag(flagNegative, (bHigh & 8) != 0); bool bOverflow = (((bHigh << 4) ^ bOperand1) & 0x80) && !((bOperand1 ^ bOperand2) & 0x80); SetFlag(flagOverflow, bOverflow); // BCD fixup for upper nibble if (bHigh > 9) bHigh += 6; // carry is the only flag set after fixing the result SetFlag(flagCarry, bHigh > 15); wResult = (bLow & 0x0f) | (static_cast<WORD>(bHigh) << 4); bResult = static_cast<BYTE>(wResult & 0xff); } } break; case arithmeticOperationSbc: { if (!GetFlag(flagDecimal)) { WORD wResult = bOperand1 - bOperand2 - (GetFlag(flagCarry) ? 0 : 1); bResult = static_cast<BYTE>(wResult & 0xff); // set flags SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, (bResult & 0x80) != 0); SetFlag(flagCarry, wResult < 0x100); // underflow when result is 0xff?? bool bOverflow = ((bOperand1 ^ wResult) & 0x80) && ((bOperand1 ^ bOperand2) & 0x80); SetFlag(flagOverflow, bOverflow); } else { // decimal mode // calculate lower nibble BYTE bLow = (bOperand1 & 0xf) - (bOperand2 & 0xf) - (GetFlag(flagCarry) ? 0 : 1); // calculate upper nibble //BYTE bHigh = (bOperand1 >> 4) - (bOperand2 >> 4) - ((bLow & 16) != 0 ? 1 : 0); BYTE bHigh = (bOperand1 >> 4) - (bOperand2 >> 4) - ((bLow & 16) != 0 ? 1 : 0); // BCD fixup for lower nibble if (bLow & 0x10) bLow -= 6; // BCD fixup for upper nibble if (bHigh & 0x10) bHigh -= 6; // set flags WORD wResultBin = (bOperand1 - bOperand2 - (GetFlag(flagCarry) ? 0 : 1)); SetFlag(flagZero, (wResultBin & 0xff) == 0); SetFlag(flagNegative, (wResultBin & 0x80) != 0); SetFlag(flagCarry, wResultBin < 0x100); bool bOverflow = ((bOperand1 ^ wResultBin) & 0x80) && ((bOperand1 ^ bOperand2) & 0x80); SetFlag(flagOverflow, bOverflow); WORD wResult = (bLow & 0x0f) | (static_cast<WORD>(bHigh) << 4); bResult = static_cast<BYTE>(wResult & 0xff); } } break; default: ATLASSERT(false); return; } SetRegister(regA, bResult); if (m_debugOutput) m_opcodeText.AppendFormat(_T(" (new value #$%02x)"), bResult); // count cycles; add extra cycle when page boundary is crossed if (enAddressingMode == addrIndirectZeropageIndexedY || enAddressingMode == addrAbsoluteIndexedX || enAddressingMode == addrAbsoluteIndexedY) { BYTE bReg = GetRegister(enAddressingMode == addrAbsoluteIndexedX ? regX : regY); // page boundary was crossed while adding register? if ((wAddr & 0xff00) != ((wAddr - bReg) & 0xff00)) m_uiElapsedCycles++; } } void Processor6510::ShiftOperation(C64::ShiftOperation enShiftOperation, AddressingMode enAddressingMode) { if (m_debugOutput) { switch (enShiftOperation) { case shiftOperationAsl: m_opcodeText.AppendFormat(_T("ASL ")); break; case shiftOperationRol: m_opcodeText.AppendFormat(_T("ROL ")); break; case shiftOperationLsr: m_opcodeText.AppendFormat(_T("LSR ")); break; case shiftOperationRor: m_opcodeText.AppendFormat(_T("ROR ")); break; default: ATLASSERT(false); return; } } WORD wAddr = enAddressingMode == addrImplicit ? 0 : FetchAddress(enAddressingMode); BYTE bOperand = enAddressingMode == addrImplicit ? GetRegister(regA) : Load(wAddr); BYTE bResult; bool bCarry = GetFlag(flagCarry); switch (enShiftOperation) { case shiftOperationAsl: // shift left; c = op.bit7, a = op * 2; bCarry = (bOperand & 0x80) != 0; // bit 7 -> carry bResult = bOperand << 1; break; case shiftOperationLsr: // shift right; c = op.bit0, a = op / 2 bCarry = (bOperand & 1) != 0; // bit 0 -> carry bResult = bOperand >> 1; break; case shiftOperationRol: // roll left; c = op.bit7, a = op * 2 + c bResult = (bOperand << 1) | (bCarry ? 1 : 0); bCarry = (bOperand & 0x80) != 0; // bit 7 -> carry break; case shiftOperationRor: // roll right, c = op.bit0, a = op / 2 + 128 * c bResult = (bOperand >> 1) | (bCarry ? 0x80 : 0); bCarry = (bOperand & 1) != 0; // bit 0 -> carry break; default: ATLASSERT(false); return; } if (enAddressingMode == addrImplicit) SetRegister(regA, bResult); else Store(wAddr, bResult); if (m_debugOutput) m_opcodeText.AppendFormat(_T(" (new value #$%02x)"), bResult); // set flags SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, (bResult & 0x80) != 0); SetFlag(flagCarry, bCarry); } void Processor6510::BitOperation(AddressingMode enAddressingMode) { if (m_debugOutput) m_opcodeText.AppendFormat(_T("BIT ")); WORD wAddr = FetchAddress(enAddressingMode); BYTE bValue = Load(wAddr); BYTE bResult = GetRegister(regA) & bValue; // set flags SetFlag(flagZero, bResult == 0); SetFlag(flagNegative, (bValue & 0x80) != 0); SetFlag(flagOverflow, (bValue & 0x40) != 0); } void Processor6510::SetFlagOperation(C64::ProcessorFlag enFlag, bool bFlag) { if (m_debugOutput) { m_opcodeText.AppendFormat(bFlag ? _T("SE") : _T("CL")); switch (enFlag) { case flagCarry: m_opcodeText.AppendFormat(_T("C")); break; case flagDecimal: m_opcodeText.AppendFormat(_T("D")); break; case flagInterrupt: m_opcodeText.AppendFormat(_T("I")); break; case flagOverflow: m_opcodeText.AppendFormat(_T("O")); break; default: ATLASSERT(false); break; } } SetFlag(enFlag, bFlag); }
#include<stdio.h> #include<malloc.h> struct node{ int data; struct node *next; }; int reverse(struct node **); int push(struct node **,int ); int printList(struct node *); int main(){ struct node *head; push(&head,22); push(&head,11); push(&head,4); reverse(&head); printList(head); return 0; } int reverse(struct node **head){ struct node *result=NULL; struct node *curr=*head; struct node *next; while(curr!=NULL){ next=curr->next; curr->next=result; result=curr; curr=next; } *head=result; } int push(struct node **head,int new_data){ struct node *temp=(struct node *)malloc(sizeof(struct node)); temp->data=new_data; temp->next=*head; *head=temp; } int printList(struct node *head){ while(head!=NULL){ printf(" %d ", head->data); head=head->next; } }
#include <iostream> using namespace std; int main(){ int r; cout << "enter number of rows"; cin >> r; for(int i=0; i< r; i++){ for(int j=0; j <= i; j++) {cout << "*"; if(j==i){cout << endl;} } } }
#include "coubsArmyWidget.h" #include <QScreen> void CoubsArmy::initializeGL() { colorOwner.setSources({&ambientLight , &directionLight , &pointLight}); ambientLight.setColor(QColor(255,0,0)); directionLight.setPosition(QVector4D( QVector3D(1,0,0), 1 )); directionLight.setColor(QColor(255,0,0)); directionLight.off(); pointLight.setPosition(QVector4D( QVector3D(0,0,-15), 1 )); pointLight.setColor(QColor(255,0,0)); initMatrix(); setRotate(false); initTextures(); initProgram(); initShadersParam(); initVaoVbo(); initObject(); m_vbo->allocate( object.vertexs.data(), object.vertexs.size() * sizeof(Vertex)); m_program->enableAttributeArray("posAttr"); m_program->setAttributeBuffer("posAttr", GL_FLOAT, offsetof(Vertex, vertex), 3, sizeof(Vertex)); m_program->enableAttributeArray("norAttr"); m_program->setAttributeBuffer("norAttr", GL_FLOAT, offsetof(Vertex, normal), 3, sizeof(Vertex)); m_program->enableAttributeArray("texCoord"); m_program->setAttributeBuffer("texCoord", GL_FLOAT, offsetof(Vertex, texCoord), 2, sizeof(Vertex)); m_vbo->release(); } void CoubsArmy::paintGL() { connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(10); const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); m_vao->bind(); m_program->bind(); QMatrix4x4 projection; projection.perspective(60.0f, 4.0f / 3.0f, 0.1f, 100.0f); glEnable(GL_DEPTH_TEST); colorOwner.checkColor(); for (auto it = matrix.begin() ; it != matrix.end() ; ++it) { auto mat = it->getMatrix(); m_program->setUniformValue(coefs.m_ka , coefs.ka); m_program->setUniformValue(coefs.m_kd , coefs.kd); m_program->setUniformValue(coefs.m_k , coefs.k); m_program->setUniformValue(coefs.m_p , coefs.p); m_program->setUniformValue(pointLight.getFlagUniform() , pointLight.state()); m_program->setUniformValue(pointLight.getPosUniform() , pointLight.getPosition()); m_program->setUniformValue(pointLight.getColorUniform(), pointLight.getColor()); m_program->setUniformValue(directionLight.getFlagUniform() , directionLight.state()); m_program->setUniformValue(directionLight.getPosUniform() , directionLight.getPosition()); m_program->setUniformValue(directionLight.getColorUniform(), directionLight.getColor()); m_program->setUniformValue(ambientLight.getColorUniform() , ambientLight.getColor()); m_program->setUniformValue(ambientLight.getFlagUniform() , ambientLight.state()); m_program->setUniformValue(m_trMatrix , mat); m_program->setUniformValue("textureMap",0); glActiveTexture(GL_TEXTURE0); texture->bind(); m_program->setUniformValue("normalMap",1); glActiveTexture(GL_TEXTURE1); normalMap->bind(); m_program->setUniformValue(m_matrixUniform, projection*mat); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDrawArrays(GL_TRIANGLES, 0, object.vertexs.size()); } m_program->release(); ++m_frame; } void CoubsArmy::initTextures() { texture.reset(new QOpenGLTexture(QImage("D:\\source\\repos\\Qt\\Earth\\Earth\\Earth_Albedo.jpg"))); texture->setMinificationFilter(QOpenGLTexture::Nearest); texture->setMagnificationFilter(QOpenGLTexture::Linear); texture->setWrapMode(QOpenGLTexture::Repeat); normalMap.reset(new QOpenGLTexture(QImage("D:\\source\\repos\\Qt\\Earth\\Earth\\Earth_NormalMap.jpg"))); } void CoubsArmy::initProgram() { initializeOpenGLFunctions(); f = QOpenGLContext::currentContext()->functions(); m_program = new QOpenGLShaderProgram(this); m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, "D:\\source\\repos\\Qt\\Earth\\Earth\\vertexShaider.glsl"); m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, "D:\\source\\repos\\Qt\\Earth\\Earth\\fragmentShaider.glsl"); m_program->link(); m_program->bind(); } void CoubsArmy::initVaoVbo() { m_vao = new QOpenGLVertexArrayObject; if (m_vao->create()) m_vao->bind(); m_vbo = new QOpenGLBuffer; m_vbo->create(); m_vbo->bind(); } void CoubsArmy::initMatrix() { matrix.clear(); ObjectModel objm; objm.setTranslate(0, 0.0f, -2.5f); objm.setRotate(screen()->refreshRate()/100,0.0f,1.0f,0.0f); matrix.push_back(objm); } void CoubsArmy::initShadersParam() { m_posAttr = m_program->attributeLocation("posAttr"); Q_ASSERT(m_posAttr != -1); m_norAttr = m_program->attributeLocation("norAttr"); Q_ASSERT(m_matrixUniform != -1); m_matrixUniform = m_program->uniformLocation("matrix"); Q_ASSERT(m_matrixUniform != -1); m_trMatrix = m_program->uniformLocation("trmatrix"); Q_ASSERT(m_trMatrix != -1); coefs.m_ka = m_program->uniformLocation("ka"); Q_ASSERT(coefs.m_ka != -1); coefs.m_kd = m_program->uniformLocation("kd"); Q_ASSERT(coefs.m_kd != -1); coefs.m_k = m_program->uniformLocation("k"); Q_ASSERT(coefs.m_k != -1); coefs.m_p = m_program->uniformLocation("p"); Q_ASSERT(coefs.m_p != -1); pointLight.setPosUniform( m_program->uniformLocation("pointPos")); Q_ASSERT(pointLight.getPosUniform() != -1); pointLight.setColorUniform( m_program->uniformLocation("pointColor")); Q_ASSERT(pointLight.getColorUniform() != -1); pointLight.setFlagUniform( m_program->uniformLocation("pointFlag")); Q_ASSERT(pointLight.getFlagUniform() != -1); directionLight.setPosUniform( m_program->uniformLocation("directionPos")); Q_ASSERT(directionLight.getPosUniform() != -1); directionLight.setColorUniform( m_program->uniformLocation("directionColor")); Q_ASSERT(directionLight.getColorUniform() != -1); directionLight.setFlagUniform( m_program->uniformLocation("directionFlag")); Q_ASSERT(directionLight.getFlagUniform() != -1); ambientLight.setColorUniform( m_program->uniformLocation("ambientColor")); Q_ASSERT(ambientLight.getColorUniform() != -1); ambientLight.setFlagUniform( m_program->uniformLocation("ambientFlag")); Q_ASSERT(ambientLight.getFlagUniform() != -1); } void CoubsArmy::initObject() { Sphere s(30,30); object.setObject(s.getVertex() , s.getNormals(),s.getTexCoord()); } void CoubsArmy::setRotation(std::vector<GLfloat> rt) { for (auto it = matrix.begin() ; it!=matrix.end() ; ++it ) { it->setRotate(rt[0],rt[1],rt[2]); } } void CoubsArmy::setColor(QColorDialog* cd , int active) { colorOwner.setActive(active); colorOwner.setDialog(cd); } void CoubsArmy::setSphere(float x, float y) { m_vbo->bind(); Sphere s(x,y); object.setObject(s.getVertex() , s.getNormals(),s.getTexCoord()); m_vbo->allocate( object.vertexs.data(), object.vertexs.size() * sizeof(Vertex)); m_vbo->release(); } void CoubsArmy::setRotate(bool fl) { for (auto it = matrix.begin() ; it!=matrix.end() ; ++it ) { it->rotate(fl); } } void CoubsArmy::setLightCoefs(std::vector<int> vec) { coefs.ka = static_cast<float>(vec[0])/100; coefs.kd = static_cast<float>(vec[1])/100; coefs.k = static_cast<float>(vec[2])/10; coefs.p = vec[3]; } void CoubsArmy::setActivateLight(std::vector<bool> vec) { directionLight.setState(vec[0]); pointLight.setState(vec[1]); } void CoubsArmy::setDirectionLightPosition(QVector4D pos) { directionLight.setPosition(pos); } void CoubsArmy::setPointLightPosition(QVector4D pos) { pointLight.setPosition(pos); }
BinaryTreeNode* Construct(int* preorder,int* inorder,int length) { if(preorder==nullptr||inorder==nullptr||length<=0) return nullptr; retr ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1); } BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder) { int rootValue=startPreorder[0]; BinaryTreeNode* root=new BinaryTreeNode(); root->m_nValue=rootValue; root->m_pLeft=root->m_pRight=nullptr; if(startPreorder==endPreorder) { if(startInorder==endInorder&&*startPreorder==*startInorder) { return root; }else { throw std::exception("Invalid input"); } int* rootInorder=startInorder; while (rootInorder<=endInorder&&*rootInorder!=rootValue) { ++rootInorder; } if(rootInorder==endInorder&&*rootInorder!=rootValue) { throw std::exception("Invalid input"); } int leftLength=rootInorder-startInorder; int* leftLength=rootInorder-startInorder; int*leftPreorderEnd=startPreorder+leftLength; if(leftLength>0) { root->m_pLeft=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1); } if(leftLength<endPreorder-startPreorder) { root->m_pRight=ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder); } return root; } }
/* * fileio.cpp * * Created on: Feb 14, 2021 * Author: Madison Callan */ #include "../includes/fileio.h" using namespace std; int loadData(const std::string filename, vector<process> &myProcesses){ return UNIMPLEMENTED; } int saveData(const std::string filename, vector<process> &myProcesses){ return UNIMPLEMENTED; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __SUBTITLE_SOURCE_H__ #define __SUBTITLE_SOURCE_H__ #include <pthread.h> #include <stdio.h> #include <unistd.h> #include "multimedia/mm_cpp_utils.h" #include "multimedia/mm_debug.h" #include "multimedia/component.h" #include "multimedia/mmmsgthread.h" #include "multimedia/media_attr_str.h" #include "multimedia/media_monitor.h" #include <multimedia/clock.h> #include "../clock_wrapper.h" #include <queue> #include <algorithm> namespace YUNOS_MM { class SubtitleSource : public PlaySourceComponent, public MMMsgThread { public: SubtitleSource(); virtual ~SubtitleSource(); public: virtual mm_status_t init(); virtual void uninit(); virtual const char * name() const { return "SubtitleSource"; } COMPONENT_VERSION; virtual ReaderSP getReader(MediaType mediaType); virtual mm_status_t addSink(Component * component, MediaType mediaType) { return MM_ERROR_IVALID_OPERATION; } virtual mm_status_t prepare(); virtual mm_status_t start(); virtual mm_status_t resume(); virtual mm_status_t stop(); virtual mm_status_t pause() { return MM_ERROR_SUCCESS; } virtual mm_status_t seek(int msec, int seekSequence); virtual mm_status_t reset(); virtual mm_status_t flush(); virtual mm_status_t setUri(const char * uri, const std::map<std::string, std::string> * headers = NULL); virtual mm_status_t setUri(int fd, int64_t offset, int64_t length) { return MM_ERROR_UNSUPPORTED; } virtual const std::list<std::string> & supportedProtocols() const; virtual bool isSeekable() { return true; } virtual mm_status_t getDuration(int64_t & durationMs) { return MM_ERROR_IVALID_OPERATION;} virtual bool hasMedia(MediaType mediaType) { return true;} virtual MediaMetaSP getMetaData() { return MediaMetaSP((MediaMeta*)NULL); } virtual MMParamSP getTrackInfo() { return nilParam; } virtual mm_status_t selectTrack(MediaType mediaType, int index) { return MM_ERROR_SUCCESS; } virtual int getSelectedTrack(MediaType mediaType) { return 0;} virtual mm_status_t setClock(ClockSP clock); private: mm_status_t internalStop(); void releaseBuffers(); mm_status_t createPriv(); struct SubtitleBuffer { uint32_t index; uint64_t startPositionMs; uint64_t endPositionMs; std::string text; }; typedef MMSharedPtr <SubtitleBuffer> SubtitleBufferSP; class SubtitleSourceReader : public Reader { public: SubtitleSourceReader(SubtitleSource *source, MediaType type) { mSource = source; mType = type; } ~SubtitleSourceReader() { } virtual mm_status_t read(MediaBufferSP & buffer); virtual MediaMetaSP getMetaData(); private: SubtitleSource *mSource; MediaType mType; DECLARE_LOGTAG() }; class ReaderThread : public MMThread { public: ReaderThread(SubtitleSource *source); ~ReaderThread(); void signalExit(); void signalContinue(); static bool releaseInputBuffer(MediaBuffer* mediaBuffer); protected: virtual void main(); private: SubtitleSource *mSource; bool mContinue; DECLARE_LOGTAG() }; typedef MMSharedPtr<ReaderThread> ReaderThreadSP; class Private; typedef std::tr1::shared_ptr<Private> PrivateSP; class Private { public: static PrivateSP create(char* uri); static bool comp (SubtitleBufferSP a,SubtitleBufferSP b) { return (a->startPositionMs < b->startPositionMs); } void sortByStartTime() {sort(mSubtitleSource->mSubtitleBuffers.begin(),mSubtitleSource->mSubtitleBuffers.end(), comp); } mm_status_t init(SubtitleSource *subtitlesource); virtual void parseTime(const char *time, size_t pos, uint64_t& start, uint64_t& end); virtual mm_status_t parseFile(const char *uri) { return MM_ERROR_UNSUPPORTED; } virtual mm_status_t removeFont() { return MM_ERROR_UNSUPPORTED; } void uninit() {} ~Private() {} Private() : mSubtitleSource(NULL) {} SubtitleSource *mSubtitleSource; MM_DISALLOW_COPY(Private); }; private: std::queue<MediaBufferSP> mBuffers; std::vector<SubtitleBufferSP> mSubtitleBuffers; Lock mLock; Condition mCondition; bool mIsPaused; ReaderThreadSP mReaderThread; std::string mUri; uint32_t mCurrentIndex; class ParseSrt; class ParseSub; class ParseVTT; class ParseASS; class ParseTXT; class ParseSMI; PrivateSP mPriv; ClockWrapperSP mClockWrapper; private: DECLARE_MSG_LOOP() DECLARE_MSG_HANDLER(onPrepare) DECLARE_MSG_HANDLER(onStart) DECLARE_MSG_HANDLER(onResume) DECLARE_MSG_HANDLER(onFlush) DECLARE_MSG_HANDLER(onStop) DECLARE_MSG_HANDLER(onReset) MM_DISALLOW_COPY(SubtitleSource); private: DECLARE_LOGTAG() }; typedef MMSharedPtr<SubtitleSource> SubtitleSourceSP; } #endif // __SUBTITLE_SOURCE_H__
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or imlied. // See the License for the specific language governing permissions and // limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////// #ifndef __CPUTMATERIALEFFECT_H__ #define __CPUTMATERIALEFFECT_H__ #include "CPUTConfigBlock.h" #include "CPUTRenderStateBlock.h" class CPUTModel; enum CPUTLayerType { CPUT_LAYER_SOLID, CPUT_LAYER_TRANSPARENT, }; //----------------------------------------------------------------------------- static const StringToIntMapEntry pLayerMap[] = { { _L("CPUT_LAYER_SOLID"), CPUT_LAYER_SOLID }, { _L("CPUT_LAYER_TRANSPARENT"), CPUT_LAYER_TRANSPARENT }, { _L(""), -1 } }; class CPUTMaterialEffect:public CPUTRefCount { protected: UINT mMaterialNameHash; cString mMaterialName; const CPUTModel *mpModel; // We use pointers to the model and mesh to distinguish instanced materials. int mMeshIndex; CPUTConfigBlock mConfigBlock; CPUTRenderStateBlock *mpRenderStateBlock; // TODO: We could make that a special object, and derive them from material. Not sure that's worth the effort. // The alternative we choose here is to simply comandeer this one, ignoring most of its state and functionality. CPUTMaterialEffect *mpMaterialNextClone; CPUTMaterialEffect *mpMaterialLastClone; // Destructor is not public. Must release instead of delete. virtual ~CPUTMaterialEffect(){ // SAFE_RELEASE(mpRenderStateBlock); // Allocated in derived class, so released there too. } public: CPUTLayerType mLayer; static CPUTMaterialEffect *CreateMaterialEffect( const cString &absolutePathAndFilename, const CPUTModel *pModel=NULL, int meshIndex=-1, CPUT_SHADER_MACRO* pShaderMacros=NULL, int externalCount=0, cString *pExternalName=NULL, float4 *pExternals=NULL, int *pExternalOffset=NULL, int *pExternalSize=NULL ); CPUTMaterialEffect() : mLayer(CPUT_LAYER_SOLID), mpRenderStateBlock(NULL), mpMaterialNextClone(NULL), mpMaterialLastClone(NULL), mMaterialNameHash(0), mpModel(NULL), mMeshIndex(-1) { }; // TODO: Where to put this? UINT CPUTComputeHash( const cString &string ) { size_t length = string.length(); UINT hash = 0; for( size_t ii=0; ii<length; ii++ ) { hash += tolow(string[ii]); } return hash; } UINT GetNameHash() { return mMaterialNameHash; } void SetMaterialName(const cString materialName) { mMaterialName = materialName; mMaterialNameHash = CPUTComputeHash(materialName); } cString *GetMaterialName() { return &mMaterialName; } virtual void ReleaseTexturesAndBuffers() = 0; virtual void RebindTexturesAndBuffers() = 0; virtual void SetRenderStates(CPUTRenderParameters &renderParams) { if( mpRenderStateBlock ) { mpRenderStateBlock->SetRenderStates(renderParams); } } virtual bool MaterialRequiresPerModelPayload() = 0; virtual CPUTMaterialEffect *CloneMaterialEffect( const CPUTModel *pModel=NULL, int meshIndex=-1 ) = 0; CPUTMaterialEffect *GetNextClone() { return mpMaterialNextClone; } const CPUTModel *GetModel() { return mpModel; } int GetMeshIndex() { return mMeshIndex; } virtual CPUTResult LoadMaterialEffect( const cString &fileName, const CPUTModel *pModel=NULL, int meshIndex=-1, CPUT_SHADER_MACRO* pShaderMacros=NULL, int externalCount=0, cString *pExternalName=NULL, float4 *pExternals=NULL, int *pExternalOffset=NULL, int *pExternalSize=NULL ) = 0; }; #endif
 #ifndef __BEGIN_STAGE3__ #define __BEGIN_STAGE3__ #include "..\..\FrameWork\Sprite.h" #include "..\..\FrameWork\SpriteManager.h" //#include "..\..\FrameWork\Managers\SoundManager.h" #include "..\..\FrameWork\InputController.h" #include "..\..\FrameWork\StopWatch.h" #include "../../FrameWork/Scene/PlayScene.h" #include "Scene.h" //#include "..\TextSprite.h" //#include "Stage3.h" class HighScore { public: static char* filehighscore; static int loadHighScore(const char* fileInfoPath); static bool saveHighScore(const char* fileInfoPath, int score); }; class BeginPlayScene : public Scene { public: /* * Khởi tạo màn hình chờ stage 3 * @score: điểm hiện tại. * @rest: số mạng còn lại. */ BeginPlayScene(int score, int rest, int stage = 1); ~BeginPlayScene(); bool init() override; void update(float dt) override; void draw(LPD3DXSPRITE spriteHandle) override; void release() override; void updateInput(float deltatime); private: static const float delaytime; int _score; int _highscore; int _rest; int _stage; Sprite* _waitscreen; StopWatch* _access; TextSprite* _textscore; TextSprite* _textrest; TextSprite* _texthighscore; TextSprite* _textStage; TextSprite* _textStageName; }; #endif // !__BEGIN_STAGE3__
#include <iostream> using namespace std; class LL{ private: struct node{ int data; node *next; }; node *head; node *tail; public: LL(); ~LL(); void InsertNodeAtEnd(int data); void Concatenate(LL & secondlist); void Print(); }; LL::LL(){ head = tail = NULL; } LL::~LL(){ } void LL::InsertNodeAtEnd(int data){ node *temp = new node; temp -> data = data; temp -> next = NULL; if(head==NULL && tail==NULL){ head = tail = temp; return; } tail -> next = temp; tail = temp; } void LL::Concatenate(LL & secondlist){ tail->next = secondlist.head; } void LL::Print(){ node *temp = head; while(temp!=NULL){ cout << temp->data << endl; temp = temp -> next; } } int main(){ LL l1; LL l2; cout << "---First list---" << endl; l1.InsertNodeAtEnd(10); l1.InsertNodeAtEnd(20); l1.InsertNodeAtEnd(30); l1.Print(); cout << "---Second list---" << endl; l2.InsertNodeAtEnd(40); l2.InsertNodeAtEnd(50); l2.InsertNodeAtEnd(60); l2.Print(); cout << "---Concatenated list---" << endl; l1.Concatenate(l2); l1.Print(); return 0; }
#ifndef SOLUTIONDATAIO_H #define SOLUTIONDATAIO_H #include "solutiondataio_global.h" #include "qstring.h" #include "vtkFloatArray.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellType.h" #include "vtkDataSet.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "qmap.h" #include "vtkIdTypeArray.h" #include "vtkUnstructuredGrid.h" #include "vtkPoints.h" #include "vtkMultiBlockDataSet.h" #include <vtkAutoInit.h> #include "qfile.h" #include "qtextstream.h" #include "vtkIdList.h" #include "qdebug.h" #define Data_Interval " " #define Num_ZoneId_Per_Row 10 #define pointsID "POINTS" #define cellsID "CELLS" #define pScalarValID "SCALAR_POINTS_VALUE" #define cScalarValID "SCALAR_CELLS_VALUE" #define pNormalValID "NORMAL_POINTS_VALUE" #define cNormalValID "NORMAL_CELLS_VALUE" #define zoneCellIDList "ZONE_CELL_IDS" #define zoneID "ZONE" #define zoneStartID "zoneStart!" #define zoneEndID "zoneEnd!" #define zonePointsID "ZONE_POINTS" #define zoneCellsID "ZONE_CELLS" #define pZoneScalarValID "ZONE_SCALAR_POINTS_VALUE" #define cZoneScalarValID "ZONE_SCALAR_CELLS_VALUE" #define pZoneNormalValID "ZONE_NORMAL_POINTS_VALUE" #define cZoneNormalValID "ZONE_NORMAL_CELLS_VALUE" #define floatType "FLOAT" class SOLUTIONDATAIO_EXPORT SolutionDataIO { public: SolutionDataIO(); ~SolutionDataIO(); bool writeSolutionData(QString fileName, vtkDataSet* dataSet); bool write_Points(QString fileName, vtkDataSet* dataSet, QString strID); bool write_Cells(QString fileName, vtkDataSet* dataSet, QString strID); bool write_Points_Value(QString fileName, vtkDataSet* dataSet, QString strID); bool write_Cells_Value(QString fileName, vtkDataSet* dataSet, QString strID); bool write_Zones(QString fileName, QMap<QString, vtkSmartPointer<vtkIdTypeArray>> tep_zoneMap); bool write_Zones(QString fileName, vtkMultiBlockDataSet* blockDataSet); bool write_ZonesString(QString fileName, QString strID); vtkDataSet* readSolutionData(QString fileName); bool read_Points(int num_points, vtkUnstructuredGrid* tep_grid1); bool read_Cells(int num_cells, vtkUnstructuredGrid* tep_grid1); bool read_scalarPValue(int num_scalarPVal, QString name, vtkUnstructuredGrid* tep_grid1); bool read_normalPValue(int num_scalarPVal, QString name, vtkUnstructuredGrid* tep_grid1); bool read_scalarCValue(int num_scalarCVal, QString name, vtkUnstructuredGrid* tep_grid1); bool read_normalCValue(int num_scalarCVal, QString name, vtkUnstructuredGrid* tep_grid1); bool read_ZonesCellID(int num_Ids, QString name); QMap<QString, vtkSmartPointer<vtkIdTypeArray>> zoneCell_map; vtkMultiBlockDataSet* blockDataSet; private: int cur_num_points, cur_num_cells; vtkUnstructuredGrid* tep_grid; vtkUnstructuredGrid* tep_zoneGrid; QFile rFile; }; #endif // SOLUTIONDATAIO_H
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include "opencv2/core/core.hpp" using namespace cv; using namespace std; int main() { int i, j, k, B1[256] = { 0 }, G1[256] = { 0 }, R1[256] = { 0 }; Mat img = imread("C:\\Users\\ariji\\Desktop\\Extra\\test1.png", 1); for (i = 0; i < img.rows; i++) { for (j = 0; j < img.cols; j++) { B1[img.at<Vec3b>(i, j)[0]]++; G1[img.at<Vec3b>(i, j)[1]]++; R1[img.at<Vec3b>(i, j)[2]]++; } } for (i = 0; i < 256; i++) { B1[i] = B1[i] / 10; G1[i] = G1[i] / 10; R1[i] = R1[i] / 10; } Mat B(600, 768, CV_8UC3, Scalar(255, 255, 255)); Mat G(600, 768, CV_8UC3, Scalar(255, 255, 255)); Mat R(600, 768, CV_8UC3, Scalar(255, 255, 255)); for (i = 0; i < 256; i++) { for (k = 0; k < 3; k++) { for (j = 0; j < B1[i]; j++) { B.at<Vec3b>(599 - j, 3 * i + k)[1] = 0; B.at<Vec3b>(599 - j, 3 * i + k)[2] = 0; } } } for (i = 0; i < 256; i++) { for (k = 0; k < 3; k++) { for (j = 0; j < G1[i]; j++) { G.at<Vec3b>(599 - j, 3 * i + k)[0] = 0; G.at<Vec3b>(599 - j, 3 * i + k)[2] = 0; } } } for (i = 0; i < 256; i++) { for (k = 0; k < 3; k++) { for (j = 0; j < R1[i]; j++) { R.at<Vec3b>(599 - j, 3 * i + k)[0] = 0; R.at<Vec3b>(599 - j, 3 * i + k)[1] = 0; } } } namedWindow("Image", WINDOW_AUTOSIZE); namedWindow("Histogram_B", WINDOW_AUTOSIZE); namedWindow("Histogram_G", WINDOW_AUTOSIZE); namedWindow("Histogram_R", WINDOW_AUTOSIZE); imshow("Image", img); imshow("Histogram_B", B); imshow("Histogram_G", G); imshow("Histogram_R", R); waitKey(0); return 0; }
// Longest substring without repeating characters #include<iostream> #include "bits/stdc++.h" using namespace std; int main(){ string s; cin>>s; vector<int> dict(256, -1); int maxLen = 0, start = -1; for(int i=0; i<s.size();i++){ if(dict[s[i]] > start){ start = dict[s[i]]; } dict[s[i]] = i; maxLen = max(maxLen, i - start); } cout<<maxLen<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll a, b, v, x; ll solve() { for(int i = 63; i >= 0; i--){ if( (v & (1LL<<i)) ){ x = v; x ^= (1LL << i); for(int j=i-1; j >= 0; j--){ x |= (1LL << j); } break; } } return min(x,b); } int main() { int t; scanf("%d", &t); while(t--) { scanf("%lld %lld %lld", &a, &b, &v); if(v >= b) printf("%lld\n", b-a+1); else if(v < a) printf("0\n"); else { printf("%lld\n", solve()-a+1); } } }
#ifndef MODEL_H #define MODEL_H #include "shader.h" #include "mesh.h" #include <assimp/scene.h> #include <string> #include <vector> using namespace std; class Model { public: // Constructor, expects a filepath to a 3D model Model(const string& path); // Render the model, and thus all its meshes void render(Shader& shader) const; private: // Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector void loadModel(const string& path); // Processes a node in a recursive fashion // Processes each individual mesh located at the node and repeats this process on its children nodes (if any) void processNode(aiNode *node, const aiScene *scene); // Processes mesh Mesh processMesh(aiMesh *mesh, const aiScene *scene); // Checks all material textures of a given type and loads the textures if they're not loaded yet vector<Texture> loadMaterialTextures(aiMaterial *material, aiTextureType type, string type_name); // Load a texture from file unsigned int textureFromFile(const char path[], const string &directory); // Model Data vector<Texture> textures_loaded_; vector<Mesh> meshes_; string directory_; }; #endif
 #include<iostream> #include"enums.hpp" #include"enumTest.hpp" // consider the following to be your existing enum namespace Some { namespace Nested { namespace Namespace { struct Struct { enum class ESomeEnum { a_0 = 1, b_1 = 4, c_2 = 8, d_3 = 3, }; }; }}} // now it is simple to import it: GMacroEnumImport( (Some)(Nested)(Namespace)(Struct), ESomeEnum, a_0, b_1, c_2, d_3 ) int main() { std::cout << meta::enums::toString(Some::Nested::Namespace::Struct::ESomeEnum::a_0) << std::endl; return 0; }
/** @file Fraction.cpp @brief The implementation for Fraction class ... */ #include "Fraction.h" /** Default constructor initializes the fraction to 0/1. numerator and denominator are default initialized THEN it runs the code inside { ... } */ Fraction::Fraction() { numerator = 0; denominator = 1; } /** Initializes fraction to input_numerator/1 @param input_numerator this is the value of the numerator */ Fraction::Fraction(int input_numerator) : numerator(input_numerator), denominator(1) { } /** Initializes fraction to input_numerator/input_denominator @param input_numerator is the initial numerator @param input_denominator is the initial denominator */ Fraction::Fraction(int input_numerator, int input_denominator) : numerator(input_numerator), denominator(input_denominator) { Reduce(); } /** Prints out the fraction in the form n/d */ void Fraction::print() { cout << numerator << "/" << denominator; } /** Performs f += rhs where f is the object calling the function @param rhs is the Fraction object to add to f */ /*Fraction& Fraction::plusEquals(const Fraction& rhs) { // a/b + c/d = (a*d+b*c) / (b*d) int a = numerator; int b = denominator; int c = rhs.numerator; int d = rhs.denominator; numerator = (a*d+b*c); denominator = (b*d); return *this; }; */ /** ... */ Fraction& Fraction::operator+=(const Fraction& rhs) { // a/b + c/d = (a*d+b*c) / (b*d) int a = numerator; int b = denominator; int c = rhs.numerator; int d = rhs.denominator; numerator = (a*d+b*c); denominator = (b*d); Reduce(); return *this; } /** ... .. .. */ Fraction& Fraction::operator*=(const Fraction& rhs) { // a/b * c/d = (a*c) / (b*d) int a = numerator; int b = denominator; int c = rhs.numerator; int d = rhs.denominator; numerator = (a*c); denominator = (b*d); Reduce(); return *this; } /** Critical assumption that b > 0, i.e., denominator is always positive */ inline Fraction& Fraction::operator++() { // a/b + 1 = a/b + b/b = (a+b) / b numerator += denominator; // Maybe we don't need this...we shall ask a number theorist! Reduce(); return *this; } Fraction Fraction::operator++(int unused) { // These two are the same, they construct the object with initial values // provided by *this Fraction clone( *this ); //Fraction clone = *this; // This one would be different, not desireable //Fraction clone; // Construct object first by default //clone = *this; // Assign values from existing object // These three do the same thing. //++*this; this->operator++(); //(*this).operator++(); return clone; } /** performs lhs+rhs fraction arithmetic @param lhs is the left hand side of the addition @param rhs is the right hand side of the addition @returns the value of lhs+rhs. */ Fraction operator+(Fraction lhs, const Fraction& rhs) { return lhs+=rhs; } /** ... */ Fraction operator*(Fraction lhs, const Fraction& rhs) { return lhs*=rhs; } /** ... */ Fraction Fraction::operator-() { Fraction negation( -numerator, denominator); // This operation preserves reduced form. No need to call Reduce(). return negation; } /** Called using Fraction p; +p; */ Fraction Fraction::operator+() { Fraction copy(*this); return copy; } /** ... */ bool operator<(const Fraction& lhs, const Fraction& rhs) { // a/b < c/d ? // First approach: convert to doubles //double left = static_cast<double>(lhs.numerator)/lhs.denominator; //double right = static_cast<double>(rhs.numerator)/rhs.denominator; // Second approach: assume denominators are always > 0. // return a*d < b*c int a = lhs.numerator; int b = lhs.denominator; int c = rhs.numerator; int d = rhs.denominator; return a*d < b*c; } /** ... */ bool operator==(const Fraction& lhs, const Fraction& rhs) { // a/b = c/d // First approach: Cross multiply // a*d = b*c //return ( lhs.numerator*rhs.denominator == lhs.denominator*rhs.numerator); // Second approach: assume fractions are in reduced form, compare numerators // and denominators directly. return ( lhs.numerator == rhs.numerator && rhs.denominator == lhs.denominator); } /** ... */ bool operator!=(const Fraction& lhs, const Fraction& rhs) { return !(lhs==rhs); } /** ... */ bool operator<=(const Fraction& lhs, const Fraction& rhs) { return (lhs < rhs) || (lhs == rhs); } /** ... */ bool operator>=(const Fraction& lhs, const Fraction& rhs) { return !(lhs<rhs); } /** ... */ bool operator>(const Fraction& lhs, const Fraction& rhs) { // Exercise...think about this one. return true; } /** Calculates the greatest common divisor of integers a and b. @param a is one of the values @param b is the second value @return gcd(a,b) */ int gcd(int a, int b) { int t = 0; // loop until reduction is finished while (b != 0) { t = b; b = a % b; a = t; } return a; } /** This reduces the fraction to lowest terms: \n 1. 5/5 --> 1/1 2. 0/a --> 0/1 (assuming a != 0) 3. 0/0 --> Error? 4. 2/4 --> 1/2 5. -3/-5--> 3/5 6. 2/-7 --> -2/7 7. a/0 --> Error? */ void Fraction::Reduce() { // GCD algorithm: int division_factor = gcd(numerator,denominator); // e.g., 15/5, division_factor = 5; // Now divide numeratror and denominator by division_factor numerator /= division_factor; denominator /= division_factor; // a/b, -a/b, a/-b, -a/-b // a/-b OR -a/-b // if( (numerator >0 && denominator<0) || (numerator<0 && denominator < 0) ) { // Equivalent to if( denominator<0 ) { //numerator =- numerator; // not recommended, possible confusion with -= numerator *= -1; denominator *= -1; } // cout << numerator << "/"<<denominator<<endl; } /* // Not necessary once you properly #include <string> bool operator==(const string& lhs, const string& rhs) { for(size_t i=0;i<lhs.size();i++) { if(lhs[i] != rhs[i]) return 0; } return 1; } */ int Fraction::operator[](string& value) { if( value == string("numerator")) return numerator; else if(value == string("denominator") ) return denominator; else return -12345; } int Fraction::operator[](int value) { if( value == 0) return numerator; else if(value == 1) return denominator; else return -12345; } void Fraction::operator()() { numerator = 0; denominator = 1; } //int operator()(int, int); int Fraction::operator()(int a, int b, const string& message, double d) { cout << a << "/"<<b<<endl; if(message == "monkey") cout << "no monkey business here."<<endl; cout<<d<<endl; return static_cast<int>(d); } //Fraction::operator double() { // return static_cast<double>(numerator)/denominator; //} Fraction::operator string() { return string("conversion to string"); }
#include <Windows.h> #include <sstream> typedef unsigned __int64 QWORD; extern "C" __declspec(dllexport) void __cdecl ExportFunc() { MessageBox(NULL, TEXT("dummy export"), TEXT("info"), MB_OK); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { int patchlen = 21; QWORD offset = 0x9d130; DWORD curProtection; DWORD temp; QWORD base = (QWORD)GetModuleHandle("ntdll.dll"); QWORD patchaddr = base + offset; void *ppatchaddr = (void*)patchaddr; /* *std::stringstream ss; *ss << "patch address : 0x" << std::hex << patchaddr; *MessageBox(NULL, ss.str().c_str(), TEXT("info"), MB_OK); */ if (VirtualProtect(ppatchaddr, patchlen, PAGE_EXECUTE_READWRITE, &curProtection) == 0) MessageBox(NULL, TEXT("virtualProtect failed!"), TEXT("fail"), MB_OK | MB_ICONERROR); for(int i=0; i<16; i++) *(BYTE*)(patchaddr+i) = 0x90; *(BYTE*)(patchaddr+16) = 0xb8; for(int i=17; i<21; i++) *(BYTE*)(patchaddr+i) = 0x00; VirtualProtect(ppatchaddr, patchlen, curProtection, &temp); //FreeLibraryAndExitThread(hModule, 0); } return TRUE; }
#pragma once #include "Geometry/Public/Box.h" #include "Geometry/Public/BoundedView.h" namespace Geometry { namespace Index { namespace Detail { template <typename Indexable> long double Content (const Indexable& indexable) { const auto& max = indexable.max_corner(); const auto& min = indexable.min_corner(); return (max.x - min.x) * (max.y - min.y) * (max.z - min.z); } template <> long double Content<Math::Vec3> (const Math::Vec3& /*point*/) { return 0.0L; } } // namespace Detail } // namespace Index } // namespace Geometry
#pragma once #include <memory> #include "drake/math/rotation_matrix.h" #include "drake/multibody/multibody_tree/multibody_plant/multibody_plant.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace multibody { /** * Solves an inverse kinematics (IK) problem on a MultibodyPlant, to find the * postures of the robot satisfying certain constraints. * The decision variables include the generalized position of the robot. * TODO(hongkai.dai) The bounds on the generalized positions (i.e., joint * limits) should be imposed automatially. */ class InverseKinematics { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InverseKinematics) ~InverseKinematics() {} /** * Constructs an inverse kinematics problem for a MultibodyPlant. * @param plant The robot on which the inverse kinematics problem will be * solved. */ explicit InverseKinematics( const multibody_plant::MultibodyPlant<double>& plant); /** Adds the kinematic constraint that a point Q, fixed in frame B, should lie * within a bounding box expressed in another frame A as p_AQ_lower <= p_AQ <= * p_AQ_upper, where p_AQ is the position of point Q measured and expressed * in frame A. * @param frameB The frame in which point Q is fixed. * @param p_BQ The position of the point Q, rigidly attached to frame B, * measured and expressed in frame B. * @param frameA The frame in which the bounding box p_AQ_lower <= p_AQ <= * p_AQ_upper is expressed. * @param p_AQ_lower The lower bound on the position of point Q, measured and * expressed in frame A. * @param p_AQ_upper The upper bound on the position of point Q, measured and * expressed in frame A. */ solvers::Binding<solvers::Constraint> AddPositionConstraint( const Frame<double>& frameB, const Eigen::Ref<const Eigen::Vector3d>& p_BQ, const Frame<double>& frameA, const Eigen::Ref<const Eigen::Vector3d>& p_AQ_lower, const Eigen::Ref<const Eigen::Vector3d>& p_AQ_upper); /** * Constrains that the angle difference θ between the orientation of frame A * and the orientation of frame B to satisfy θ ≤ θ_bound. Frame A is fixed to * frame A_bar, with orientation R_AbarA measured in frame A_bar. Frame B is * fixed to frame B_bar, with orientation R_BbarB measured in frame B_bar. The * angle difference between frame A's orientation R_WA and B's orientation * R_WB is θ, (θ ∈ [0, π]), if there exists a rotation axis a, such that * rotating frame A by angle θ about axis a aligns it with frame B. Namely * R_AB = I + sinθ â + (1-cosθ)â² (1) * where R_AB is the orientation of frame B expressed in frame A. â is the * skew symmetric matrix of the rotation axis a. Equation (1) is the Rodrigues * formula that computes the rotation matrix from a rotation axis a and an * angle θ, https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula * If the users want frame A and frame B to align perfectly, they can set * θ_bound = 0. * Mathematically, this constraint is imposed as * trace(R_AB) ≥ 2cos(θ_bound) + 1 (1) * To derive (1), using Rodrigues formula * R_AB = I + sinθ â + (1-cosθ)â² * where * trace(R_AB) = 2cos(θ) + 1 ≥ 2cos(θ_bound) + 1 * @param frameAbar frame A_bar, the frame A is fixed to frame A_bar. * @param R_AbarA The orientation of frame A measured in frame A_bar. * @param frameBbar frame B_bar, the frame B is fixed to frame B_bar. * @param R_BbarB The orientation of frame B measured in frame B_bar. * @param theta_bound The bound on the angle difference between frame A's * orientation and frame B's orientation. It is denoted as θ_bound in the * documentation. @p theta_bound is in radians. */ solvers::Binding<solvers::Constraint> AddOrientationConstraint( const Frame<double>& frameAbar, const math::RotationMatrix<double>& R_AbarA, const Frame<double>& frameBbar, const math::RotationMatrix<double>& R_BbarB, double theta_bound); /** * Constrains a target point T to be within a cone K. The point T ("T" stands * for "target") is fixed in a frame B, with position p_BT. The cone * originates from a point S ("S" stands for "source"), fixed in frame A with * position p_AS, with the axis of the cone being n, also fixed * in frame A. The half angle of the cone is θ. A common usage of this * constraint is that a camera should gaze at some target; namely the target * falls within a gaze cone, originating from the camera eye. * @param frameA The frame where the gaze cone is fixed to. * @param p_AS The position of the cone source point S, measured and * expressed in frame A. * @param n_A The directional vector representing the center ray of the * cone, expressed in frame A. * @pre @p n_A cannot be a zero vector. * @throw invalid_argument is n_A is close to a zero vector. * @param frameB The frame where the target point T is fixed to. * @param p_BT The position of the target point T, measured and expressed in * frame B. * @param cone_half_angle The half angle of the cone. We denote it as θ in the * documentation. @p cone_half_angle is in radians. * @pre @p 0 <= cone_half_angle <= pi. * @throw invalid_argument if cone_half_angle is outside of the bound. */ solvers::Binding<solvers::Constraint> AddGazeTargetConstraint( const Frame<double>& frameA, const Eigen::Ref<const Eigen::Vector3d>& p_AS, const Eigen::Ref<const Eigen::Vector3d>& n_A, const Frame<double>& frameB, const Eigen::Ref<const Eigen::Vector3d>& p_BT, double cone_half_angle); /** * Constrains that the angle between a vector na and another vector nb is * between [θ_lower, θ_upper]. na is fixed to a frame A, while nb is fixed * to a frame B. * Mathematically, if we denote na_unit_A as na expressed in frame A after * normalization (na_unit_A has unit length), and nb_unit_B as nb expressed in * frame B after normalization, the constraint is * cos(θ_upper) ≤ na_unit_Aᵀ * R_AB * nb_unit_B ≤ cos(θ_lower), where R_AB is * the rotation matrix, representing the orientation of frame B expressed in * frame A. * @param frameA The frame to which na is fixed. * @param na_A The vector na fixed to frame A, expressed in frame A. * @pre na_A should be a non-zero vector. * @throw invalid_argument if na_A is close to zero. * @param frameB The frame to which nb is fixed. * @param nb_B The vector nb fixed to frame B, expressed in frame B. * @pre nb_B should be a non-zero vector. * @throw invalid_argument if nb_B is close to zero. * @param angle_lower The lower bound on the angle between na and nb. It is * denoted as θ_lower in the documentation. @p angle_lower is in radians. * @pre angle_lower >= 0. * @throw invalid_argument if angle_lower is negative. * @param angle_upper The upper bound on the angle between na and nb. it is * denoted as θ_upper in the class documentation. @p angle_upper is in * radians. * @pre angle_lower <= angle_upper <= pi. * @throw invalid_argument if angle_upper is outside the bounds. */ solvers::Binding<solvers::Constraint> AddAngleBetweenVectorsConstraint( const Frame<double>& frameA, const Eigen::Ref<const Eigen::Vector3d>& na_A, const Frame<double>& frameB, const Eigen::Ref<const Eigen::Vector3d>& nb_B, double angle_lower, double angle_upper); /** Getter for q. q is the decision variable for the generalized positions of * the robot. */ const solvers::VectorXDecisionVariable& q() const { return q_; } /** Getter for the optimization program constructed by InverseKinematics. */ const solvers::MathematicalProgram& prog() const { return *prog_; } /** Getter for the optimization program constructed by InverseKinematics. */ solvers::MathematicalProgram* get_mutable_prog() const { return prog_.get(); } private: MultibodyTreeContext<AutoDiffXd>* get_mutable_context() { return dynamic_cast<MultibodyTreeContext<AutoDiffXd>*>(context_.get()); } std::unique_ptr<solvers::MathematicalProgram> prog_; const multibody_plant::MultibodyPlant<double>& plant_; const MultibodyTreeSystem<AutoDiffXd> system_; std::unique_ptr<systems::Context<AutoDiffXd>> const context_; solvers::VectorXDecisionVariable q_; }; } // namespace multibody } // namespace drake
// // CircleCropSprite.cpp // SMFrameWork // // Created by KimSteve on 2016. 12. 5.. // // #include "CircleCropSprite.h" #include "../Base/ShaderNode.h" static const GLfloat _texCoordStripConst[8] = { 0, 1, 1, 1, 0, 0, 1, 0 }; CircleCropSprite* CircleCropSprite::createWithTexture(cocos2d::Texture2D *texture, bool crop) { auto cropSprite = new (std::nothrow)CircleCropSprite(); if (cropSprite && cropSprite->initWithCropTexture(texture, crop)) { cropSprite->autorelease(); } else { CC_SAFE_DELETE(cropSprite); } return cropSprite; } CircleCropSprite::CircleCropSprite() : _aaWidth(ShapeNode::DEFAULT_ANTI_ALIAS_WIDTH) { } CircleCropSprite::~CircleCropSprite() { } bool CircleCropSprite::initWithCropTexture(cocos2d::Texture2D *texture, bool crop) { if (!cocos2d::Sprite::initWithTexture(texture)) { return false; } #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID const std::string shaderName = "mobileShader/SpriteCropCircle.fsh"; #else const std::string shaderName = "shader/SpriteCropCircle.fsh"; #endif auto program = cocos2d::GLProgramCache::getInstance()->getGLProgram(shaderName); if (program==nullptr) { auto fileUtils = cocos2d::FileUtils::getInstance(); #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID auto vertexFilePath = fileUtils->fullPathForFilename("mobileShader/PositionTexture_uColor.vsh"); #else auto vertexFilePath = fileUtils->fullPathForFilename("shader/PositionTexture_uColor.vsh"); #endif auto vertexSource = fileUtils->getStringFromFile(vertexFilePath); auto fragmentShaderName = fileUtils->fullPathForFilename(shaderName); auto fragmentSource =fileUtils->getStringFromFile(fragmentShaderName); program = cocos2d::GLProgram::createWithByteArrays(vertexSource.c_str(), fragmentSource.c_str()); cocos2d::GLProgramCache::getInstance()->addGLProgram(program, shaderName); program->bindAttribLocation(cocos2d::GLProgram::ATTRIBUTE_NAME_POSITION, cocos2d::GLProgram::VERTEX_ATTRIB_POSITION); program->bindAttribLocation(cocos2d::GLProgram::ATTRIBUTE_NAME_TEX_COORD, cocos2d::GLProgram::VERTEX_ATTRIB_TEX_COORD); program->link(); program->updateUniforms(); } auto state = cocos2d::GLProgramState::getOrCreateWithGLProgram(program); setGLProgramState(state); getGLProgram()->use(); _uniformDimension = program->getUniformLocation("u_dimension"); _uniformAAWidth = program->getUniformLocation("u_aaWidth"); _uniformRadius = program->getUniformLocation("u_radius"); _uniformColor = program->getUniformLocation("u_color"); _uniformTexture = program->getUniformLocation("u_texture"); // 실제 pixel단위 사이즈 _size = texture->getContentSizeInPixels(); if (crop) { _radius = 0.5*std::min(_size.x, _size.y); } else { _radius = 0.5*std::max(_size.x, _size.y); } return true; } void CircleCropSprite::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) { if (_displayedOpacity==0) { // opacity가 0이면 그릴 필요 없음. return; } // on draw 호출 _customCommand.init(_globalZOrder, transform, flags); _customCommand.func = CC_CALLBACK_0(CircleCropSprite::onDraw, this, transform, flags); renderer->addCommand(&_customCommand); } void CircleCropSprite::onDraw(const cocos2d::Mat4 &transform, uint32_t flags) { const float alpha = _displayedOpacity/255.0f; const cocos2d::Vec4 color = cocos2d::Vec4( alpha * _displayedColor.r/255.0f, alpha * _displayedColor.g/255.0f, alpha * _displayedColor.b/255.0f, alpha); const float width = _size.x; const float height = _size.y; GLfloat vertices[8] = {0, 0, width, 0, 0, height, width, height}; auto state = getGLProgramState(); state->setUniformVec2(_uniformDimension, _size); state->setUniformVec4(_uniformColor, color); state->setUniformFloat(_uniformRadius, _radius); state->setUniformFloat(_uniformAAWidth, _aaWidth); state->setUniformTexture(_uniformTexture, _texture); state->setVertexAttribPointer("a_position", 2, GL_FLOAT, GL_FALSE, 0, vertices); state->setVertexAttribPointer("a_texCoord", 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)_texCoordStripConst); state->apply(transform); cocos2d::GL::blendFunc(_blendFunc.src, _blendFunc.dst); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, 4); } void CircleCropSprite::setAntiAliasWidth(float aaWidth) { _aaWidth = aaWidth; } void CircleCropSprite::setRadius(float radius) { _radius = radius; }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Class: // MultiArg1<A1> // MultiArg2<A1,A2> // etc. // Functions: // applyMultiArg //----------------------------------------------------------------------------- #ifndef POOMA_FUNCTIONS_MULTIARG_H #define POOMA_FUNCTIONS_MULTIARG_H ////////////////////////////////////////////////////////////////////// /** @file * @ingroup Utilities * @brief * The MultiArg1...N classes are intended to be used to wrap multiple arrays, * fields, or particles where a common set of operations need to be performed * on the set. * * Typical operations would be: taking views, getting locks, * performing intersections. * * It would be nicer in some sense to have an inhomogenous container with * common interfaces through a base class. That approach would avoid the * following huge number of MultiArg classes. * The difficulty arises in extracting * the arrays at the end and handing them off to a function. To extract the * arrays requires knowing their types, requiring you to know the complete * signature of the function you are calling. At that point, you've already * accumulated all the type information in something at least as complicated * as the MultiArg<> classes here. */ //----------------------------------------------------------------------------- // Typedefs: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes: //----------------------------------------------------------------------------- #include "Pooma/View.h" //----------------------------------------------------------------------------- // Forward Declarations: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // Full Description: // //----------------------------------------------------------------------------- template<class A1> struct MultiArg1; template<class A1, class A2> struct MultiArg2; template<class A1, class A2, class A3> struct MultiArg3; template<class A1, class A2, class A3, class A4> struct MultiArg4; template<class A1, class A2, class A3, class A4, class A5> struct MultiArg5; template<class A1, class A2, class A3, class A4, class A5, class A6> struct MultiArg6; template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> struct MultiArg7; // These MultiArgView structs are workarounds for Compaq's // c++ compiler. It had some odd problems with the definition // of View1<MA<A>> in terms of View1<A>. template<class A1, class Dom> struct MultiArgView1 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef MultiArg1<A1_t> Type_t; }; template<class A1, class A2, class Dom> struct MultiArgView2 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef MultiArg2<A1_t, A2_t> Type_t; }; template<class A1, class A2, class A3, class Dom> struct MultiArgView3 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef typename View1<A3, Dom>::Type_t A3_t; typedef MultiArg3<A1_t, A2_t, A3_t> Type_t; }; template<class A1, class A2, class A3, class A4, class Dom> struct MultiArgView4 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef typename View1<A3, Dom>::Type_t A3_t; typedef typename View1<A4, Dom>::Type_t A4_t; typedef MultiArg4<A1_t, A2_t, A3_t, A4_t> Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class Dom> struct MultiArgView5 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef typename View1<A3, Dom>::Type_t A3_t; typedef typename View1<A4, Dom>::Type_t A4_t; typedef typename View1<A5, Dom>::Type_t A5_t; typedef MultiArg5<A1_t, A2_t, A3_t, A4_t, A5_t> Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class A6, class Dom> struct MultiArgView6 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef typename View1<A3, Dom>::Type_t A3_t; typedef typename View1<A4, Dom>::Type_t A4_t; typedef typename View1<A5, Dom>::Type_t A5_t; typedef typename View1<A6, Dom>::Type_t A6_t; typedef MultiArg6<A1_t, A2_t, A3_t, A4_t, A5_t, A6_t> Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class Dom> struct MultiArgView7 { typedef typename View1<A1, Dom>::Type_t A1_t; typedef typename View1<A2, Dom>::Type_t A2_t; typedef typename View1<A3, Dom>::Type_t A3_t; typedef typename View1<A4, Dom>::Type_t A4_t; typedef typename View1<A5, Dom>::Type_t A5_t; typedef typename View1<A6, Dom>::Type_t A6_t; typedef typename View1<A7, Dom>::Type_t A7_t; typedef MultiArg7<A1_t, A2_t, A3_t, A4_t, A5_t, A6_t, A7_t> Type_t; }; template<class A1, class Dom> struct View1<MultiArg1<A1>, Dom> { typedef typename MultiArgView1<A1, Dom>::Type_t Type_t; }; template<class A1, class A2, class Dom> struct View1<MultiArg2<A1, A2>, Dom> { typedef typename MultiArgView2<A1, A2, Dom>::Type_t Type_t; }; template<class A1, class A2, class A3, class Dom> struct View1<MultiArg3<A1, A2, A3>, Dom> { typedef typename MultiArgView3<A1, A2, A3, Dom>::Type_t Type_t; }; template<class A1, class A2, class A3, class A4, class Dom> struct View1<MultiArg4<A1, A2, A3, A4>, Dom> { typedef typename MultiArgView4<A1, A2, A3, A4, Dom>::Type_t Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class Dom> struct View1<MultiArg5<A1, A2, A3, A4, A5>, Dom> { typedef typename MultiArgView5<A1, A2, A3, A4, A5, Dom>::Type_t Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class A6, class Dom> struct View1<MultiArg6<A1, A2, A3, A4, A5, A6>, Dom> { typedef typename MultiArgView6<A1, A2, A3, A4, A5, A6, Dom>::Type_t Type_t; }; template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class Dom> struct View1<MultiArg7<A1, A2, A3, A4, A5, A6, A7>, Dom> { typedef typename MultiArgView7<A1, A2, A3, A4, A5, A6, A7, Dom>::Type_t Type_t; }; template<class A1> struct MultiArg1 { enum { size = 1 }; MultiArg1(const A1 &a1) : a1_m(a1) { } template<class Dom> typename View1<MultiArg1<A1>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg1<A1>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom)); } A1 a1_m; }; template<class A1, class A2> struct MultiArg2 { enum { size = 2 }; MultiArg2(const A1 &a1, const A2 &a2) : a1_m(a1), a2_m(a2) { } template<class Dom> typename View1<MultiArg2<A1, A2>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg2<A1, A2>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom)); } A1 a1_m; A2 a2_m; }; template<class A1, class A2, class A3> struct MultiArg3 { enum { size = 3 }; MultiArg3(const A1 &a1, const A2 &a2, const A3 &a3) : a1_m(a1), a2_m(a2), a3_m(a3) { } template<class Dom> typename View1<MultiArg3<A1, A2, A3>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg3<A1, A2, A3>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom), a3_m(dom)); } A1 a1_m; A2 a2_m; A3 a3_m; }; template<class A1, class A2, class A3, class A4> struct MultiArg4 { enum { size = 4 }; MultiArg4(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4) : a1_m(a1), a2_m(a2), a3_m(a3), a4_m(a4) { } template<class Dom> typename View1<MultiArg4<A1, A2, A3, A4>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg4<A1, A2, A3, A4>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom), a3_m(dom), a4_m(dom)); } A1 a1_m; A2 a2_m; A3 a3_m; A4 a4_m; }; template<class A1, class A2, class A3, class A4, class A5> struct MultiArg5 { enum { size = 5 }; MultiArg5(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5) : a1_m(a1), a2_m(a2), a3_m(a3), a4_m(a4), a5_m(a5) { } template<class Dom> typename View1<MultiArg5<A1, A2, A3, A4, A5>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg5<A1, A2, A3, A4, A5>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom), a3_m(dom), a4_m(dom), a5_m(dom)); } A1 a1_m; A2 a2_m; A3 a3_m; A4 a4_m; A5 a5_m; }; template<class A1, class A2, class A3, class A4, class A5, class A6> struct MultiArg6 { enum { size = 6 }; MultiArg6(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6) : a1_m(a1), a2_m(a2), a3_m(a3), a4_m(a4), a5_m(a5), a6_m(a6) { } template<class Dom> typename View1<MultiArg6<A1, A2, A3, A4, A5, A6>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg6<A1, A2, A3, A4, A5, A6>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom), a3_m(dom), a4_m(dom), a5_m(dom), a6_m(dom)); } A1 a1_m; A2 a2_m; A3 a3_m; A4 a4_m; A5 a5_m; A6 a6_m; }; template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> struct MultiArg7 { enum { size = 7 }; MultiArg7(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6, const A7 &a7) : a1_m(a1), a2_m(a2), a3_m(a3), a4_m(a4), a5_m(a5), a6_m(a6), a7_m(a7) { } template<class Dom> typename View1<MultiArg7<A1, A2, A3, A4, A5, A6, A7>, Dom>::Type_t operator()(const Dom &dom) const { typedef typename View1<MultiArg7<A1, A2, A3, A4, A5, A6, A7>, Dom>::Type_t Ret_t; return Ret_t(a1_m(dom), a2_m(dom), a3_m(dom), a4_m(dom), a5_m(dom), a6_m(dom), a7_m(dom)); } A1 a1_m; A2 a2_m; A3 a3_m; A4 a4_m; A5 a5_m; A6 a6_m; A7 a7_m; }; template<class A1, class Function> void applyMultiArg(const MultiArg1<A1> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); } template<class A1, class A2, class Function> void applyMultiArg(const MultiArg2<A1, A2> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); } template<class A1, class A2, class A3, class Function> void applyMultiArg(const MultiArg3<A1, A2, A3> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); f(node.a3_m, condition[2]); } template<class A1, class A2, class A3, class A4, class Function> void applyMultiArg(const MultiArg4<A1, A2, A3, A4> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); f(node.a3_m, condition[2]); f(node.a4_m, condition[3]); } template<class A1, class A2, class A3, class A4, class A5, class Function> void applyMultiArg(const MultiArg5<A1, A2, A3, A4, A5> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); f(node.a3_m, condition[2]); f(node.a4_m, condition[3]); f(node.a5_m, condition[4]); } template<class A1, class A2, class A3, class A4, class A5, class A6, class Function> void applyMultiArg(const MultiArg6<A1, A2, A3, A4, A5, A6> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); f(node.a3_m, condition[2]); f(node.a4_m, condition[3]); f(node.a5_m, condition[4]); f(node.a6_m, condition[5]); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class Function> void applyMultiArg(const MultiArg7<A1, A2, A3, A4, A5, A6, A7> &node, const Function &f, const std::vector<bool> &condition) { f(node.a1_m, condition[0]); f(node.a2_m, condition[1]); f(node.a3_m, condition[2]); f(node.a4_m, condition[3]); f(node.a5_m, condition[4]); f(node.a6_m, condition[5]); f(node.a7_m, condition[6]); } template<class A1, class Function> void applyMultiArg(const MultiArg1<A1> &node, const Function &f) { f(node.a1_m); } template<class A1, class A2, class Function> void applyMultiArg(const MultiArg2<A1, A2> &node, const Function &f) { f(node.a1_m); f(node.a2_m); } template<class A1, class A2, class A3, class Function> void applyMultiArg(const MultiArg3<A1, A2, A3> &node, const Function &f) { f(node.a1_m); f(node.a2_m); f(node.a3_m); } template<class A1, class A2, class A3, class A4, class Function> void applyMultiArg(const MultiArg4<A1, A2, A3, A4> &node, const Function &f) { f(node.a1_m); f(node.a2_m); f(node.a3_m); f(node.a4_m); } template<class A1, class A2, class A3, class A4, class A5, class Function> void applyMultiArg(const MultiArg5<A1, A2, A3, A4, A5> &node, const Function &f) { f(node.a1_m); f(node.a2_m); f(node.a3_m); f(node.a4_m); f(node.a5_m); } template<class A1, class A2, class A3, class A4, class A5, class A6, class Function> void applyMultiArg(const MultiArg6<A1, A2, A3, A4, A5, A6> &node, const Function &f) { f(node.a1_m); f(node.a2_m); f(node.a3_m); f(node.a4_m); f(node.a5_m); f(node.a6_m); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class Function> void applyMultiArg(const MultiArg7<A1, A2, A3, A4, A5, A6, A7> &node, const Function &f) { f(node.a1_m); f(node.a2_m); f(node.a3_m); f(node.a4_m); f(node.a5_m); f(node.a6_m); f(node.a7_m); } template<class A1, class Function> void applyMultiArgIf(const MultiArg1<A1> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); } template<class A1, class A2, class Function> void applyMultiArgIf(const MultiArg2<A1, A2> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); } template<class A1, class A2, class A3, class Function> void applyMultiArgIf(const MultiArg3<A1, A2, A3> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); if (condition[2]) f(node.a3_m); } template<class A1, class A2, class A3, class A4, class Function> void applyMultiArgIf(const MultiArg4<A1, A2, A3, A4> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); if (condition[2]) f(node.a3_m); if (condition[3]) f(node.a4_m); } template<class A1, class A2, class A3, class A4, class A5, class Function> void applyMultiArgIf(const MultiArg5<A1, A2, A3, A4, A5> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); if (condition[2]) f(node.a3_m); if (condition[3]) f(node.a4_m); if (condition[4]) f(node.a5_m); } template<class A1, class A2, class A3, class A4, class A5, class A6, class Function> void applyMultiArgIf(const MultiArg6<A1, A2, A3, A4, A5, A6> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); if (condition[2]) f(node.a3_m); if (condition[3]) f(node.a4_m); if (condition[4]) f(node.a5_m); if (condition[5]) f(node.a6_m); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class Function> void applyMultiArgIf(const MultiArg7<A1, A2, A3, A4, A5, A6, A7> &node, const Function &f, const std::vector<bool> &condition) { if (condition[0]) f(node.a1_m); if (condition[1]) f(node.a2_m); if (condition[2]) f(node.a3_m); if (condition[3]) f(node.a4_m); if (condition[4]) f(node.a5_m); if (condition[5]) f(node.a6_m); if (condition[6]) f(node.a7_m); } #endif // POOMA_FUNCTIONS_MULTIARG_H // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: MultiArg.h,v $ $Author: richard $ // $Revision: 1.10 $ $Date: 2004/11/01 18:16:49 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
/* XBFOG.CPP FOG CLASS (c) g0at3r */ #include "XbFog.h" CXBFog::CXBFog() { m_dwVertexDecl[0] = D3DVSD_STREAM( 0 ); m_dwVertexDecl[1] = D3DVSD_REG( 0, D3DVSDT_FLOAT3 ); m_dwVertexDecl[2] = D3DVSD_REG( 2, D3DVSDT_FLOAT3 ); m_dwVertexDecl[3] = D3DVSD_REG( 5, D3DVSDT_FLOAT2 ); m_dwVertexDecl[4] = D3DVSD_END(); m_dwVertexShader = NULL; m_dwFogMode = D3DFOG_EXP; m_dwFogColor = D3DCOLOR_XRGB(0,0,130); m_fFogStartValue = 50.0f; m_fFogEndValue = 70.0f; m_fFogDensity = 0.03f; m_bUseFog = true; } CXBFog::~CXBFog() { } void CXBFog::Enable() { m_bUseFog = true; } void CXBFog::Disable() { m_bUseFog = false; } void CXBFog::ChangeFog(DWORD dwFogMode, FLOAT fFogStart, FLOAT fFogEnd, FLOAT fFogDensity, DWORD dwFogColor) { m_dwFogMode = dwFogMode; m_dwFogColor = dwFogColor; m_fFogStartValue = fFogStart; m_fFogEndValue = fFogEnd; m_fFogDensity = fFogDensity; } void CXBFog::SetVertexShader(char* szVertexShader) { XBUtil_CreateVertexShader(szVertexShader, m_dwVertexDecl, &m_dwVertexShader); // VXU } void CXBFog::Render() { if( m_bUseFog && (m_dwFogMode != D3DFOG_NONE) ) { SetupVertexShader(); D3DDevice::SetTexture( 0, NULL ); D3DDevice::SetRenderState( D3DRS_LIGHTING, TRUE ); D3DDevice::SetRenderState( D3DRS_ZENABLE, TRUE ); D3DDevice::SetRenderState( D3DRS_DITHERENABLE, TRUE ); D3DDevice::SetRenderState( D3DRS_SPECULARENABLE, FALSE ); D3DDevice::SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); D3DDevice::SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ); D3DDevice::SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); D3DDevice::SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); D3DDevice::SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); D3DDevice::SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); D3DDevice::SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); D3DDevice::SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); D3DDevice::SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR ); D3DDevice::SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR ); D3DDevice::SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_NONE ); D3DDevice::SetTextureStageState( 0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP ); D3DDevice::SetTextureStageState( 0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP ); } else { D3DDevice::SetRenderState( D3DRS_FOGENABLE, FALSE ); } } void CXBFog::SetupVertexShader() { D3DDevice::SetVertexShader( m_dwVertexShader ); D3DXMATRIX matW, matWV, matWVP; D3DXMatrixMultiply( &matWV, &m_matWorld, &m_matView ); D3DXMatrixMultiply( &matWVP, &matWV, &m_matProj ); D3DXMatrixTranspose( &matW, &m_matWorld ); D3DXMatrixTranspose( &matWV, &matWV ); D3DXMatrixTranspose( &matWVP, &matWVP ); D3DDevice::SetVertexShaderConstant( 10, &matW, 4 ); D3DDevice::SetVertexShaderConstant( 20, &matWV, 4 ); D3DDevice::SetVertexShaderConstant( 30, &matWVP, 4 ); D3DXVECTOR4 vZeroes( 0.0f, 0.0f, 0.0f, 0.0f ); D3DXVECTOR4 vLight( 0.0f, 50.0f, 0.0f, 0.0f ); D3DXVECTOR4 vDiffuse( 1.0f, 1.0f, 1.0f, 1.0f ); D3DXVECTOR4 vAmbient( 0x44/255.0f, 0x44/255.0f, 0x44/255.0f, 1.0f ); D3DXMATRIX matInvWorld; D3DXMatrixInverse( &matInvWorld, NULL, &m_matWorld ); D3DXVec3TransformCoord( (D3DXVECTOR3*)&vLight, (D3DXVECTOR3*)&vLight, &matInvWorld ); D3DDevice::SetVertexShaderConstant( 0, &vZeroes, 1 ); D3DDevice::SetVertexShaderConstant( 40, &vLight, 1 ); D3DDevice::SetVertexShaderConstant( 41, &vDiffuse, 1 ); D3DDevice::SetVertexShaderConstant( 42, &vAmbient, 1 ); D3DXVECTOR4 vFog( 1.0f, 0.0f, 0.0f, 0.0f ); D3DDevice::SetVertexShaderConstant( 44, &vFog, 1 ); D3DDevice::SetRenderState( D3DRS_FOGENABLE, TRUE ); D3DDevice::SetRenderState( D3DRS_FOGCOLOR, m_dwFogColor ); D3DDevice::SetRenderState( D3DRS_FOGTABLEMODE, m_dwFogMode ); D3DDevice::SetRenderState( D3DRS_FOGSTART, FtoDW(m_fFogStartValue) ); D3DDevice::SetRenderState( D3DRS_FOGEND, FtoDW(m_fFogEndValue) ); D3DDevice::SetRenderState( D3DRS_FOGDENSITY, FtoDW(m_fFogDensity) ); }
#include "resultados.h" #include "ui_resultados.h" Resultados::Resultados(QWidget *parent) : QDialog(parent), ui(new Ui::Resultados) { ui->setupUi(this); //Cargar los votos del archivo this->cargarVotos(); //Crear el lienzo lienzo = QPixmap(660,500); //Invocar al metodo dibujar this->dibujar(); } Resultados::~Resultados() { delete ui; } void Resultados::dibujar() { //Rellenar el lienzo de color blanco lienzo.fill(Qt::white); //Crear el pintor QPainter picasso(&lienzo); int x = 50; int y = 50; int ancho = 100; m_total = m_arauz+m_lasso+m_blanco+m_nulo; //PORCENTAJE porArauz=(m_arauz*100)/m_total; porLasso=(m_lasso*100)/m_total; porNulo=(m_nulo*100)/m_total; porBlanco=(m_blanco*100)/m_total; //Obtener el alto a partir del procentaje float alto_1 = porArauz*380/100; float alto_2 = porLasso*380/100; float alto_3 = porNulo*380/100; float alto_4 = porBlanco*380/100; //Crear el pincel para el borde QPen pincel; pincel.setWidth(5); pincel.setColor(Qt::red); QColor colorRelleno1(255, 120, 108); pincel.setJoinStyle(Qt::MiterJoin); //Establecer el pincel al pintor picasso.setPen(pincel); //Dibujar la primera barra picasso.drawRect(x, y+(400-alto_1), ancho, alto_1); picasso.setFont(QFont("Arial", 10)); picasso.setPen(Qt::black); picasso.drawText(x, (400 - alto_1) + 17, "Arauz"); picasso.drawText(x, (400 - alto_1), tr("Lista 1")); picasso.drawText(x, (400 - alto_1)+34,QString::number(porArauz,'f',2)+" %"); //Crear un nuevo color QColor colorBorde2(78,3,48); QColor colorRelleno2(190,120,162); //Establecer el nuevo color al pincel pincel.setColor(colorBorde2); //Volver a establecer el pincel al objeto painter picasso.setPen(pincel); //Establecer el color de la brocha del objeto painter picasso.setBrush(colorRelleno2); //Dibujar la segunda barra picasso.drawRect(x+150, y+(400-alto_2), ancho, alto_2); picasso.setPen(Qt::black); picasso.drawText(x + 150, (400 - alto_2), tr("Lista 21")); picasso.drawText(x + 150, (400 - alto_2) + 17, "Lasso"); picasso.drawText(x + 150, (400 - alto_2) + 34,QString::number(porLasso,'f',2)+" %"); //Creando los colores de la tercera barra QColor colorRelleno3(253,253,115); QColor colorBorde3(174,174,51); //Establecer nuevo color al pincel pincel.setColor(colorBorde3); //Establecer el pincel y la brocha al painter picasso.setPen(pincel); picasso.setBrush(colorRelleno3); //Dibujar la tercera barra picasso.drawRect(x+300, y+(400-alto_3), ancho, alto_3); picasso.setPen(Qt::black); picasso.drawText(x + 300, (400-alto_3) + 17, tr("Nulo")); picasso.drawText(x + 300, (400-alto_3) + 34,QString::number(porNulo,'f',2)+" %"); //Dibujar cuarta barra QColor colorRelleno4(110,250,125); QColor colorBorde4(100,100,100); pincel.setColor(colorBorde4); picasso.setPen(pincel); picasso.setBrush(colorRelleno4); picasso.drawRect(x+450, y+(400-alto_4), ancho, alto_4); picasso.setPen(Qt::black); picasso.drawText(x+450, (400-alto_4) + 17, tr("Blanco")); picasso.drawText(x+450, (400-alto_4) + 34,QString::number(porBlanco,'f',2)+" %"); //Mostrar el lienzo en el cuadro ui->outResultados->setPixmap(lienzo); } void Resultados::cargarVotos() { QFile votos("Votos.csv"); QTextStream io; io.setDevice(&votos); votos.open(QIODevice::ReadOnly); io.setDevice(&votos); while(!io.atEnd()) { auto linea = io.readLine(); auto valores =linea.split(";"); int numeroColumnas = valores.size(); for(int i = 0; i< numeroColumnas; i++) { if(valores.at(0) == "Arauz") { m_arauz = (valores.at(1).toInt());//retorna los votos como enteros } else if(valores.at(0) == "Lasso") { m_lasso = (valores.at(1).toInt());//retorna los votos como enteros } else if(valores.at(0) == tr("Nulo")) { m_nulo = (valores.at(1).toInt());//retorna los votos como enteros } else m_blanco = (valores.at(1).toInt());//retorna los votos como enteros } } } void Resultados::on_cmdImagen_released() { QString nombreArchivo = QFileDialog::getSaveFileName(this, tr("Guardar imagen"), QString(), "Imagenes (*.png)"); if (!nombreArchivo.isEmpty()){ if (lienzo.save(nombreArchivo)) QMessageBox::information(this, tr("Guardar imagen"), tr("Archivo almacenado en: ") + nombreArchivo); else QMessageBox::warning(this, tr("Guardar imagen"), tr("No se pudo almacenar la imagen.")); } } void Resultados::on_cmdExcel_released() { //Crear un objeto QDir a partir del directorio del usuario QDir directorio = QDir::home(); //Agregar al path absoluto del objeto un nombre por defecto del archivo QString pathArchivo = directorio.absolutePath() + "/Resultados.csv"; //Abrir un cuadro de dialogo para seleccionar el nombre y ubicacion del archivo a guardar QString fileName = QFileDialog::getSaveFileName(this, "Guardar archivo", pathArchivo, "CSV (delimitado por comas) (*.csv)"); //Crear el archivo a partir del nombre arrojado por el cuadro de dialogo QFile f(fileName); //Crear el objeto QTextstream (permite escribir sobre el archivo) QTextStream out(&f); //Intentar abrir el archivo ya sea para escribir(si no existe) o para agregar texto(si existe) if(!f.open(QIODevice::WriteOnly | QIODevice::Append)) { QMessageBox::warning(this, "Resumen", "No se puede abrir el archivo"); return; } //Guardar el contenido out << ";CNE" << endl << "Resultados" << endl; out << "Arauz;" << "Lasso;" << "Nulo;" << "Blanco" << endl; out << QString::number(m_arauz) << ";" << QString::number(m_lasso) << ";" << QString::number(m_nulo) << ";" << QString::number(m_blanco) << endl; out << QString("%" "%1;").arg(porArauz) << QString("%" "%1;").arg(porLasso) << QString("%" "%1;").arg(porNulo) << QString("%" "%1").arg(porBlanco) << endl; out << endl << "Votos Totales" << endl << QString::number(m_total); f.close(); }
//#include <iostream> //#include "typet.h" #include "stubgen.h" using namespace std; //#include "hfss.h" //#include "hfssstubc_t.h" //extern int subi; bool stubs = 1; //extern int tabs = 0; int main (int argc, char *argv[]) { printf( "Vardist stubgen! \n"); if (argc<4) { printf("Usage: classname in_header_file out_skelfile\n"); // printf(" -json classname in_header_file out_file\n"); return 0; } stubgen_t *s = new stubgen_t; s->gen(argv[1], argv[2], argv[3]); // s->gen("hfs_t", "hfss.h", "skelhfs.h"); delete s; /* if (!strcmp(argv[1], "-json")) { printf("JSON generating\n"); stubgen_t *s = new stubgen_t; stubs = 0; s->gen_json(argv[2], argv[3], argv[4]); delete s; } else { printf("Stub and Skel generating\n"); stubgen_t *s = new stubgen_t; stubs = 1; s->gen(argv[1], argv[2], argv[3]); s->list_all_types(); //s->list_type("vector<char*>"); delete s; s = new stubgen_t; stubs = 0; //s->list_type("read_ret_t*"); s->gen(argv[1], argv[2], argv[4]); delete s; } */ return 0; }
/* * wayPoint.h * * Created on: Jun 20, 2015 * Author: colman */ #ifndef WAYPOINT_H_ #define WAYPOINT_H_ #include "Globals.h" #include "Position.h" class wayPoint{ public: PositionState* _state; Position* _position; wayPoint(); virtual ~wayPoint(); }; #endif /* WAYPOINT_H_ */
/** * @file single_board.cpp * @author Hamdi Sahloul * @date September 2014 * @version 0.1 * @brief ROS version of the example named "simple_board" in the Aruco software package. */ #include <iostream> #include <fstream> #include <sstream> #include <aruco/aruco.h> #include <aruco/boarddetector.h> #include <aruco/cvdrawingutils.h> #include <opencv2/core/core.hpp> #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <ar_sys/utils.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <std_msgs/String.h> using namespace aruco; class ArSysSingleBoard { private: cv::Mat inImage, resultImg; aruco::CameraParameters camParam; bool useRectifiedImages; bool draw_markers; bool draw_markers_cube; bool draw_markers_axis; bool publish_tf; MarkerDetector mDetector; vector<Marker> markers; BoardConfiguration the_board_config; BoardDetector the_board_detector; Board the_board_detected; ros::Subscriber cam_info_sub; ros::Subscriber switch_board_sub; bool cam_info_received; image_transport::Publisher image_pub; image_transport::Publisher debug_pub; ros::Publisher pose_pub; ros::Publisher transform_pub; ros::Publisher position_pub; std::string board_frame; double marker_size; double marker_size_outer; double marker_size_inner; std::string board_config; std::string board_config_outer; std::string board_config_inner; ros::NodeHandle nh; image_transport::ImageTransport it; image_transport::Subscriber image_sub; tf::TransformListener _tfListener; public: ArSysSingleBoard() : cam_info_received(false), nh("~"), it(nh) { image_sub = it.subscribe("/image", 1, &ArSysSingleBoard::image_callback, this); cam_info_sub = nh.subscribe("/camera_info", 1, &ArSysSingleBoard::cam_info_callback, this); switch_board_sub = nh.subscribe("/switch_board", 1, &ArSysSingleBoard::switch_board_callback, this); image_pub = it.advertise("result", 1); debug_pub = it.advertise("debug", 1); pose_pub = nh.advertise<geometry_msgs::PoseStamped>("pose", 100); transform_pub = nh.advertise<geometry_msgs::TransformStamped>("transform", 100); position_pub = nh.advertise<geometry_msgs::Vector3Stamped>("position", 100); nh.param<double>("marker_size_outer", marker_size_outer, 0.05); nh.param<double>("marker_size_inner", marker_size_inner, 0.05); nh.param<double>("marker_size", marker_size, marker_size_outer); // start with outer board nh.param<std::string>("board_config_outer", board_config_outer, "boardConfiguration.yml"); nh.param<std::string>("board_config_inner", board_config_inner, "boardConfiguration.yml"); nh.param<std::string>("board_config", board_config, board_config_outer); // start with outer board nh.param<std::string>("board_frame", board_frame, ""); nh.param<bool>("image_is_rectified", useRectifiedImages, true); nh.param<bool>("draw_markers", draw_markers, false); nh.param<bool>("draw_markers_cube", draw_markers_cube, false); nh.param<bool>("draw_markers_axis", draw_markers_axis, false); nh.param<bool>("publish_tf", publish_tf, false); the_board_config.readFromFile(board_config.c_str()); ROS_INFO("ArSys node started with marker size of %f m and board configuration: %s", marker_size, board_config.c_str()); } void image_callback(const sensor_msgs::ImageConstPtr& msg) { static tf::TransformBroadcaster br; if(!cam_info_received) return; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); inImage = cv_ptr->image; resultImg = cv_ptr->image.clone(); //detection results will go into "markers" markers.clear(); //Ok, let's detect mDetector.detect(inImage, markers, camParam, marker_size, false); //Detection of the board float probDetect=the_board_detector.detect(markers, the_board_config, the_board_detected, camParam, marker_size); if (probDetect > 0.0) { tf::Transform transform = ar_sys::getTf(the_board_detected.Rvec, the_board_detected.Tvec); tf::StampedTransform stampedTransform(transform, msg->header.stamp, msg->header.frame_id, board_frame); if (publish_tf) br.sendTransform(stampedTransform); geometry_msgs::PoseStamped poseMsg; tf::poseTFToMsg(transform, poseMsg.pose); poseMsg.header.frame_id = msg->header.frame_id; poseMsg.header.stamp = msg->header.stamp; pose_pub.publish(poseMsg); geometry_msgs::TransformStamped transformMsg; tf::transformStampedTFToMsg(stampedTransform, transformMsg); transform_pub.publish(transformMsg); geometry_msgs::Vector3Stamped positionMsg; positionMsg.header = transformMsg.header; positionMsg.vector = transformMsg.transform.translation; position_pub.publish(positionMsg); } //for each marker, draw info and its boundaries in the image for(size_t i=0; draw_markers && i < markers.size(); ++i) { markers[i].draw(resultImg,cv::Scalar(0,0,255),2); } if(camParam.isValid() && marker_size != -1) { //draw a 3d cube in each marker if there is 3d info for(size_t i=0; i<markers.size(); ++i) { if (draw_markers_cube) CvDrawingUtils::draw3dCube(resultImg, markers[i], camParam); if (draw_markers_axis) CvDrawingUtils::draw3dAxis(resultImg, markers[i], camParam); } //draw board axis if (probDetect > 0.0) CvDrawingUtils::draw3dAxis(resultImg, the_board_detected, camParam); } if(image_pub.getNumSubscribers() > 0) { //show input with augmented information cv_bridge::CvImage out_msg; out_msg.header.frame_id = msg->header.frame_id; out_msg.header.stamp = msg->header.stamp; out_msg.encoding = sensor_msgs::image_encodings::RGB8; out_msg.image = resultImg; image_pub.publish(out_msg.toImageMsg()); } if(debug_pub.getNumSubscribers() > 0) { //show also the internal image resulting from the threshold operation cv_bridge::CvImage debug_msg; debug_msg.header.frame_id = msg->header.frame_id; debug_msg.header.stamp = msg->header.stamp; debug_msg.encoding = sensor_msgs::image_encodings::MONO8; debug_msg.image = mDetector.getThresholdedImage(); debug_pub.publish(debug_msg.toImageMsg()); } } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } } // wait for one camerainfo, then shut down that subscriber void cam_info_callback(const sensor_msgs::CameraInfo &msg) { camParam = ar_sys::getCamParams(msg, useRectifiedImages); cam_info_received = true; cam_info_sub.shutdown(); } void switch_board_callback(const std_msgs::StringConstPtr &msg) { if (msg->data == "outer") { ROS_INFO("ar_single_board: Request board switch to outer"); board_config = board_config_outer; marker_size = marker_size_outer; } else if (msg->data == "inner") { ROS_INFO("ar_single_board: Request board switch to inner"); board_config = board_config_inner; marker_size = marker_size_inner; } // Update board the_board_config.readFromFile(board_config.c_str()); ROS_INFO("ArSys node updated with marker size of %f m and board configuration: %s", marker_size, board_config.c_str()); } }; int main(int argc,char **argv) { ros::init(argc, argv, "ar_single_board"); ArSysSingleBoard node; ros::spin(); }
#include "cached_bit_writer.h" #include "utils.h" using namespace std; const size_t CachedBitWriter::MAX_CACHED_BYTES = 10; CachedBitWriter::CachedBitWriter(ostream& out) : out_(out), bucket_idx(0), bucket_bits_allocated(0) { buffer.resize(MAX_CACHED_BYTES); } void CachedBitWriter::WriteNLastBits(uint code, uint n) { while (n) { u_char byte_patch = (code << bucket_bits_allocated) & 0xFF; buffer[bucket_idx] |= byte_patch; u_char bits_collected = 8 - bucket_bits_allocated; code = code >> bits_collected; if (bits_collected <= n) { n -= bits_collected; bucket_bits_allocated = 0; if (++bucket_idx == MAX_CACHED_BYTES) { // Problem here, sometimes it fucks up FlushBuffer(); } } else { bucket_bits_allocated += n; n = 0; } } } bool CachedBitWriter::CanWriteBits(uint length) const { return BufferedBytesCount() * 8 + length < MAX_CACHED_BYTES * 8; } void CachedBitWriter::FlushBuffer() { WritePrimitive<u_char>(out_, buffer.data(), bucket_idx); buffer.assign(MAX_CACHED_BYTES, 0); bucket_idx = 0; bucket_bits_allocated = 0; } void CachedBitWriter::Flush() { if (bucket_bits_allocated) { WriteNLastBits(0, 8 - bucket_bits_allocated); } FlushBuffer(); } size_t CachedBitWriter::BufferedBytesCount() const { return bucket_idx + (bucket_bits_allocated != 0); } const std::vector<u_char>& CachedBitWriter::GetBuffer() const { return buffer; }
#pragma once #include "data/traits.h" #include "data/allocator.h" #include "data/aerecord.h" ////////////////////////////////////////////////////////////////////////// namespace data { /** * @brief Хранилище аэ данных. * * хранит аэ записи, типы хранимых характеристик. * является примитивным хранилищем, которое хранит в себе указатели на * последовательные ае события. */ class ae_collection : fastmem::allocator { public: ae_collection(); /** * @brief очищает хранилище */ void clear(); /** * @brief set_typestring устанавливает набор хранимых характеристик * @param chars указатель на начало буфера * @param end указатель на конец буфера */ void set_typestring(const aera::chars *chars, unsigned count); /** * @brief get_typestring * @param result возвращает */ void get_typestring(std::vector<aera::chars> &result) const; /** * @brief добавляет в коллекцию запись * @param указатель на запись * * при добавлении данные копируются в внутренний выделенный буфер */ void copy_append_record(const double * rec); /** * @brief выделяет указатеьл для очередной записи * @param sz размер, выраженный в количестве double * @return указатель на выделенную область */ double *allocate_record(unsigned sz); /** * @brief append_allocated_record * @param rec указатель на выделенную область * * ВНИМАНИЕ. не осуществляется проверка, что указатель * выделен данным классом (функцией allocate_record) * если это не так, то не гарантируется что время жизни указателя * будет соответствовать времени жизни объекта ae_collection. */ void append_allocated_record(double * rec); /** * @brief возвращает указатель на запись по ее номеру * @param no номер записи */ const double *get_record(unsigned no) const; /** * @brief количество данных, хранящихся в хранилище */ unsigned size() const; bool sorted() const; private: std::vector<aera::chars> chars_; std::vector<double *> data_; bool sorted_; double prevtime_; }; }
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <cstring> #include <queue> #include <map> #include <sstream> #include <cmath> #include <unordered_set> // 需要c++ 11才能支持 #include <unordered_map> // 需要c++ 11才能支持 using namespace std; class MagicIndex { public: /* 没做出来 bool findMagicIndex(vector<int> A, int n) { int l = 0, r = n-1, mid; while(l <= r){ mid = (l+r)/2; cout << "A[mid]=" << A[mid] << " mid=" << mid << endl; if(A[mid] == mid){return true;} else if(A[mid] < mid){ l = mid+1; } else{ r = mid-1; } } return false; }*/ }; void find_(int* a, int n){ for(int i = 0; i < n; ++i){ if(a[i] == i){ cout << i << endl; return; } } cout << "False" << endl; } int main(){ int a[] = {0,0,1,1,3,4,5,6,6,8,9,9,11,11,11,11,12,14,14,14,14,16,18,18,18,20,20,22,24,24,24,26,28,30,30,32,32,32}; int n = 38; find_(a, n); MagicIndex().findMagicIndex(vector<int>(a, a+n), n); return 0; }
#ifndef UNTITLED5_GAME_H #define UNTITLED5_GAME_H #include "View.h" #include <SFML/Graphics.hpp> #include "../managers/ViewManager.h" #include "../managers/GameManager.h" #include "../gameparts/Board.h" #include "../gameparts/SnakePart.h" #include "../gameparts/Snake.h" #include "../gameparts/Food.h" class Game : public View { sf::RectangleShape *rect; sf::Clock *clock; public: Game(); ~Game(); void render(sf::RenderWindow *window); void handleEvent(sf::Event *e); void init(); Board *board; Snake *snake; Food *food; }; #endif //UNTITLED5_GAME_H
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ #include "ReduceCodeTextFontSize.h" #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/console.h> #include <Generation/EncodeTypes/SymbologyEncodeType.h> #include <Generation/EncodeTypes/EncodeTypes.h> #include <Generation/BarCodeImageFormat.h> #include <BarCode.Generation/BarcodeGenerator.h> #include <BarCode.Generation/GenerationParameters/BaseGenerationParameters.h> #include <BarCode.Generation/GenerationParameters/BarcodeParameters.h> #include <BarCode.Generation/GenerationParameters/CodetextParameters.h> #include "RunExamples.h" using namespace Aspose::BarCode::Generation; namespace Aspose { namespace BarCode { namespace Examples { namespace CSharp { namespace CreateAndManageTwoDBarcodes { RTTI_INFO_IMPL_HASH(1949665166u, ::Aspose::BarCode::Examples::CSharp::CreateAndManageTwoDBarcodes::ReduceCodeTextFontSize, ThisTypeBaseTypesInfo); void ReduceCodeTextFontSize::Run() { System::Console::WriteLine(u"ExStart:ReduceCodeTextFontSize"); // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir_CreateAndManage2DBarCodes(); System::String codeText = System::String(u"The quick brown fox jumps over the lazy dog\n") + u"The quick brown fox jumps over the lazy dog\n"; // Instantiate barcode object, Set CodeText, Symbology and CodeLocation System::SharedPtr<BarcodeGenerator> generator = System::MakeObject<BarcodeGenerator>(EncodeTypes::DataMatrix, codeText); generator->get_Parameters()->get_Barcode()->get_CodeTextParameters()->set_Location(CodeLocation::None); generator->Save(dataDir + u"HideBarcodeCodeText_out.png", BarCodeImageFormat::Png); System::Console::WriteLine(u"ExEnd:ReduceCodeTextFontSize"); } } // namespace CreateAndManageTwoDBarcodes } // namespace CSharp } // namespace Examples } // namespace BarCode } // namespace Aspose
#ifndef AROYA_DBSCAN #define AROYA_DBSCAN #include<vector> using namespace std; class AroyaDBSCAN { public: AroyaDBSCAN(); void setData(const vector<vector<double>>&newData); void setRadius(const double&); void setDensity(const int&); void run(); vector<int>getFlag(); void writeFile(const char*fileName, const bool&withData = false); private: //maximum radius double radius; //minimum density int density; //data double**data; int rows, columns, clusters; //点的分类 int *cluster; //distance实时计算 }; #endif
#include <iostream> using namespace std; void main() { char N; bool result; cin >> N; if ((N >= 'a' && N <= 'z' )||(N>='A' && N<='Z')) result = true; else result = false; cout << result; }
// // Created by wojtekreg on 15.01.18. // #ifndef PYRAPORTFEL_PRODUKT_STRUKTURYZOWANY_H #define PYRAPORTFEL_PRODUKT_STRUKTURYZOWANY_H #include "Aktywa.h" class ProduktStrukturyzowany : public Aktywa { private: int czasTrwania; double udzialWZyskach; double maksymalnyZysk; void setCzasTrwania(int czasTrwania); void setUdzialWZyskach(double udzialWZyskach); void setMaksymalnyZysk(double maksymalnyZysk); public: ProduktStrukturyzowany(std::string opis, double wartosc, int czasTrwania, double udzialWZyskach, double maksymalnyZysk); virtual void wyswietlInformacje() override; virtual double wartoscWMiesiacu(int miesiac) override; virtual void edytuj() override; virtual std::string serializuj() override; }; #endif //PYRAPORTFEL_PRODUKT_STRUKTURYZOWANY_H
#ifndef _INC__RPG2K__MODEL__data__BASE_HPP #define _INC__RPG2K__MODEL__data__BASE_HPP #include "Model.hpp" namespace rpg2kLib { namespace model { class DataBase : public Base { private: std::map< uint, std::vector< uint16_t > > charStatus_; std::map< uint, std::vector< uint16_t > > terrain_; std::map< uint, std::vector< std::vector< uint8_t > > > chipFlag_; protected: virtual void load(); virtual RPG2kString getHeader() const { return "LcfDataBase"; } virtual SystemString defaultName() const { return "RPG_RT.ldb"; } public: DataBase(SystemString const& dir); DataBase(SystemString const& dir, SystemString const& name); virtual ~DataBase(); uint getBasicStatus(int charID, int level, ParamType t) const; virtual void save(); structure::Array2D& character() const { return (*this)[11]; } std::vector< uint8_t >& lowerChipFlag(uint id); std::vector< uint8_t >& upperChipFlag(uint id); std::vector< uint16_t >& terrain(uint id); }; } // namespace model } // namespace rpg2kLib #endif
#include <iostream> #include<vector> #include<algorithm> using namespace std; int cmmp(vector<int> v) { int min=1001; for(int i=0;i<v.size();i++) { if(v[i] && min > v[i]) min=v[i]; } return min; } int main() { // your code goes here unsigned int n; cin>>n; vector<int> v; for(int i=0;i<n;i++) { unsigned int t; cin>>t; v.push_back(t); } while(*max_element(v.begin(),v.end())) { unsigned int ct=0; unsigned int min=cmmp(v); for(int i=0;i<v.size();i++) { if(v[i]) { ct++; v[i]-=min; } } cout<<ct<<endl; } return 0; }
#include "votante.h" QString Votante::cedula() const{ return m_cedula; } void Votante::setCedula(const QString &cedula){ m_cedula = cedula; } QString Votante::nombre() const{ return m_nombre; } void Votante::setNombre(const QString &nombre){ m_nombre = nombre; } Votante::Votante(QObject *parent) : QObject(parent){ } Votante::Votante(QString nombre, QString cedula){ m_nombre = nombre; m_cedula = cedula; }
#ifndef _EXPLICIT_FDM_H_ #define _EXPLICIT_FDM_H_ #include "fdm_engine.h" class ExplicitFDM: public FDMEngine { public: /* Constructors and destructor */ ExplicitFDM(); ExplicitFDM(double spot, double maturity, unsigned int imax, unsigned int jmax, double upper, double lower = 0.0); ~ExplicitFDM(); /* calculate price by using EFDM */ virtual void calcPrice(); protected: /* calculate value at (j, i) */ void value(int j, int i); }; #endif
class HighLevelRewrite : public MidLevelRewrite<HighLevelInterfaceNodeCollection> { // Interface classification: // Permits String Based Specification of Transformation: YES // Permits Relative Specification of Target: YES // Contains State information: YES public: // ***************************************************************** // Note about Doxygen: Documentation for enums must appear in the header file. //! The AST Rewrite Mechanism's internal tree traversal mechanism //! (makes the user's use of the rewrite mechanism as simple as possible) template <class RewriteInheritedAttribute, class RewriteSynthesizedAttribute> class RewriteTreeTraversal : public SgTopDownBottomUpProcessing<RewriteInheritedAttribute,RewriteSynthesizedAttribute> { //! Specialized tree traversal for use by transformations (tree traversals that //! use the rewrite mechanism). public: virtual RewriteInheritedAttribute evaluateRewriteInheritedAttribute ( SgNode* astNode, RewriteInheritedAttribute inheritedValue ) = 0; virtual RewriteSynthesizedAttribute evaluateRewriteSynthesizedAttribute ( SgNode* astNode, RewriteInheritedAttribute inheritedValue, typename RewriteTreeTraversal<RewriteInheritedAttribute,RewriteSynthesizedAttribute>::SubTreeSynthesizedAttributes attributList ) = 0; public: // Functions required by the global tree traversal mechanism (must be public?) RewriteInheritedAttribute evaluateInheritedAttribute ( SgNode* astNode, RewriteInheritedAttribute inheritedValue ); RewriteSynthesizedAttribute evaluateSynthesizedAttribute ( SgNode* astNode, RewriteInheritedAttribute inheritedValue, typename RewriteTreeTraversal<RewriteInheritedAttribute,RewriteSynthesizedAttribute>::SubTreeSynthesizedAttributes attributList ); }; //! Class representing synthesized attribute for use in tree traversal // class SynthesizedAttribute : public MiddleLevelRewrite::CollectionType class SynthesizedAttribute : public HighLevelInterfaceNodeCollection { //! This class attempts to provide an interface definition for all Synthesised attributes. We are //! still searching for what would represent a base class set of abstractions for the difinition of //! all possible (or a reasonable subset) of abstractions supporting the specification of //! transformations. //! This class represents the string abstraction required for storing the list of strings for //! declarations, initializations, for insertion into different scopes. For each scope we store a //! list of strings so that redundant strings (or strings redundant upto an integer //! (psuedo-redundant strings as defined and handled by the ROSE/util/string_functions.C code)) can //! be identified and eliminated. This avoids multiply defined variables when multiple //! transformations are applied. public: // Enum typedef types defined in the ASTNodeCollection // typedef HighLevelInterfaceNodeCollection::PlacementPositionEnum PlacementPositionEnum; //! List of strings associated with each scope (ordered from current scope backward to global //! scope). We use the list of strings so that we can identify uniqueness (or //! pseudo-uniqueness). An STL map based on ScopeIdentifierEnum, PlacementPositionEnum, //! SourceCodeStringEnum might be a better container than an STL list or vector of lists. // AST_FragmentStringContainer astFragmentStringContainer; // Declarations required to compile the source code string to generate an AST fragment (which // can be used to edit the original AST). We might still need this. // list<string> supportingDeclarationsForSourceCodeStringList; //! Strings that form declarations and initializations can be sorted and redundent strings //! removed, but strings that build the main body of transformations can not be sorted else we //! generate nonsense. This variable preserves the order of the strings in the list (not //! premiting the removal of redundant strings). This is useful in the specification of the //! main body of the transformation (loop structures etc.). bool preserveStringOrder; //! Link to associated node in the AST // SgNode* associated_AST_Node; public: //! Constructors and destructors virtual ~SynthesizedAttribute(); //! This is required by the tree traversal mechanism (only used by the tree traversal mechanism) SynthesizedAttribute(); //! This is the constructor that we use SynthesizedAttribute ( SgNode* inputASTNode ); SynthesizedAttribute ( const SynthesizedAttribute & X ); SynthesizedAttribute & operator= ( const SynthesizedAttribute & X ); // ********************************************************* // Public (Published) Interface for Synthesized Attribute // ********************************************************* //! These must be defined to take a SgNode and not a SgStatement since //! they can be called from the insert function on any expression within //! a statement under the High-Level Rewrite Interface. void insert ( SgNode* astNode, const std::string & transformation, ScopeIdentifierEnum inputRelativeScope, PlacementPositionEnum inputRelativeLocation ); void replace ( SgNode* astNode, const std::string & transformation, ScopeIdentifierEnum inputRelativeScope = SurroundingScope ); // This should not be specified as part of this interface // (it is defined in the HighLevelRewrite class) // void remove ( SgStatement* target ); // ********************************************************* virtual bool containsStringsForThisNode ( SgNode* astNode ); //! The details of the aggrigation of attributes is abstracted away in to an overloaded //! operator+= member function SynthesizedAttribute & operator+= ( const SynthesizedAttribute & X ); //! generate a display string of the information in the attribute (useful for debugging) bool isEmpty() const; //! Return all the strings associated with a particular scope or node in the AST and //! for a specific position in the scoep or relative to the AST node. std::list<std::string> getStringsSpecificToScopeAndPositionInScope( SgNode* astNode, HighLevelInterfaceNodeCollection::PlacementPositionEnum positionInScope ) const; //! Output a single string representing all the string data concatinated together //! (with "[" and "]" separating different types of data. std::string displayString() const; //! Memeber functions called by derived classes to simplify the implementation //! of the evaluateSynthesizedAttribute() member function. template <class ListOfChildSynthesizedAttributes> void mergeChildSynthesizedAttributes( ListOfChildSynthesizedAttributes & list ); void rewriteAST( SgNode* astNode ); }; private: static void permitedLocationToInsertNewCode ( SgNode* astNode, bool & insertIntoGlobalScope, bool & insertIntoFunctionScope ); static void insertContainerOfListsOfStatements ( SgNode* astNode, const HighLevelInterfaceNodeCollection & X ); static void insertStatementList ( const SgStatementPtrList & X, SgNode* targetNode, IntermediateFileStringPositionEnum positionInScope ); public: // We set the default to generate #include directives instead of all the // declarations from all system files (which can sometimes fail to unparse). // Note that the HighLevelInterface::generatePrefixAndSuffix() differs from // the MidLevelInterface::generatePrefixAndSuffix(). static void generatePrefixAndSuffix ( SgNode* astNode, std::string & globalPrefixString, std::string & localPrefixString, std::string & suffixString, // bool generateIncludeDirectives = true, // bool prefixIncludesCurrentStatement = false ); bool generateIncludeDirectives, bool prefixIncludesCurrentStatement ); // public (and published) interface member functions (can be used from synthesized attributes as well) static void remove ( SgStatement* target ); };
#ifndef MAKSA_H #define MAKSA_H #include <QDialog> #include "dllmysql.h" namespace Ui { class Maksa; } class Maksa : public QDialog { Q_OBJECT public: explicit Maksa(QWidget *parent = nullptr); ~Maksa(); public slots: void asetaSaldo(double s){saldo=s;} void asetaTili(int i){idTili = i;} void asetaLaskujenMaara(int m){laskujenMaara=m;} private slots: void on_btnPeruuta_clicked(); void on_btnHaeTiedot_clicked(); void asetaTiedot(QString tilinumero, QString saaja, QString viite, double summa); void tyhjenna(); void on_btnMaksa_clicked(); void asetaSumma(double i){summa=i;} void asetaTili(QString a){tilinumero=a;} void asetaViite(QString a){viite=a;} void asetaSaaja(QString a){saaja=a;} private: Ui::Maksa *ui; DLLMySQL *olio4mysql; QString tilinumero; QString saaja; QString viite; double saldo=0.0; int laskujenMaara=0; double laskunSumma=0; int idTili; int laskuID=0; double summa = 0; }; #endif // MAKSA_H
#include "PJS.h" class Baseline : PJS { };
// Module: Matrix.h // Author: Miguel Antonio Logarta // Date: April 17, 2020 // Purpose: Header file for Matrix class // Bi-directional linked list #pragma once class Matrix { public: // Constructor Matrix(string, string, string, string, string); // Accessors TCHAR* GetName(); TCHAR* GetDec(); TCHAR* GetHex(); TCHAR* GetOct(); TCHAR* GetBin(); // Link void SetNext(Matrix*); // Set Next void SetPrev(Matrix*); // Set Prev Matrix* GetNext(); // Return Next Matrix* GetPrev(); // Return Prev private: // Stored data TCHAR szName[TCHAR_SIZE]; TCHAR szDec[TCHAR_SIZE]; TCHAR szHex[TCHAR_SIZE]; TCHAR szOct[TCHAR_SIZE]; TCHAR szBin[TCHAR_SIZE]; Matrix* Next; // Link to the next node Matrix* Prev; // Link to the previous node };
// ***************************************************************** // This file is part of the CYBERMED Libraries // // Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve), // Federal University of Paraiba and University of São Paulo. // All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // ***************************************************************** #include "cybTCPIteractiveServer.h" CybTCPIteractiveServer::CybTCPIteractiveServer(const short server_port): CybTCPServer(server_port) { } void CybTCPIteractiveServer::communicate(int i) { char* msg = "the server is on"; int size = 30; char buffer[30]; CybTCPClient* client = this->getClient(i); if(client) { try {// o problema esta aki this->receiveData(client->getSock(), buffer, size); cout << buffer << endl; this->sendData(client->getSock(), msg, size); } catch(CybCommunicationException e) { e.showErrorMessage(); } } }
#include "stdafx.h" #include "Game\Parent.h" #include "Title.h" using namespace Sequence; Child* Title::update(Parent* parent) { Child* next= this; switch(b) { case 1: next = new Game::Parent; break; } return next; };
/*#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> int main(){ int s = socket(AF_INET, SOCK_STREAM, 0); if(s<0){ printf("Error on server socket"); return 1; } struct sockaddr_in server, client; int c, err, l; memset(&server, 0, sizeof(server)); server.sin_port = htons(1234); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; if(bind(s, (struct sockaddr*)&server, sizeof(server)) < 0){ printf("Error on bind\n"); return 1; } listen(s, 5); l = sizeof(client); memset(&client, 0, sizeof(client)); printf("Listening for incoming connections\n"); while(1){ c = accept(s, (struct sockaddr*)&client, (socklen_t*)&l); err = errno; if(c<0){ printf("Accept error: %d", err); continue; } printf("Incoming connected client from %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); int nr; int res = recv(c, (char*)&nr, sizeof(nr), 0); if(res != sizeof(nr)) printf("Error on nr\n"); nr = ntohl(nr); printf("Received: %d\n", nr); int* v = (int*)malloc(sizeof(int) * ((1 + nr/2))); int k=0; for(int i=1;i<=nr/2;i+=1) if(nr%i == 0) v[k++] = i; v[k++] = nr; int aux = htonl(k); send(c, (char*)&aux, sizeof(aux), 0); for(int i=0;i<k;i+=1){ aux = htonl(v[i]); send(c, (char*)&aux, sizeof(aux), 0); } free(v); close(c); } } */
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.UI.ApplicationSettings.0.h" #include "Windows.Foundation.0.h" #include "Windows.Security.Credentials.0.h" #include "Windows.UI.Popups.0.h" #include "Windows.Foundation.Collections.1.h" #include "Windows.Foundation.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::UI::ApplicationSettings { struct __declspec(uuid("61c0e185-0977-4678-b4e2-98727afbeed9")) __declspec(novtable) CredentialCommandCredentialDeletedHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::UI::ApplicationSettings::ICredentialCommand * command) = 0; }; struct __declspec(uuid("81ea942c-4f09-4406-a538-838d9b14b7e6")) __declspec(novtable) IAccountsSettingsPane : Windows::Foundation::IInspectable { virtual HRESULT __stdcall add_AccountCommandsRequested(Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::AccountsSettingsPane, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs> * handler, event_token * cookie) = 0; virtual HRESULT __stdcall remove_AccountCommandsRequested(event_token cookie) = 0; }; struct __declspec(uuid("3b68c099-db19-45d0-9abf-95d3773c9330")) __declspec(novtable) IAccountsSettingsPaneCommandsRequestedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_WebAccountProviderCommands(Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::WebAccountProviderCommand> ** value) = 0; virtual HRESULT __stdcall get_WebAccountCommands(Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::WebAccountCommand> ** value) = 0; virtual HRESULT __stdcall get_CredentialCommands(Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::CredentialCommand> ** value) = 0; virtual HRESULT __stdcall get_Commands(Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::SettingsCommand> ** value) = 0; virtual HRESULT __stdcall get_HeaderText(hstring * value) = 0; virtual HRESULT __stdcall put_HeaderText(hstring value) = 0; virtual HRESULT __stdcall abi_GetDeferral(Windows::UI::ApplicationSettings::IAccountsSettingsPaneEventDeferral ** deferral) = 0; }; struct __declspec(uuid("cbf25d3f-e5ba-40ef-93da-65e096e5fb04")) __declspec(novtable) IAccountsSettingsPaneEventDeferral : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_Complete() = 0; }; struct __declspec(uuid("561f8b60-b0ec-4150-a8dc-208ee44b068a")) __declspec(novtable) IAccountsSettingsPaneStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_GetForCurrentView(Windows::UI::ApplicationSettings::IAccountsSettingsPane ** current) = 0; virtual HRESULT __stdcall abi_Show() = 0; }; struct __declspec(uuid("d21df7c2-ce0d-484f-b8e8-e823c215765e")) __declspec(novtable) IAccountsSettingsPaneStatics2 : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_ShowManageAccountsAsync(Windows::Foundation::IAsyncAction ** asyncInfo) = 0; virtual HRESULT __stdcall abi_ShowAddAccountAsync(Windows::Foundation::IAsyncAction ** asyncInfo) = 0; }; struct __declspec(uuid("a5f665e6-6143-4a7a-a971-b017ba978ce2")) __declspec(novtable) ICredentialCommand : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_PasswordCredential(Windows::Security::Credentials::IPasswordCredential ** value) = 0; virtual HRESULT __stdcall get_CredentialDeleted(Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler ** value) = 0; }; struct __declspec(uuid("27e88c17-bc3e-4b80-9495-4ed720e48a91")) __declspec(novtable) ICredentialCommandFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateCredentialCommand(Windows::Security::Credentials::IPasswordCredential * passwordCredential, Windows::UI::ApplicationSettings::ICredentialCommand ** instance) = 0; virtual HRESULT __stdcall abi_CreateCredentialCommandWithHandler(Windows::Security::Credentials::IPasswordCredential * passwordCredential, Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler * deleted, Windows::UI::ApplicationSettings::ICredentialCommand ** instance) = 0; }; struct __declspec(uuid("68e15b33-1c83-433a-aa5a-ceeea5bd4764")) __declspec(novtable) ISettingsCommandFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateSettingsCommand(Windows::Foundation::IInspectable * settingsCommandId, hstring label, Windows::UI::Popups::UICommandInvokedHandler * handler, Windows::UI::Popups::IUICommand ** instance) = 0; }; struct __declspec(uuid("749ae954-2f69-4b17-8aba-d05ce5778e46")) __declspec(novtable) ISettingsCommandStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_AccountsCommand(Windows::UI::Popups::IUICommand ** value) = 0; }; struct __declspec(uuid("b1cd0932-4570-4c69-8d38-89446561ace0")) __declspec(novtable) ISettingsPane : Windows::Foundation::IInspectable { virtual HRESULT __stdcall add_CommandsRequested(Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::SettingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs> * handler, event_token * cookie) = 0; virtual HRESULT __stdcall remove_CommandsRequested(event_token cookie) = 0; }; struct __declspec(uuid("44df23ae-5d6e-4068-a168-f47643182114")) __declspec(novtable) ISettingsPaneCommandsRequest : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_ApplicationCommands(Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::SettingsCommand> ** value) = 0; }; struct __declspec(uuid("205f5d24-1b48-4629-a6ca-2fdfedafb75d")) __declspec(novtable) ISettingsPaneCommandsRequestedEventArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Request(Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequest ** request) = 0; }; struct __declspec(uuid("1c6a52c5-ff19-471b-ba6b-f8f35694ad9a")) __declspec(novtable) ISettingsPaneStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_GetForCurrentView(Windows::UI::ApplicationSettings::ISettingsPane ** current) = 0; virtual HRESULT __stdcall abi_Show() = 0; virtual HRESULT __stdcall get_Edge(winrt::Windows::UI::ApplicationSettings::SettingsEdgeLocation * value) = 0; }; struct __declspec(uuid("caa39398-9cfa-4246-b0c4-a913a3896541")) __declspec(novtable) IWebAccountCommand : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_WebAccount(Windows::Security::Credentials::IWebAccount ** value) = 0; virtual HRESULT __stdcall get_Invoked(Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler ** value) = 0; virtual HRESULT __stdcall get_Actions(winrt::Windows::UI::ApplicationSettings::SupportedWebAccountActions * value) = 0; }; struct __declspec(uuid("bfa6cdff-2f2d-42f5-81de-1d56bafc496d")) __declspec(novtable) IWebAccountCommandFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateWebAccountCommand(Windows::Security::Credentials::IWebAccount * webAccount, Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler * invoked, winrt::Windows::UI::ApplicationSettings::SupportedWebAccountActions actions, Windows::UI::ApplicationSettings::IWebAccountCommand ** instance) = 0; }; struct __declspec(uuid("e7abcc40-a1d8-4c5d-9a7f-1d34b2f90ad2")) __declspec(novtable) IWebAccountInvokedArgs : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Action(winrt::Windows::UI::ApplicationSettings::WebAccountAction * action) = 0; }; struct __declspec(uuid("d69bdd9a-a0a6-4e9b-88dc-c71e757a3501")) __declspec(novtable) IWebAccountProviderCommand : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_WebAccountProvider(Windows::Security::Credentials::IWebAccountProvider ** value) = 0; virtual HRESULT __stdcall get_Invoked(Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler ** value) = 0; }; struct __declspec(uuid("d5658a1b-b176-4776-8469-a9d3ff0b3f59")) __declspec(novtable) IWebAccountProviderCommandFactory : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreateWebAccountProviderCommand(Windows::Security::Credentials::IWebAccountProvider * webAccountProvider, Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler * invoked, Windows::UI::ApplicationSettings::IWebAccountProviderCommand ** instance) = 0; }; struct __declspec(uuid("1ee6e459-1705-4a9a-b599-a0c3d6921973")) __declspec(novtable) WebAccountCommandInvokedHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::UI::ApplicationSettings::IWebAccountCommand * command, Windows::UI::ApplicationSettings::IWebAccountInvokedArgs * args) = 0; }; struct __declspec(uuid("b7de5527-4c8f-42dd-84da-5ec493abdb9a")) __declspec(novtable) WebAccountProviderCommandInvokedHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::UI::ApplicationSettings::IWebAccountProviderCommand * command) = 0; }; } namespace ABI { template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPane> { using default_interface = Windows::UI::ApplicationSettings::IAccountsSettingsPane; }; template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs> { using default_interface = Windows::UI::ApplicationSettings::IAccountsSettingsPaneCommandsRequestedEventArgs; }; template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPaneEventDeferral> { using default_interface = Windows::UI::ApplicationSettings::IAccountsSettingsPaneEventDeferral; }; template <> struct traits<Windows::UI::ApplicationSettings::CredentialCommand> { using default_interface = Windows::UI::ApplicationSettings::ICredentialCommand; }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsCommand> { using default_interface = Windows::UI::Popups::IUICommand; }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPane> { using default_interface = Windows::UI::ApplicationSettings::ISettingsPane; }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPaneCommandsRequest> { using default_interface = Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequest; }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs> { using default_interface = Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequestedEventArgs; }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountCommand> { using default_interface = Windows::UI::ApplicationSettings::IWebAccountCommand; }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountInvokedArgs> { using default_interface = Windows::UI::ApplicationSettings::IWebAccountInvokedArgs; }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountProviderCommand> { using default_interface = Windows::UI::ApplicationSettings::IWebAccountProviderCommand; }; } namespace Windows::UI::ApplicationSettings { template <typename D> struct WINRT_EBO impl_IAccountsSettingsPane { event_token AccountCommandsRequested(const Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::AccountsSettingsPane, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs> & handler) const; using AccountCommandsRequested_revoker = event_revoker<IAccountsSettingsPane>; AccountCommandsRequested_revoker AccountCommandsRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::AccountsSettingsPane, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs> & handler) const; void AccountCommandsRequested(event_token cookie) const; }; template <typename D> struct WINRT_EBO impl_IAccountsSettingsPaneCommandsRequestedEventArgs { Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::WebAccountProviderCommand> WebAccountProviderCommands() const; Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::WebAccountCommand> WebAccountCommands() const; Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::CredentialCommand> CredentialCommands() const; Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::SettingsCommand> Commands() const; hstring HeaderText() const; void HeaderText(hstring_view value) const; Windows::UI::ApplicationSettings::AccountsSettingsPaneEventDeferral GetDeferral() const; }; template <typename D> struct WINRT_EBO impl_IAccountsSettingsPaneEventDeferral { void Complete() const; }; template <typename D> struct WINRT_EBO impl_IAccountsSettingsPaneStatics { Windows::UI::ApplicationSettings::AccountsSettingsPane GetForCurrentView() const; void Show() const; }; template <typename D> struct WINRT_EBO impl_IAccountsSettingsPaneStatics2 { Windows::Foundation::IAsyncAction ShowManageAccountsAsync() const; Windows::Foundation::IAsyncAction ShowAddAccountAsync() const; }; template <typename D> struct WINRT_EBO impl_ICredentialCommand { Windows::Security::Credentials::PasswordCredential PasswordCredential() const; Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler CredentialDeleted() const; }; template <typename D> struct WINRT_EBO impl_ICredentialCommandFactory { Windows::UI::ApplicationSettings::CredentialCommand CreateCredentialCommand(const Windows::Security::Credentials::PasswordCredential & passwordCredential) const; Windows::UI::ApplicationSettings::CredentialCommand CreateCredentialCommandWithHandler(const Windows::Security::Credentials::PasswordCredential & passwordCredential, const Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler & deleted) const; }; template <typename D> struct WINRT_EBO impl_ISettingsCommandFactory { Windows::UI::ApplicationSettings::SettingsCommand CreateSettingsCommand(const Windows::Foundation::IInspectable & settingsCommandId, hstring_view label, const Windows::UI::Popups::UICommandInvokedHandler & handler) const; }; template <typename D> struct WINRT_EBO impl_ISettingsCommandStatics { Windows::UI::ApplicationSettings::SettingsCommand AccountsCommand() const; }; template <typename D> struct WINRT_EBO impl_ISettingsPane { [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] event_token CommandsRequested(const Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::SettingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs> & handler) const; using CommandsRequested_revoker = event_revoker<ISettingsPane>; [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] CommandsRequested_revoker CommandsRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::UI::ApplicationSettings::SettingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs> & handler) const; [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] void CommandsRequested(event_token cookie) const; }; template <typename D> struct WINRT_EBO impl_ISettingsPaneCommandsRequest { [[deprecated("SettingsPaneCommandsRequest is deprecated and might not work on all platforms. For more info, see MSDN.")]] Windows::Foundation::Collections::IVector<Windows::UI::ApplicationSettings::SettingsCommand> ApplicationCommands() const; }; template <typename D> struct WINRT_EBO impl_ISettingsPaneCommandsRequestedEventArgs { [[deprecated("SettingsPaneCommandsRequestedEventArgs is deprecated and might not work on all platforms. For more info, see MSDN.")]] Windows::UI::ApplicationSettings::SettingsPaneCommandsRequest Request() const; }; template <typename D> struct WINRT_EBO impl_ISettingsPaneStatics { [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] Windows::UI::ApplicationSettings::SettingsPane GetForCurrentView() const; [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] void Show() const; [[deprecated("SettingsPane is deprecated and might not work on all platforms. For more info, see MSDN.")]] Windows::UI::ApplicationSettings::SettingsEdgeLocation Edge() const; }; template <typename D> struct WINRT_EBO impl_IWebAccountCommand { Windows::Security::Credentials::WebAccount WebAccount() const; Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler Invoked() const; Windows::UI::ApplicationSettings::SupportedWebAccountActions Actions() const; }; template <typename D> struct WINRT_EBO impl_IWebAccountCommandFactory { Windows::UI::ApplicationSettings::WebAccountCommand CreateWebAccountCommand(const Windows::Security::Credentials::WebAccount & webAccount, const Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler & invoked, Windows::UI::ApplicationSettings::SupportedWebAccountActions actions) const; }; template <typename D> struct WINRT_EBO impl_IWebAccountInvokedArgs { Windows::UI::ApplicationSettings::WebAccountAction Action() const; }; template <typename D> struct WINRT_EBO impl_IWebAccountProviderCommand { Windows::Security::Credentials::WebAccountProvider WebAccountProvider() const; Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler Invoked() const; }; template <typename D> struct WINRT_EBO impl_IWebAccountProviderCommandFactory { Windows::UI::ApplicationSettings::WebAccountProviderCommand CreateWebAccountProviderCommand(const Windows::Security::Credentials::WebAccountProvider & webAccountProvider, const Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler & invoked) const; }; } namespace impl { template <> struct traits<Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler> { using abi = ABI::Windows::UI::ApplicationSettings::CredentialCommandCredentialDeletedHandler; }; template <> struct traits<Windows::UI::ApplicationSettings::IAccountsSettingsPane> { using abi = ABI::Windows::UI::ApplicationSettings::IAccountsSettingsPane; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IAccountsSettingsPane<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IAccountsSettingsPaneCommandsRequestedEventArgs> { using abi = ABI::Windows::UI::ApplicationSettings::IAccountsSettingsPaneCommandsRequestedEventArgs; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IAccountsSettingsPaneCommandsRequestedEventArgs<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IAccountsSettingsPaneEventDeferral> { using abi = ABI::Windows::UI::ApplicationSettings::IAccountsSettingsPaneEventDeferral; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IAccountsSettingsPaneEventDeferral<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IAccountsSettingsPaneStatics> { using abi = ABI::Windows::UI::ApplicationSettings::IAccountsSettingsPaneStatics; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IAccountsSettingsPaneStatics<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IAccountsSettingsPaneStatics2> { using abi = ABI::Windows::UI::ApplicationSettings::IAccountsSettingsPaneStatics2; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IAccountsSettingsPaneStatics2<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ICredentialCommand> { using abi = ABI::Windows::UI::ApplicationSettings::ICredentialCommand; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ICredentialCommand<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ICredentialCommandFactory> { using abi = ABI::Windows::UI::ApplicationSettings::ICredentialCommandFactory; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ICredentialCommandFactory<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsCommandFactory> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsCommandFactory; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsCommandFactory<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsCommandStatics> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsCommandStatics; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsCommandStatics<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsPane> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsPane; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsPane<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequest> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequest; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsPaneCommandsRequest<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequestedEventArgs> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsPaneCommandsRequestedEventArgs; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsPaneCommandsRequestedEventArgs<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::ISettingsPaneStatics> { using abi = ABI::Windows::UI::ApplicationSettings::ISettingsPaneStatics; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_ISettingsPaneStatics<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IWebAccountCommand> { using abi = ABI::Windows::UI::ApplicationSettings::IWebAccountCommand; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IWebAccountCommand<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IWebAccountCommandFactory> { using abi = ABI::Windows::UI::ApplicationSettings::IWebAccountCommandFactory; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IWebAccountCommandFactory<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IWebAccountInvokedArgs> { using abi = ABI::Windows::UI::ApplicationSettings::IWebAccountInvokedArgs; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IWebAccountInvokedArgs<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IWebAccountProviderCommand> { using abi = ABI::Windows::UI::ApplicationSettings::IWebAccountProviderCommand; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IWebAccountProviderCommand<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::IWebAccountProviderCommandFactory> { using abi = ABI::Windows::UI::ApplicationSettings::IWebAccountProviderCommandFactory; template <typename D> using consume = Windows::UI::ApplicationSettings::impl_IWebAccountProviderCommandFactory<D>; }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler> { using abi = ABI::Windows::UI::ApplicationSettings::WebAccountCommandInvokedHandler; }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler> { using abi = ABI::Windows::UI::ApplicationSettings::WebAccountProviderCommandInvokedHandler; }; template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPane> { using abi = ABI::Windows::UI::ApplicationSettings::AccountsSettingsPane; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.AccountsSettingsPane"; } }; template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs> { using abi = ABI::Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.AccountsSettingsPaneCommandsRequestedEventArgs"; } }; template <> struct traits<Windows::UI::ApplicationSettings::AccountsSettingsPaneEventDeferral> { using abi = ABI::Windows::UI::ApplicationSettings::AccountsSettingsPaneEventDeferral; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.AccountsSettingsPaneEventDeferral"; } }; template <> struct traits<Windows::UI::ApplicationSettings::CredentialCommand> { using abi = ABI::Windows::UI::ApplicationSettings::CredentialCommand; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.CredentialCommand"; } }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsCommand> { using abi = ABI::Windows::UI::ApplicationSettings::SettingsCommand; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.SettingsCommand"; } }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPane> { using abi = ABI::Windows::UI::ApplicationSettings::SettingsPane; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.SettingsPane"; } }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPaneCommandsRequest> { using abi = ABI::Windows::UI::ApplicationSettings::SettingsPaneCommandsRequest; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.SettingsPaneCommandsRequest"; } }; template <> struct traits<Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs> { using abi = ABI::Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs"; } }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountCommand> { using abi = ABI::Windows::UI::ApplicationSettings::WebAccountCommand; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.WebAccountCommand"; } }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountInvokedArgs> { using abi = ABI::Windows::UI::ApplicationSettings::WebAccountInvokedArgs; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.WebAccountInvokedArgs"; } }; template <> struct traits<Windows::UI::ApplicationSettings::WebAccountProviderCommand> { using abi = ABI::Windows::UI::ApplicationSettings::WebAccountProviderCommand; static constexpr const wchar_t * name() noexcept { return L"Windows.UI.ApplicationSettings.WebAccountProviderCommand"; } }; } }
#include <iostream> using namespace std; int main() { int qnt; cin >> qnt; bool flag = true ; while(qnt != 0){ int numeros[qnt]; if(!flag) cout << endl ; flag = false ; for(int i = 0; i < qnt; i++){ cin >> numeros[i]; } for(int i = 0; i < qnt; i++){ for(int j = i+1; j < qnt; j++){ for(int k = j+1; k < qnt; k++){ for(int l = k+1; l < qnt; l++){ for(int m = l+1; m < qnt; m++){ for(int n = m+1; n < qnt; n++){ cout << numeros[i] << " "; cout << numeros[j] << " "; cout << numeros[k] << " "; cout << numeros[l] << " "; cout << numeros[m] << " "; cout << numeros[n] << endl; } } } } } } cin >> qnt; } return 0; }
#include <iostream> #include <iCub/iDyn/iDyn.h> #include <yarp/sig/all.h> #include <yarp/math/api.h> #include <yarp/os/Log.h> #include <yarp/os/all.h> #include <yarp/os/Time.h> #include "chain_conversion.h" #include <kdl/chainfksolver.hpp> #include "custom_kdl/chainidsolver_recursive_newton_euler_internal_wrenches.hpp" #include <kdl/chainfksolverpos_recursive.hpp> #include <kdl/chainfksolvervel_recursive.hpp> #include <kdl/frames_io.hpp> #include <kdl/kinfam_io.hpp> #include <cassert> using namespace std; using namespace iCub::iDyn; using namespace yarp::math; using namespace yarp::sig; using namespace yarp::os; double delta = 1e-10; #define EQUALISH(x,y) norm(x-y) < delta void printMatrix(string s,const Matrix &m) { cout<<s<<endl; for(int i=0;i<m.rows();i++) { for(int j=0;j<m.cols();j++) cout << " " <<m(i,j); cout<<endl; } } double g = 9.8; class ManyDofDyn : public iDynLimb { public: ManyDofDyn(); }; ManyDofDyn::ManyDofDyn() { allocate(""); pushLink(new iDynLink(0.189, 0.005e-3, 18.7e-3, 1.19e-3, 123.0e-6, 0.021e-6, -0.001e-6, 24.4e-6, 4.22e-6, 113.0e-6, 0.0, -0.0, M_PI/2.0, -M_PI/2.0, -95.5*CTRL_DEG2RAD, 5.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.179, -0.094e-3, -6.27e-3, -16.6e-3, 137.0e-6, -0.453e-06, 0.203e-06, 83.0e-6, 20.7e-6, 99.3e-6, 0.0, 0.0, -M_PI/2.0, -M_PI/2.0, 0.0, 160.8*CTRL_DEG2RAD)); pushLink(new iDynLink(0.884, 1.79e-3, -62.9e-3, 0.064e-03, 743.0e-6, 63.9e-6, 0.851e-06, 336.0e-6, -3.61e-6, 735.0e-6, -0.015, -0.15228, -M_PI/2.0, -105.0*CTRL_DEG2RAD, -37.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.074, -13.7e-3, -3.71e-3, 1.05e-3, 28.4e-6, -0.502e-6, -0.399e-6, 9.24e-6, -0.371e-6, 29.9e-6, 0.015, 0.0, M_PI/2.0, 0.0, 5.5*CTRL_DEG2RAD, 106.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.525, -0.347e-3, 71.3e-3, -4.76e-3, 766.0e-6, 5.66e-6, 1.40e-6, 164.0e-6, 18.2e-6, 699.0e-6, 0.0, -0.1373, M_PI/2.0, -M_PI/2.0, -90.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, M_PI/2.0, M_PI/2.0, -90.0*CTRL_DEG2RAD, 0.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.213, 7.73e-3, -8.05e-3, -9.00e-3, 154.0e-6, 12.6e-6, -6.08e-6, 250.0e-6, 17.6e-6, 378.0e-6, 0.0625, 0.016, 0.0, M_PI, -20.0*CTRL_DEG2RAD, 40.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.189, 0.005e-3, 18.7e-3, 1.19e-3, 123.0e-6, 0.021e-6, -0.001e-6, 24.4e-6, 4.22e-6, 113.0e-6, 0.0, -0.0, M_PI/2.0, -M_PI/2.0, -95.5*CTRL_DEG2RAD, 5.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.179, -0.094e-3, -6.27e-3, -16.6e-3, 137.0e-6, -0.453e-06, 0.203e-06, 83.0e-6, 20.7e-6, 99.3e-6, 0.0, 0.0, -M_PI/2.0, -M_PI/2.0, 0.0, 160.8*CTRL_DEG2RAD)); pushLink(new iDynLink(0.884, 1.79e-3, -62.9e-3, 0.064e-03, 743.0e-6, 63.9e-6, 0.851e-06, 336.0e-6, -3.61e-6, 735.0e-6, -0.015, -0.15228, -M_PI/2.0, -105.0*CTRL_DEG2RAD, -37.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.074, -13.7e-3, -3.71e-3, 1.05e-3, 28.4e-6, -0.502e-6, -0.399e-6, 9.24e-6, -0.371e-6, 29.9e-6, 0.015, 0.0, M_PI/2.0, 0.0, 5.5*CTRL_DEG2RAD, 106.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.525, -0.347e-3, 71.3e-3, -4.76e-3, 766.0e-6, 5.66e-6, 1.40e-6, 164.0e-6, 18.2e-6, 699.0e-6, 0.0, -0.1373, M_PI/2.0, -M_PI/2.0, -90.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, M_PI/2.0, M_PI/2.0, -90.0*CTRL_DEG2RAD, 0.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.213, 7.73e-3, -8.05e-3, -9.00e-3, 154.0e-6, 12.6e-6, -6.08e-6, 250.0e-6, 17.6e-6, 378.0e-6, 0.0625, 0.016, 0.0, M_PI, -20.0*CTRL_DEG2RAD, 40.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.189, 0.005e-3, 18.7e-3, 1.19e-3, 123.0e-6, 0.021e-6, -0.001e-6, 24.4e-6, 4.22e-6, 113.0e-6, 0.0, -0.0, M_PI/2.0, -M_PI/2.0, -95.5*CTRL_DEG2RAD, 5.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.179, -0.094e-3, -6.27e-3, -16.6e-3, 137.0e-6, -0.453e-06, 0.203e-06, 83.0e-6, 20.7e-6, 99.3e-6, 0.0, 0.0, -M_PI/2.0, -M_PI/2.0, 0.0, 160.8*CTRL_DEG2RAD)); pushLink(new iDynLink(0.884, 1.79e-3, -62.9e-3, 0.064e-03, 743.0e-6, 63.9e-6, 0.851e-06, 336.0e-6, -3.61e-6, 735.0e-6, -0.015, -0.15228, -M_PI/2.0, -105.0*CTRL_DEG2RAD, -37.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.074, -13.7e-3, -3.71e-3, 1.05e-3, 28.4e-6, -0.502e-6, -0.399e-6, 9.24e-6, -0.371e-6, 29.9e-6, 0.015, 0.0, M_PI/2.0, 0.0, 5.5*CTRL_DEG2RAD, 106.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.525, -0.347e-3, 71.3e-3, -4.76e-3, 766.0e-6, 5.66e-6, 1.40e-6, 164.0e-6, 18.2e-6, 699.0e-6, 0.0, -0.1373, M_PI/2.0, -M_PI/2.0, -90.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, M_PI/2.0, M_PI/2.0, -90.0*CTRL_DEG2RAD, 0.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.213, 7.73e-3, -8.05e-3, -9.00e-3, 154.0e-6, 12.6e-6, -6.08e-6, 250.0e-6, 17.6e-6, 378.0e-6, 0.0625, 0.016, 0.0, M_PI, -20.0*CTRL_DEG2RAD, 40.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.189, 0.005e-3, 18.7e-3, 1.19e-3, 123.0e-6, 0.021e-6, -0.001e-6, 24.4e-6, 4.22e-6, 113.0e-6, 0.0, -0.0, M_PI/2.0, -M_PI/2.0, -95.5*CTRL_DEG2RAD, 5.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.179, -0.094e-3, -6.27e-3, -16.6e-3, 137.0e-6, -0.453e-06, 0.203e-06, 83.0e-6, 20.7e-6, 99.3e-6, 0.0, 0.0, -M_PI/2.0, -M_PI/2.0, 0.0, 160.8*CTRL_DEG2RAD)); pushLink(new iDynLink(0.884, 1.79e-3, -62.9e-3, 0.064e-03, 743.0e-6, 63.9e-6, 0.851e-06, 336.0e-6, -3.61e-6, 735.0e-6, -0.015, -0.15228, -M_PI/2.0, -105.0*CTRL_DEG2RAD, -37.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.074, -13.7e-3, -3.71e-3, 1.05e-3, 28.4e-6, -0.502e-6, -0.399e-6, 9.24e-6, -0.371e-6, 29.9e-6, 0.015, 0.0, M_PI/2.0, 0.0, 5.5*CTRL_DEG2RAD, 106.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.525, -0.347e-3, 71.3e-3, -4.76e-3, 766.0e-6, 5.66e-6, 1.40e-6, 164.0e-6, 18.2e-6, 699.0e-6, 0.0, -0.1373, M_PI/2.0, -M_PI/2.0, -90.0*CTRL_DEG2RAD, 90.0*CTRL_DEG2RAD)); pushLink(new iDynLink( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0.0, M_PI/2.0, M_PI/2.0, -90.0*CTRL_DEG2RAD, 0.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.213, 7.73e-3, -8.05e-3, -9.00e-3, 154.0e-6, 12.6e-6, -6.08e-6, 250.0e-6, 17.6e-6, 378.0e-6, 0.0625, 0.016, 0.0, M_PI, -20.0*CTRL_DEG2RAD, 40.0*CTRL_DEG2RAD)); pushLink(new iDynLink(0.074, -13.7e-3, -3.71e-3, 1.05e-3, 28.4e-6, -0.502e-6, -0.399e-6, 9.24e-6, -0.371e-6, 29.9e-6, 0.015, 0.0, M_PI/2.0, 0.0, 5.5*CTRL_DEG2RAD, 106.0*CTRL_DEG2RAD)); } int main() { Vector Fend(3); Fend.zero(); Vector Muend(Fend); Vector w0(3); Vector dw0(3); Vector ddp0(3); w0 = dw0=ddp0= 3.8; ddp0[1]=g; ManyDofDyn Chain_iDyn; int N = Chain_iDyn.getN(); Vector q(N); Vector dq(N); Vector ddq(N); Random rng; rng.seed(yarp::os::Time::now()); for(int i=0;i<N-1;i++) { q[i] = 0*CTRL_DEG2RAD*rng.uniform(); dq[i] = 0*CTRL_DEG2RAD*rng.uniform(); ddq[i] = 0*CTRL_DEG2RAD*rng.uniform(); } for(int i=N-1;i<N;i++) { q[i] = 0; dq[i] = 0; ddq[i] = 1; } int nj=N; KDL::JntArray jointpositions = KDL::JntArray(nj); KDL::JntArray jointvel = KDL::JntArray(nj); KDL::JntArray jointacc = KDL::JntArray(nj); KDL::JntArray torques = KDL::JntArray(nj); int N_TRIALS = 100000; double time_idyn = 0.0; double time_kdl = 0.0; double tic = 0.0; double toc = 0.0; Chain_iDyn.prepareNewtonEuler(DYNAMIC); KDL::Chain kdlChain; idynChain2kdlChain(Chain_iDyn,kdlChain); /* KDL::JntArray jointpositions = KDL::JntArray(nj); KDL::JntArray jointvel = KDL::JntArray(nj); KDL::JntArray jointacc = KDL::JntArray(nj); KDL::JntArray torques = KDL::JntArray(nj); */ for(unsigned int i=0;i<nj;i++){ jointpositions(i)=q[i]; jointvel(i) = dq[i]; jointacc(i) = ddq[i]; } KDL::Wrenches f_ext(nj); KDL::Wrenches f_int(nj); KDL::Vector grav_kdl; idynVector2kdlVector(Chain_iDyn.getH0().submatrix(0,2,0,2).transposed()*ddp0,grav_kdl); KDL::ChainIdSolver_RNE_IW neSolver = KDL::ChainIdSolver_RNE_IW(kdlChain,-grav_kdl); for(int trial=0; trial < N_TRIALS; trial++ ) { q = Chain_iDyn.setAng(q); dq = Chain_iDyn.setDAng(dq); ddq = Chain_iDyn.setD2Ang(ddq); for(unsigned int i=0;i<nj;i++){ jointpositions(i)=q[i]; jointvel(i) = dq[i]; jointacc(i) = ddq[i]; } tic = yarp::os::Time::now(); Chain_iDyn.computeNewtonEuler(w0,dw0,ddp0,Fend,Muend); toc = yarp::os::Time::now(); Matrix F = Chain_iDyn.getForces(); time_idyn += (toc-tic); tic = yarp::os::Time::now(); YARP_ASSERT( neSolver.CartToJnt_and_internal_wrenches(jointpositions,jointvel,jointacc,f_ext,torques,f_int) >= 0); toc = yarp::os::Time::now(); time_kdl += (toc-tic); } cout << "Total time for KDL:" << time_kdl/N_TRIALS << endl; cout << "Total time for iDyn:" << time_idyn/N_TRIALS << endl; }
/* File: main-stack.cpp * Name: Paulo Lemus * Date: 3/13/2017 */ #include <exception> #include <iostream> #include "stack-array.h" #include "stack-list.h" int main(){ // Stack objects from both implementations ee::array::stack<int> arrayStk(5); ee::list::stack<int> listStk(5); // Verify size and capacity functions are working std::cout << "arrayStk capacity: " << arrayStk.capacity() << std::endl; std::cout << "arrayStk size: " << arrayStk.size() << std::endl; std::cout << "listStk capacity: " << listStk.capacity() << std::endl; std::cout << "listStk size: " << listStk.size() << std::endl; // Completely fill both stacks arrayStk.push(1); arrayStk.push(2); arrayStk.push(3); arrayStk.push(4); arrayStk.push(5); arrayStk.push(6); listStk.push(1); listStk.push(2); listStk.push(3); listStk.push(4); listStk.push(5); listStk.push(6); // Cap and size should both be full std::cout << "arrayStk capacity: " << arrayStk.capacity() << std::endl; std::cout << "arrayStk size: " << arrayStk.size() << std::endl; std::cout << "listStk capacity: " << listStk.capacity() << std::endl; std::cout << "listStk size: " << listStk.size() << std::endl; std::cout << "Is arrayStk full? " << arrayStk.isFull() << std::endl; std::cout << "Is listStk full? " << listStk.isFull() << std::endl; // test print function, prints from base to top of stack arrayStk.print(); std::cout << std::endl; listStk.print(); std::cout << std::endl; // Pop test, throws exception if you attempt to over pop // Intended usage is to check isEmpty before popping for(int i = 0; i < arrayStk.capacity() + 1; ++i) { try { std::cout << arrayStk.pop() << std::endl; } catch(const std::runtime_error& err) { std::cout << "Error: " << err.what() << std::endl; } } for(int i = 0; i < listStk.capacity() + 1; ++i) { try { std::cout << listStk.pop() << std::endl; } catch(const std::runtime_error& err) { std::cout << "Error: " << err.what() << std::endl; } } // Check isEmpty function, should be true std::cout << "Is arrayStk empty? " << arrayStk.isEmpty() << std::endl; std::cout << "Is listStk empty? " << listStk.isEmpty() << std::endl; std::cout << "DONE!" << std::endl; ////////////////////////////////////////////////////////// // USER TESTING // ////////////////////////////////////////////////////////// ee::array::stack<int> arrayStack(10); ee::list::stack<int> listStack(10); bool running = true; bool usingArray = false; std::cout << "\n\nNote that input is UNPROTECTED, enter values correctly" << std::endl; while(running){ int select; int data; std::cout << "\n\nEnter 1 to push/enqueue an int" << std::endl; std::cout << "Enter 2 to pop/dequeue an int" << std::endl; std::cout << "Enter 3 to get size" << std::endl; std::cout << "Enter 4 to get capacity" << std::endl; std::cout << "Enter 5 to check isFull" << std::endl; std::cout << "Enter 6 to check isEmpty" << std::endl; std::cout << "Enter 7 to print" << std::endl; std::cout << "Enter 8 to switch structure" << std::endl; if(usingArray) { std::cout << "Currently editing arrayStack" << std::endl; std::cin >> select; switch(select) { case 1: std::cout << "Enter an int: "; std::cin >> data; arrayStack.push(data); break; case 2: try { arrayStack.pop(); } catch(...) { std::cout << "Caught an error" << std::endl; } break; case 3: std::cout << "Size: " << arrayStack.size() << std::endl; break; case 4: std::cout << "Capacity: " << arrayStack.capacity() << std::endl; break; case 5: std::cout << "isFull: " << arrayStack.isFull() << std::endl; break; case 6: std::cout << "isEmpty: " << arrayStack.isEmpty() << std::endl; break; case 7: arrayStack.print(); break; case 8: usingArray = !usingArray; break; default: std::cout << "Did nothing" << std::endl; break; } } else { std::cout << "Currently editing listStack" << std::endl; std::cin >> select; switch(select) { case 1: std::cout << "Enter an int: "; std::cin >> data; listStack.push(data); break; case 2: try { listStack.pop(); } catch(...) { std::cout << "Caught an error" << std::endl; } break; case 3: std::cout << "Size: " << listStack.size() << std::endl; break; case 4: std::cout << "Capacity: " << listStack.capacity() << std::endl; break; case 5: std::cout << "isFull: " << listStack.isFull() << std::endl; break; case 6: std::cout << "isEmpty: " << listStack.isEmpty() << std::endl; break; case 7: listStack.print(); break; case 8: usingArray = !usingArray; break; default: std::cout << "Did nothing" << std::endl; break; } } } return 0; }
#ifndef HELP_HAND_H_INCLUDED #define HELP_HAND_H_INCLUDED #define _USE_MATH_DEFINES #include <math.h> #include <cmath> #include <iostream> #include <complex> #include <vector> #include <string> #include <sstream> #include <ctype.h> //#include <algorithm> #define M_PI 3.14159265358979323846 using namespace std; typedef complex<double> base; const int sys = 2; //try to change those 10 below to sys and see if that works vector<int> make_float(const double& a, const int& decimals) { vector<int> res; int a_int = (int) a; double f = a - a_int; if (decimals == 0 || f == 0) {res = {0}; return res;} double pow = 0.5, x = 0; int i = 1; while (i <= decimals) { if (f == (x + pow)) {res.emplace_back(1); return res;} if (f > (x + pow)) {res.emplace_back(1); x += pow;} else res.emplace_back(0); pow *= 0.5; ++i; } return res; } int get_len(const long long& a) { int i = 1; long long b = a; while (b >= sys) { // 10 = sys b = int (floor(b / sys)); //10 = sys ++i; } return i; } void add_zeroes(vector<int>& num, int amount) { if (amount < 0) throw("\n Cannot add negative number of '0'!\n"); for (int i = 0; i < amount; ++i){num.emplace_back(0);} } void print_vector(const vector<int>& num){ cout<<"\n "; int len = num.size(); for (int i = 1; i <= len; ++i){ cout<<num[len - i]; } } vector<int> add_vectors(const vector<int>& num1, const vector<int>& num2) { int perenos = 0, curr_sum = 0, leng = 0; vector<int> shorter = num1; vector<int> longer = num2; if (shorter.size() > longer.size()) {shorter = num2; longer = num1;} int short_len = shorter.size(), long_len = longer.size(); vector<int> res_rev; res_rev.resize(0); add_zeroes(shorter, long_len - short_len); while (leng < long_len){ curr_sum = (shorter)[leng] + (longer)[leng]; res_rev.emplace_back( perenos + (curr_sum % sys) ); perenos = ( curr_sum - ( curr_sum % sys ) ) / sys; ++leng; } if (perenos == 1) {res_rev.emplace_back(1); ++leng;} return res_rev; } void split_in_two(vector<int> num, vector<int>& res1, vector<int>& res2) { if (num.size() % 2 != 0) add_zeroes(num, 2 - (num.size() % 2) ); int leng = num.size(), len = num.size() / 2, i = 0; res1 = {0}; res1.resize(0); res2 = {0}; res2.resize(0); while (i < len) { res2.emplace_back(num[i]); ++i; } while (i < leng) { res1.emplace_back(num[i]); ++i; } } vector<int>* split_in_n(vector<int> num, const int& n) { if (n < 1) throw("\n Cannot split to <1 vectors!\n"); vector<int>* reses = new vector<int>[n]; for(int i = 0; i < n; ++i) {reses[i]={0}; reses[i].resize(0);} int l = num.size(); if ( (l % n) != 0 ) add_zeroes(num, n - (l % n) ); int full_leng = num.size(), one_leng = num.size() / n, curr_glob_poss = 0; while (curr_glob_poss < full_leng) { reses[curr_glob_poss / one_leng].emplace_back(num[curr_glob_poss]); ++curr_glob_poss; } return reses; } void multiply_by_base_power(vector<int>& num, const int& n) { if (n < 0) throw("\n Negative number passed to power function!\n"); for (int i = 1; i <= n; ++i){num.emplace(num.begin(), 0);} } void make_vector(vector<int>& num, const int& n) { if (n < 0) throw("\n Negative number passed to power function!\n"); num.resize(0); if (n == 0) {num = {0}; return;} int a = n; while (a >= sys) { num.emplace_back(a % sys); a /= sys; } num.emplace_back(a); } void make_vector_base(vector<int>& num, const int& n, const int& n_base) { if (n < 0) throw("\n Negative number passed to make_vector_base function!\n"); if (n_base < 2) throw("\n Negative base! Cannot convert number!\n"); num.resize(0); if (n == 0) {num = {0}; return;} int a = n; while (a >= n_base) { num.emplace_back(a % n_base); a /= n_base; } num.emplace_back(a); } void cut_zeroes(vector<int>& num) { int l = num.size(); if (l == 0) return; while (num[l - 1] == 0) { // && l>0 num.resize(l - 1); l--; } } void cut_zeroes_back(vector<int>& num) { if (num.size() == 0) return; while (num[0] == 0 && num.size()>0) { // && l>0 num.erase(num.begin()); } } vector<int> add_zeroes_back(const vector<int>& num, const int& k) { vector<int> res = num; multiply_by_base_power(res, k); return res; } vector<int> cut_last(vector<int> num, const int& k) { if (k > num.size()) throw("\n Cannot cut more digits than vector size!\n"); if (k <= 0) throw("\n Number of digits to cut has to be a positive number!\n"); for (int i = 0; i < k; ++i){ num.erase(num.begin()); } return num; } vector<int> take_first(const vector<int>& num, const int& k) { if (k > num.size()) throw("\n Cannot take more digits than vector size!\n"); if (k <= 0) throw("\n Number of digits to take has to be a positive number!\n"); vector<int> res; int n = num.size(); for (int i = 0; i < k; ++i){ res.emplace_back(num[n-i-1]); } return res; } vector<int> take_last(const vector<int>& num, const int& k) { if (k > num.size()) throw("\n Cannot take more digits than vector size!\n"); if (k <= 0) throw("\n Number of digits to take has to be a positive number!\n"); vector<int> res; for (int i = 0; i < k; ++i){ res.emplace_back(num[i]); } return res; } vector<int> make_length(const vector<int>& num, const int& k) { if (num.size() >= k) return take_first(num, k); return add_zeroes_back(num, k - num.size()); } int get_int(const vector<int>& num) { vector<int> a = num; cut_zeroes(a); //if (a.size() > sys) throw("\n Too large number to convert!\n"); if (a.size() == 0) return 0; int r = 0, l = num.size(), b = 1; for (int i = 0; i < l; ++i) { //r += (num[i] * pow(sys, i)); r += (num[i] * b); b *= sys; } return r; } int get_int_base(const vector<int>& num, const int base) { vector<int> a = num; cut_zeroes(a); //if (a.size() > base) throw("\n Too large number to convert!\n"); if (a.size() == 0) return 0; int r = 0, l = num.size(), b = 1; for (int i = 0; i < l; ++i) { //r += (num[i] * pow(sys, i)); r += (num[i] * b); b *= base; } return r; } void make_equal_sizes(vector<int>& n1, vector<int>& n2) { int longer = n1.size(); if (longer < n2.size()) longer = n2.size(); add_zeroes(n1, longer - n1.size()); add_zeroes(n2, longer - n2.size()); } void make_equal_sizes_back(vector<int>& n1, vector<int>& n2) { int longer = n1.size(); if (longer < n2.size()) longer = n2.size(); multiply_by_base_power(n1, longer - n1.size()); multiply_by_base_power(n2, longer - n2.size()); } vector<int> merge_i_and_f(const vector<int>& i, const vector<int>& f) { vector<int> num; int k = 0, l_i = i.size(), l_f = f.size(); while (k < l_f) { num.emplace_back(f[k]); ++k; } k = 0; while (k < l_i) { num.emplace_back(i[k]); ++k; } return num; } int compare_vectors(const vector<int>& num1, const vector<int>& num2) { vector<int> n1 = num1, n2 = num2; cut_zeroes(n1); cut_zeroes(n2); if (n1.size() > n2.size()) return 1; if (n2.size() > n1.size()) return -1; { int i = n1.size() - 1; while(n1[i] == n2[i] && i >= 0) {--i;} if (i == -1) return 0; if (n1[i] > n2[i]) return 1; if (n2[i] > n1[i]) return -1; } return 0; } vector<int> subtract__vectors(const vector<int>& num1, const vector<int>& num2) { if (compare_vectors(num1, num2) == -1) throw("\n Cannot subtract vectors!\n"); int perenos = 0, curr_sum = 0, leng = 0; vector<int> bigger = num1, smaller = num2; int big_len = bigger.size(), smal_len = smaller.size(); vector<int> res_rev; res_rev.resize(0); add_zeroes(smaller, big_len - smal_len); while (leng < big_len){ curr_sum = (bigger)[leng] - (smaller)[leng] + perenos; if (curr_sum < 0) {curr_sum += sys; perenos = -1;} else perenos = 0; while (curr_sum < 0) {curr_sum += sys; perenos--;} //sys = 10 res_rev.emplace_back(curr_sum % sys);// sys = 10 //if (res_rev[leng] != 0) real_leng = leng; //perenos = ( curr_sum - ( curr_sum % sys ) ) / sys; ++leng; } //if (perenos < 0) res_rev.emplace_back(perenos); return res_rev; } vector<int> divide_vectors(vector<int> a, const vector<int>& b) // returns int (a / b) { vector<int> one{1}, counter{0}, b0 = b; cut_zeroes(a); cut_zeroes(b0); if (b0.size() == 0) throw("\n Division by zero vector! \n"); if (a.size() == 0) return counter; while (compare_vectors(a, b0) == 1) { a = subtract__vectors(a, b0); counter = add_vectors(counter, one); } if (compare_vectors(a, b0) == -1) return counter; counter = add_vectors(counter, one); return counter; } vector<int> get_modulo(vector<int> a, const vector<int>& b) // returns a mod b = a % b { vector<int> b0 = b; cut_zeroes(a); cut_zeroes(b0); if (b0.size() == 0) throw("\n Division by zero vector! \n"); if (a.size() == 0) {a.emplace_back(0); return a;} while (compare_vectors(a, b0) == 1) { a = subtract__vectors(a, b0); } return a; } vector<int> get_modulo_int(vector<int> a, const int& b) // returns a mod b = a % b { vector<int> b0; make_vector(b0, b); cut_zeroes(a); cut_zeroes(b0); if (b0.size() == 0) throw("\n Division by zero vector! \n"); if (a.size() == 0) {a.emplace_back(0); return a;} while (compare_vectors(a, b0) == 1) { a = subtract__vectors(a, b0); } return a; } bool get_mod_two(const vector<int>& a) { if (a.size() == 0) return true; return ((a[0] * sys) % 2); } void increase_by_one(vector<int>& a) { vector<int> one{1}; if (a.size() == 0) a = one; else a = add_vectors(a, one); } vector<int> multiply_by_digit(vector<int> a, const int& k) { vector<int> res{0}; if (a.size() == 0 || k == 0) {return res;} if (k == 1) return a; if (k >= (sys-1) || k < 0) throw("\n Not a digit passed!\n"); // 9 = 10 - 1 = sys -1 as k < sys res.resize(0); int len = a.size(), i = 0, b = 0; while (i < len) { b += a[i] * k; res.emplace_back(b % sys); b = (b - res[i]) / sys; ++i; } if (b != 0) res.emplace_back(b); return res; } vector<int> GCD(vector<int> a, vector<int> b) { if (b.size() == 0) return a; else return GCD(b, get_modulo(a, b)); } /* vector<base> fft(const vector<base> & num, bool invert) // returns values of (n-1)-degree polynomial in n points of (-1)^(1/n) { vector<base> a = num; int n = (int) a.size(); if (n == 1) return a; vector<base> a0 (n/2), a1 (n/2); for (int i=0, j=0; i<n; i+=2, ++j) { a0[j] = a[i]; a1[j] = a[i+1]; } fft (a0, invert); fft (a1, invert); double ang = 2 * M_PI / n * (invert ? -1 : 1); base w (1), wn (cos(ang), sin(ang)); for (int i=0; i<n/2; ++i) { a[i] = a0[i] + w * a1[i]; a[i+n/2] = a0[i] - w * a1[i]; if (invert) a[i] /= 2, a[i+n/2] /= 2; w *= wn; } return a; } */ // void fft (vector<complex<double>> &a, bool invert) {/// вместо >> был какой-то символ int n = (int) a.size(); if (n == 1) return; vector<complex<double>> a0 (n/2), a1 (n/2);///тут тоже for (int i=0, j=0; i<n; i+=2, ++j) { a0[j] = a[i]; a1[j] = a[i+1]; } fft (a0, invert); fft (a1, invert); double ang = 2*M_PI/n * (invert ? -1 : 1); complex<double> w (1), wn (cos(ang), sin(ang)); for (int i=0; i<n/2; ++i) { a[i] = a0[i] + w * a1[i]; a[i+n/2] = a0[i] - w * a1[i]; if (invert) a[i] /= 2, a[i+n/2] /= 2; w *= wn; } } // #endif // HELP_HAND_H_INCLUDED
/**************************************************************************** * * * Project64 - A Nintendo 64 emulator. * * http://www.pj64-emu.com/ * * Copyright (C) 2012 Project64. All rights reserved. * * * * License: * * GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html * * * ****************************************************************************/ #include "stdafx.h" #include <io.h> #include "PluginList.h" #include <Project64-core/Plugins/PluginBase.h> CPluginList::CPluginList(bool bAutoFill /* = true */) : m_PluginDir(g_Settings->LoadStringVal(Directory_Plugin), "") { if (bAutoFill) { LoadList(); } } CPluginList::~CPluginList() { } int CPluginList::GetPluginCount() const { return m_PluginList.size(); } const CPluginList::PLUGIN * CPluginList::GetPluginInfo(int indx) const { if (indx < 0 || indx >= (int)m_PluginList.size()) { return NULL; } return &m_PluginList[indx]; } bool CPluginList::LoadList() { WriteTrace(TraceUserInterface, TraceDebug, "Start"); m_PluginList.clear(); AddPluginFromDir(m_PluginDir); WriteTrace(TraceUserInterface, TraceDebug, "Done"); return true; } void CPluginList::AddPluginFromDir(CPath Dir) { Dir.SetNameExtension("*.*"); if (Dir.FindFirst(_A_SUBDIR)) { do { AddPluginFromDir(Dir); } while (Dir.FindNext()); Dir.UpDirectory(); } Dir.SetNameExtension("*.dll"); if (Dir.FindFirst()) { HMODULE hLib = NULL; do { if (hLib) { FreeLibrary(hLib); hLib = NULL; } //UINT LastErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS ); WriteTrace(TraceUserInterface, TraceDebug, "loading %s", (LPCSTR)Dir); hLib = LoadLibrary(Dir); //SetErrorMode(LastErrorMode); if (hLib == NULL) { DWORD LoadError = GetLastError(); WriteTrace(TraceUserInterface, TraceDebug, "failed to loadi %s (error: %d)", (LPCSTR)Dir, LoadError); continue; } void(CALL *GetDllInfo) (PLUGIN_INFO * PluginInfo); GetDllInfo = (void(CALL *)(PLUGIN_INFO *))GetProcAddress(hLib, "GetDllInfo"); if (GetDllInfo == NULL) { continue; } PLUGIN Plugin = { 0 }; Plugin.Info.MemoryBswaped = true; GetDllInfo(&Plugin.Info); if (!CPlugin::ValidPluginVersion(Plugin.Info)) { continue; } Plugin.FullPath = Dir; Plugin.FileName = stdstr((const char *)Dir).substr(strlen(m_PluginDir)); if (GetProcAddress(hLib, "DllAbout") != NULL) { Plugin.AboutFunction = true; } m_PluginList.push_back(Plugin); } while (Dir.FindNext()); if (hLib) { FreeLibrary(hLib); hLib = NULL; } } }
#ifdef HAS_VTK /////////////////////////////////////////////////////////////// #include <vtkPoints.h> #include <vtkFloatArray.h> #include <vtkCellArray.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkRegularPolygonSource.h> #include <vtkCubeSource.h> #include <vtkSphereSource.h> #include <vtkStructuredPoints.h> #include <vtkRectilinearGrid.h> #include <vtkRectilinearGridWriter.h> #include <vtkPolyDataWriter.h> #include <vtkCleanPolyData.h> #include <vtkGlyph3D.h> #include <irtkImage.h> #include <irtkTransformation.h> char *input_name = NULL, *output_name = NULL; char *dof_name = NULL; void usage(){ cout << "" << endl; cout << "" << endl; cout << "" << endl; cout << "" << endl; exit(1); } int main(int argc, char **argv){ // int nPts; int i, j, k, count; bool ok; double p[3]; // double xaxis[3], yaxis[3], zaxis[3]; // double r; int xlast, ylast, zlast; int xdim, ydim, zdim; // double coord, tmp; input_name = argv[1]; argv++; argc--; output_name = argv[1]; argv++; argc--; while (argc > 1){ ok = false; if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)){ argc--; argv++; dof_name = argv[1]; argc--; argv++; ok = true; } if (ok == false){ cerr << "Can not parse argument " << argv[1] << endl; usage(); } } irtkTransformation *transformation; if (dof_name != NULL){ // Read transformation transformation = irtkTransformation::New(dof_name); } else { // Create identity transformation transformation = new irtkRigidTransformation; } // Read image irtkGreyImage image; image.Read(input_name); xdim = image.GetX(); ydim = image.GetY(); zdim = image.GetZ(); ///////////////////////////////////////// vtkPoints *points = vtkPoints::New(); // vtkFloatArray *scalars = vtkFloatArray::New(); vtkPolyData *output = vtkPolyData::New(); output->Allocate(); xlast = xdim - 1; ylast = ydim - 1; zlast = zdim - 1; int xindices[4] = {0, 1, xlast - 1, xlast}; int yindices[4] = {0, 1, ylast - 1, ylast}; int zindices[4] = {0, 1, zlast - 1, zlast}; count = 0; for (i = 0; i < xdim; i++){ for (j = 0; j < 4; j++){ for (k = 0; k <4; k++){ p[0] = i; p[1] = yindices[j]; p[2] = zindices[k]; image.ImageToWorld(p[0], p[1], p[2]); transformation->Transform(p[0], p[1], p[2]); points->InsertPoint(count, p); ++count; } } } for (k = 0; k < zdim; k++){ for (i = 0; i < 4; i++){ for (j = 0; j <4; j++){ p[0] = xindices[i]; p[1] = yindices[j]; p[2] = k; image.ImageToWorld(p[0], p[1], p[2]); transformation->Transform(p[0], p[1], p[2]); points->InsertPoint(count, p); ++count; } } } for (j = 0; j < ydim; j++){ for (i = 0; i < 4; i++){ for (k = 0; k < 4; k++){ p[0] = xindices[i]; p[1] = j; p[2] = zindices[k]; image.ImageToWorld(p[0], p[1], p[2]); transformation->Transform(p[0], p[1], p[2]); points->InsertPoint(count, p); ++count; } } } output->SetPoints(points); // output->GetPointData()->AddArray(scalars); output->Modified(); vtkRegularPolygonSource *polygon = vtkRegularPolygonSource::New(); polygon->SetNumberOfSides(3); polygon->SetRadius(0.3); polygon->SetNormal(1, 1, 1); // vtkCubeSource *cube = vtkCubeSource::New(); // r= 0.4; // cube->SetBounds(-1*r, r, -1*r, r, -1*r, r); // vtkSphereSource *sphere = vtkSphereSource::New(); // sphere->SetRadius(1); vtkGlyph3D *glyphs = vtkGlyph3D::New(); glyphs->SetSourceData(polygon->GetOutput()); // glyphs->SetSource(cube->GetOutput()); // glyphs->SetSource(sphere->GetOutput()); glyphs->SetInputData(output); glyphs->ScalingOff(); vtkCleanPolyData *cleaner = vtkCleanPolyData::New(); cleaner->SetInputData(glyphs->GetOutput()); cleaner->Modified(); vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInputData(cleaner->GetOutput()); writer->SetFileName(output_name); writer->Write(); // ////////////////////////////////////////////// // vtkFloatArray *xcoords = vtkFloatArray::New(); // vtkFloatArray *ycoords = vtkFloatArray::New(); // vtkFloatArray *zcoords = vtkFloatArray::New(); // for (i = 0; i < xdim; ++i){ // coord = i; // tmp = 0; // image.ImageToWorld(coord, tmp, tmp); // xcoords->InsertNextValue(coord); // } // for (i = 0; i < ydim; ++i){ // coord = i; // tmp = 0; // image.ImageToWorld(tmp, coord, tmp); // ycoords->InsertNextValue(coord); // } // for (i = 0; i < zdim; ++i){ // coord = i; // tmp = 0; // image.ImageToWorld(tmp, tmp, coord); // zcoords->InsertNextValue(coord); // } // vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New(); // rgrid->SetDimensions(xdim, ydim, zdim); // rgrid->SetXCoordinates(xcoords); // rgrid->SetYCoordinates(ycoords); // rgrid->SetZCoordinates(zcoords); // vtkRectilinearGridWriter *rgridWriter = vtkRectilinearGridWriter::New(); // rgridWriter->SetInputData(rgrid); // rgridWriter->SetFileName(output_name); // rgridWriter->Write(); // exit(0); // /////////////////////////////////////////// // irtkGreyImage dummy(image); // vtkStructuredPoints *vtkImage = vtkStructuredPoints::New(); // xaxis[0] = 1; xaxis[1] = 0; xaxis[2] = 0; // yaxis[0] = 0; yaxis[1] = 1; yaxis[2] = 0; // zaxis[0] = 0; zaxis[1] = 0; zaxis[2] = 1; // dummy.PutPixelSize(1, 1, 1); // dummy.PutOrigin(0, 0, 0); // dummy.PutOrientation(xaxis, yaxis, zaxis); // dummy.ImageToVTK(vtkImage); } #else #include <irtkImage.h> int main( int argc, char *argv[] ){ cerr << argv[0] << " needs to be compiled with the VTK library " << endl; } #endif
#include <bits/stdc++.h> #include <iostream> #include <conio.h> using namespace std; int main(){ FILE *out; out = fopen("B.out","a"); int t; cin>>t; for(int aa=0;aa<t;aa++){ fprintf(out, "Case #%d: ", aa+1); cout<<"Case #"<<aa+1<<": "; long long n, head=1; int b, tmp=1, imin=100000; cin>>b>>n; int m[b], t[b], last=1; for(int i=0;i<b;i++){ cin>>m[i]; t[b] = m[i]; if(imin>m[i]) imin = m[i]; } while(tmp==1){ while(last==1){ for(int i=0;i<b;i++){ if(t[i]==m[i]){ if(i==b-1) last=0; if(head==n){ cout<<i+1<<endl; fprintf(out, "%d\n", i+1); tmp=0; i=b; last=0; break; break; break; } else head++; } } } if(tmp == 1){ last = 1; for(int k=0;k<b;k++){ if(t[k]!=m[k]) t[k]++; else t[k]=0; } } } } return 0; }
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef SACPP_CPPW_SpawnButtonArea_generated_h #error "CPPW_SpawnButtonArea.generated.h already included, missing '#pragma once' in CPPW_SpawnButtonArea.h" #endif #define SACPP_CPPW_SpawnButtonArea_generated_h #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_11_DELEGATE \ static inline void FTouchDelegate_DelegateWrapper(const FMulticastScriptDelegate& TouchDelegate) \ { \ TouchDelegate.ProcessMulticastDelegate<UObject>(NULL); \ } #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_SPARSE_DATA #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_RPC_WRAPPERS #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_RPC_WRAPPERS_NO_PURE_DECLS #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUCPPW_SpawnButtonArea(); \ friend struct Z_Construct_UClass_UCPPW_SpawnButtonArea_Statics; \ public: \ DECLARE_CLASS(UCPPW_SpawnButtonArea, UUserWidget, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/SACPP"), NO_API) \ DECLARE_SERIALIZER(UCPPW_SpawnButtonArea) #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_INCLASS \ private: \ static void StaticRegisterNativesUCPPW_SpawnButtonArea(); \ friend struct Z_Construct_UClass_UCPPW_SpawnButtonArea_Statics; \ public: \ DECLARE_CLASS(UCPPW_SpawnButtonArea, UUserWidget, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/SACPP"), NO_API) \ DECLARE_SERIALIZER(UCPPW_SpawnButtonArea) #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UCPPW_SpawnButtonArea(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCPPW_SpawnButtonArea) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UCPPW_SpawnButtonArea); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCPPW_SpawnButtonArea); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UCPPW_SpawnButtonArea(UCPPW_SpawnButtonArea&&); \ NO_API UCPPW_SpawnButtonArea(const UCPPW_SpawnButtonArea&); \ public: #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UCPPW_SpawnButtonArea(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UCPPW_SpawnButtonArea(UCPPW_SpawnButtonArea&&); \ NO_API UCPPW_SpawnButtonArea(const UCPPW_SpawnButtonArea&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UCPPW_SpawnButtonArea); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCPPW_SpawnButtonArea); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCPPW_SpawnButtonArea) #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_PRIVATE_PROPERTY_OFFSET #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_13_PROLOG #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_PRIVATE_PROPERTY_OFFSET \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_SPARSE_DATA \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_RPC_WRAPPERS \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_INCLASS \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_PRIVATE_PROPERTY_OFFSET \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_SPARSE_DATA \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_RPC_WRAPPERS_NO_PURE_DECLS \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_INCLASS_NO_PURE_DECLS \ PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h_16_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> SACPP_API UClass* StaticClass<class UCPPW_SpawnButtonArea>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID PluginExporter_4_25_Plugins_SACPP_Source_SACPP_Public_CPPW_SpawnButtonArea_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
// Sandro Sobczynski, Maciej Leciejewski #include <iostream> using namespace std; int main() { int number; cout << "Enter the number: "; cin >> number; int *pointerToNumber; pointerToNumber = &number; cout << "Number is: " << number << " Pointer: " << pointerToNumber << endl; }
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ // ChooseColorStatic.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "ChooseColorStatic.h" #include "ChooseColorDialog.h" #include "format.h" #include "PicCommands.h" // CChooseColorStatic IMPLEMENT_DYNAMIC(CChooseColorStatic, CStatic) CChooseColorStatic::CChooseColorStatic() { _bHoverIndex = INVALID_COLORINDEX; _cRows = 0; _cColumns = 0; _fPrintIndex = FALSE; _fShowSelection = FALSE; _bSelectedColorIndex = 0; _bAuxSelectedColorIndex = 0; _fShowAuxSel = FALSE; memset(_pPalette, 0, sizeof(_pPalette)); _fShowIndices = FALSE; _fSelectionNumbers = FALSE; _autoHandleSelection = false; _allowMultipleSelection = false; _focusIndex = INVALID_COLORINDEX; _showUnused = false; _showHover = true; _showActualUsedColors = false; _showSelectionBoxes = false; _showTransparent = false; _transparentIndex = 0; } CChooseColorStatic::~CChooseColorStatic() { } BEGIN_MESSAGE_MAP(CChooseColorStatic, CStatic) ON_WM_DRAWITEM_REFLECT() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_MOUSEMOVE() END_MESSAGE_MAP() void CChooseColorStatic::SetSelection(BYTE bIndex) { _bSelectedColorIndex = bIndex; std::fill(_multipleSelection, _multipleSelection + ARRAYSIZE(_multipleSelection), false); _multipleSelection[_bSelectedColorIndex] = true; if (m_hWnd) { Invalidate(FALSE); } } int CChooseColorStatic::GetColorCount() { return _cRows * _cColumns; } void CChooseColorStatic::SetTransparentIndex(uint8_t transparent) { if (_transparentIndex != transparent) { _transparentIndex = transparent; if (m_hWnd) { Invalidate(FALSE); } } _showTransparent = true; } void CChooseColorStatic::SetAuxSelection(BYTE bIndex) { _bAuxSelectedColorIndex = bIndex; _fShowAuxSel = TRUE; if (m_hWnd) { Invalidate(FALSE); } } void CChooseColorStatic::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { RECT rcClient; GetClientRect(&rcClient); CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC); if (pDC) { CDC dcMem; if (dcMem.CreateCompatibleDC(pDC)) { CBitmap bitmap; bitmap.CreateCompatibleBitmap(pDC, RECTWIDTH(rcClient), RECTHEIGHT(rcClient)); if (dcMem.SelectObject(&bitmap)) { // Now hand this memory DC off to the real drawing function. _DrawItem(&dcMem, RECTWIDTH(rcClient), RECTHEIGHT(rcClient)); // Now blt back // Now we want to copy it back to the real dc. pDC->BitBlt(0, 0, RECTWIDTH(rcClient), RECTHEIGHT(rcClient), &dcMem, 0, 0, SRCCOPY); } } } } void CChooseColorStatic::SetActualUsedColors(bool *actualUsedColors) { _showActualUsedColors = true; memcpy(_actualUsedColors, actualUsedColors, sizeof(bool) * (_cRows * _cColumns)); Invalidate(FALSE); } void CChooseColorStatic::SetPalette(int cRows, int cColumns, const EGACOLOR *pPalette, int paletteColorCount, const RGBQUAD *pPaletteColors, bool dithered) { _cRows = cRows; _cColumns = cColumns; _paletteSquareInset = (max(_cRows, _cColumns) <= 4) ? 2 : 0; if (pPalette != nullptr) { // Sometimes clients dont' need this (e.g. pen style) int count = _cRows * _cColumns; // Make a copy of the palette, since we cache this and it could go away. memcpy(_pPalette, pPalette, sizeof(*pPalette) * count); memcpy(_pPaletteColors, pPaletteColors, sizeof(*pPaletteColors) * paletteColorCount); } _dithered = dithered; } // CChooseColorStatic message handlers void CChooseColorStatic::_DrawItem(CDC *pDC, int cx, int cy) { // Call CExtLabel's background, which will paint the gradient (or whatever) background //OnEraseBackground(*pDC, CRect(0, 0, cx, cy)); pDC->FillSolidRect(0, 0, cx, cy, g_PaintManager->GetColor(COLOR_BTNFACE)); if (_pPalette) { _DrawSelection(pDC); // Divide things up into _cRows rows and _cColumms columns. int iPaletteIndex = 0; for (iPaletteIndex = 0; iPaletteIndex < (_cRows * _cColumns); iPaletteIndex++) { assert(iPaletteIndex < 256); // Since we cast to a BYTE // We use an int for this loop, because there could be up to 256 colors in this static. RECT rectSquare; _MapIndexToRect((BYTE)iPaletteIndex, &rectSquare); // Is this the current selected one? Highlight it. // Figure out the right color - do color 1 for now. RGBQUAD color1; RGBQUAD color2; if (_dithered) { EGACOLOR egaColor = _pPalette[iPaletteIndex]; color1 = EGA_TO_RGBQUAD(egaColor.color1); color2 = EGA_TO_RGBQUAD(egaColor.color2); CBitmap bm; if (CreateDCCompatiblePattern(color1, color2, 4, 4, pDC, &bm)) { CBrush brushPat; if (brushPat.CreatePatternBrush(&bm)) { pDC->FillRect(&rectSquare, &brushPat); } } } else { uint8_t colorIndex = _pPalette[iPaletteIndex].ToByte(); color1 = _pPaletteColors[colorIndex]; color2 = _pPaletteColors[colorIndex]; CBrush brushPat(RGB(color1.rgbRed, color1.rgbGreen, color1.rgbBlue)); pDC->FillRect(&rectSquare, &brushPat); } _DrawIndex(pDC, (BYTE)iPaletteIndex); if (_fSelectionNumbers && (!_fShowAuxSel || (_bSelectedColorIndex != _bAuxSelectedColorIndex))) { // Only show selection numbers when we're not showing auxiliary selection, or when we // are, and the two selections are different. _DrawTextAtIndex(pDC, _bSelectedColorIndex, TEXT("A")); if (_fShowAuxSel) { _DrawTextAtIndex(pDC, _bAuxSelectedColorIndex, TEXT("B")); } } } _DrawUnused(pDC); _DrawActualUsedColors(pDC); _Draw0x3Colors(pDC); _DrawMultiSelection(pDC); if (_showSelectionBoxes) { RECT rectHover; _MapIndexToRect((uint8_t)_bSelectedColorIndex, &rectHover); // Draw a box pDC->DrawFocusRect(&rectHover); // make it a little bigger. InflateRect(&rectHover, 1, 1); pDC->DrawFocusRect(&rectHover); if (_fShowAuxSel) { // Draw a thinner one for the aux selection. _MapIndexToRect((uint8_t)_bAuxSelectedColorIndex, &rectHover); pDC->DrawFocusRect(&rectHover); } } if (_showTransparent) { _DrawTextAtIndex(pDC, _transparentIndex, TEXT("T")); } _DrawHover(pDC); } } void CChooseColorStatic::_DrawHover(CDC *pDC) { // Draw the hovered box. if (_showHover && (_bHoverIndex != (uint16_t)INVALID_COLORINDEX)) { RECT rectHover; _MapIndexToRect((uint8_t)_bHoverIndex, &rectHover); // Draw a box pDC->DrawFocusRect(&rectHover); // make it a little bigger. InflateRect(&rectHover, 1, 1); pDC->DrawFocusRect(&rectHover); } } void CChooseColorStatic::_DrawSelection(CDC *pDC) { if (_fShowSelection) { for (int i = 0; i < (_fShowAuxSel ? 2 : 1); i++) { BYTE bSelectedIndex = (i == 0) ? _bSelectedColorIndex : _bAuxSelectedColorIndex; RECT rectSquare; _MapIndexToRect(bSelectedIndex, &rectSquare); RECT rectHighlight = rectSquare; InflateRect(&rectHighlight, 2, 2); CBrush brushSolid; brushSolid.CreateSolidBrush(RGB(0, 0, 0)); pDC->FillRect(&rectHighlight, &brushSolid); InflateRect(&rectHighlight, -1, -1); CBrush brushSolidWhite; brushSolidWhite.CreateSolidBrush(RGB(255, 255, 255)); pDC->FillRect(&rectHighlight, &brushSolidWhite); } } } void CChooseColorStatic::_DrawUnused(CDC *pDC) { if (_showUnused) { std::vector<CPoint> points; std::vector<DWORD> pointCounts; points.reserve(200); pointCounts.reserve(100); for (int y = 0; y < _cRows; y++) { for (int x = 0; x < _cColumns; x++) { int index = x + (y * _cColumns); if (_pPaletteColors[index].rgbReserved == 0x0) { CRect rect; _MapIndexToRect((uint8_t)index, &rect); InflateRect(&rect, -2, -2); points.emplace_back(rect.left, rect.top); points.emplace_back(rect.right, rect.bottom); points.emplace_back(rect.right - 1, rect.top); points.emplace_back(rect.left - 1, rect.bottom); pointCounts.push_back(2); pointCounts.push_back(2); } } } if (!points.empty()) { CPen pen(PS_SOLID, 1, RGB(16, 16, 16)); HGDIOBJ hOld = pDC->SelectObject(pen); pDC->PolyPolyline(&points[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(hOld); } } } // Draw an underline under these colors void CChooseColorStatic::_Draw0x3Colors(CDC *pDC) { std::vector<CPoint> points; std::vector<DWORD> pointCounts; points.reserve(200); pointCounts.reserve(100); for (int y = 0; y < _cRows; y++) { for (int x = 0; x < _cColumns; x++) { int index = x + (y * _cColumns); if (_pPaletteColors[index].rgbReserved == 0x3) { CRect rect; _MapIndexToRect((uint8_t)index, &rect); points.emplace_back(rect.left, rect.bottom - 1); points.emplace_back(rect.right,rect.bottom - 1); pointCounts.push_back(2); } } } if (!points.empty()) { CPen pen(PS_SOLID, 1, RGB(0, 0, 64)); HGDIOBJ hOld = pDC->SelectObject(pen); pDC->PolyPolyline(&points[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(hOld); } } void CChooseColorStatic::_DrawActualUsedColors(CDC *pDC) { if (_showActualUsedColors) { std::vector<CPoint> points; std::vector<DWORD> pointCounts; points.reserve(200); pointCounts.reserve(100); for (int y = 0; y < _cRows; y++) { for (int x = 0; x < _cColumns; x++) { int index = x + (y * _cColumns); if (_actualUsedColors[index]) { CRect rect; _MapIndexToRect((uint8_t)index, &rect); CPoint center = rect.CenterPoint(); points.emplace_back(center.x, center.y); points.emplace_back(center.x + 1, center.y); pointCounts.push_back(2); } } } if (!points.empty()) { CPen pen(PS_SOLID, 1, RGB(240, 240, 240)); HGDIOBJ hOld = pDC->SelectObject(pen); pDC->PolyPolyline(&points[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(hOld); } if (!points.empty()) { // Offset by a pixel and draw a dark dot so this shows up even on light colors. for (CPoint &point : points) { point.y++; } CPen pen(PS_SOLID, 1, RGB(20, 20, 20)); HGDIOBJ hOld = pDC->SelectObject(pen); pDC->PolyPolyline(&points[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(hOld); } } } void CChooseColorStatic::_DrawMultiSelection(CDC *pDC) { if (_fShowSelection) { std::vector<CPoint> outerPoints; std::vector<CPoint> innerPoints; std::vector<DWORD> pointCounts; outerPoints.reserve(200); innerPoints.reserve(200); pointCounts.reserve(100); for (int y = 0; y < _cRows; y++) { for (int x = 0; x < _cColumns; x++) { bool aboveSelected = (y > 0) ? (_multipleSelection[x + (y - 1) * _cColumns]) : false; bool belowSelected = (y < (_cRows - 1)) ? (_multipleSelection[x + (y + 1) * _cColumns]) : false; bool leftSelected = (x > 0) ? (_multipleSelection[x - 1 + y * _cColumns]) : false; bool rightSelected = (x < (_cColumns - 1)) ? (_multipleSelection[x + 1 + y * _cColumns]) : false; int index = x + (y * _cColumns); if (_multipleSelection[index]) { CRect rect; _MapIndexToRect((uint8_t)index, &rect); InflateRect(&rect, 1, 1); if (!aboveSelected) { outerPoints.emplace_back(rect.left, rect.top); outerPoints.emplace_back(rect.right, rect.top); innerPoints.emplace_back(rect.left + 1, rect.top + 1); innerPoints.emplace_back(rect.right - 1, rect.top + 1); pointCounts.push_back(2); } if (!belowSelected) { outerPoints.emplace_back(rect.left, rect.bottom - 1); outerPoints.emplace_back(rect.right, rect.bottom - 1); innerPoints.emplace_back(rect.left + 1, rect.bottom - 2); innerPoints.emplace_back(rect.right - 1, rect.bottom - 2); pointCounts.push_back(2); } if (!leftSelected) { outerPoints.emplace_back(rect.left, rect.top); outerPoints.emplace_back(rect.left, rect.bottom); innerPoints.emplace_back(rect.left + 1, rect.top + 1); innerPoints.emplace_back(rect.left + 1, rect.bottom - 1); pointCounts.push_back(2); } if (!rightSelected) { outerPoints.emplace_back(rect.right - 1, rect.top); outerPoints.emplace_back(rect.right - 1, rect.bottom); innerPoints.emplace_back(rect.right - 2, rect.top + 1); innerPoints.emplace_back(rect.right - 2, rect.bottom - 1); pointCounts.push_back(2); } } } } if (!outerPoints.empty()) { CPen penBlack(PS_SOLID, 1, RGB(0, 0, 0)); CPen penWhite(PS_SOLID, 1, RGB(255, 255, 255)); HGDIOBJ hOld = pDC->SelectObject(penBlack); pDC->PolyPolyline(&outerPoints[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(penWhite); pDC->PolyPolyline(&innerPoints[0], &pointCounts[0], (int)pointCounts.size()); pDC->SelectObject(hOld); } } } COLORREF _GetGoodTextColor(RGBQUAD color) { DWORD dwAvg = ((DWORD)color.rgbBlue) + ((DWORD)color.rgbGreen) + ((DWORD)color.rgbRed); dwAvg /= 3; if (dwAvg < 170) { return RGB(220, 255, 220); } else { return RGB(110, 128, 110); } } // // Draw a number in this square // void CChooseColorStatic::_DrawIndex(CDC *pDC, BYTE bIndex) { if (_fShowIndices) { TCHAR szBuf[3]; StringCchPrintf(szBuf, ARRAYSIZE(szBuf), TEXT("%02d"), bIndex); _DrawTextAtIndex(pDC, bIndex, szBuf); } } void CChooseColorStatic::_DrawTextAtIndex(CDC *pDC, BYTE bIndex, PCTSTR psz) { RECT rectSquare; _MapIndexToRect(bIndex, &rectSquare); int iBkMode = pDC->SetBkMode(TRANSPARENT); // Note: we're just using color1 for sampling here. Currently the "drawindex" // feature is only used for non-dithered colours (e.g. priority and control) COLORREF colorOld = pDC->SetTextColor(_GetGoodTextColor(EGA_TO_RGBQUAD(_pPalette[bIndex].color1))); pDC->DrawText(psz, -1, &rectSquare, DT_SINGLELINE | DT_CENTER | DT_VCENTER); pDC->SetBkMode(iBkMode); pDC->SetTextColor(colorOld); } // // Returns a number between 0 and ((_cRows * _cColumns) - 1), or INVALID_COLORINDEX // if the point did not lie on a square. // int CChooseColorStatic::_MapPointToIndex(CPoint point) { int bRet = INVALID_COLORINDEX; RECT rc; GetClientRect(&rc); // Adjust a bit. InflateRect(&rc, -_paletteSquareInset, -_paletteSquareInset); if ((_cColumns > 0) && (_cRows > 0)) { int cxSquare = RECTWIDTH(rc) / _cColumns; int cySquare = RECTHEIGHT(rc) / _cRows; int x = point.x - _paletteSquareInset; int y = point.y - _paletteSquareInset; int iColumn = x / cxSquare; int iRow = y / cySquare; if ((iColumn < _cColumns) && (iRow < _cRows)) { bRet = ((iRow * _cColumns) + iColumn); } } return bRet; } void CChooseColorStatic::_MapRowColToRect(int iRow, int iColumn, RECT *prcOut) { RECT rc; GetClientRect(&rc); InflateRect(&rc, -_paletteSquareInset, -_paletteSquareInset); // Adjust a bit. int cxSquare = RECTWIDTH(rc) / _cColumns; int cySquare = RECTHEIGHT(rc) / _cRows; prcOut->left = iColumn * cxSquare + _paletteSquareInset; prcOut->top = iRow * cySquare + _paletteSquareInset; prcOut->right = (iColumn + 1) * cxSquare; prcOut->bottom = (iRow + 1) * cySquare; } void CChooseColorStatic::_MapIndexToRect(BYTE bIndex, RECT *prc) { if (bIndex < (_cColumns * _cRows)) { int iRow = bIndex / _cColumns; int iColumn = bIndex % _cColumns; _MapRowColToRect(iRow, iColumn, prc); } else { // make it zero ZeroMemory(prc, sizeof(*prc)); } } void CChooseColorStatic::_OnButtonDown(UINT nFlags, CPoint point, BOOL fLeft) { int colorIndex = _MapPointToIndex(point); if (_autoHandleSelection) { if (fLeft && (colorIndex != INVALID_COLORINDEX)) { if (_allowMultipleSelection) { _bSelectedColorIndex = (uint8_t)colorIndex; // Temporary bool control = !!(nFlags & MK_CONTROL); bool shift = !!(nFlags & MK_SHIFT); if (control) { // Toggle. if (!shift) { _multipleSelection[colorIndex] = !_multipleSelection[colorIndex]; } } else { // Clear all memset(_multipleSelection, 0, sizeof(bool) * (_cRows * _cColumns)); } if (shift && (_focusIndex != INVALID_COLORINDEX)) { // Select the range from _focusIndex to colorIndex for (int i = min(_focusIndex, colorIndex); i <= max(_focusIndex, colorIndex); i++) { _multipleSelection[i] = true; } } else if (!control) { _multipleSelection[colorIndex] = true; } if (!shift) { _focusIndex = colorIndex; } } else { SetSelection((uint8_t)colorIndex); } Invalidate(FALSE); } } if (_pCallback) { if (colorIndex != INVALID_COLORINDEX) { _pCallback->OnColorClick((uint8_t)colorIndex, this->GetDlgCtrlID(), fLeft); } } } void CChooseColorStatic::OnLButtonDown(UINT nFlags, CPoint point) { _OnButtonDown(nFlags, point, TRUE); } void CChooseColorStatic::OnRButtonDown(UINT nFlags, CPoint point) { _OnButtonDown(nFlags, point, FALSE); } void CChooseColorStatic::OnMouseMove(UINT nFlags, CPoint point) { int bHoverIndex = _MapPointToIndex(point); if ((uint16_t)bHoverIndex != _bHoverIndex) { _bHoverIndex = bHoverIndex; if (_pCallback) { _pCallback->OnColorHover((uint8_t)_bHoverIndex); } RedrawWindow(); //Invalidate(FALSE); } } void CChooseColorStatic::OnPaletteUpdated() { // Someone changed the palette from under us. Invalidate(FALSE); } void CChooseColorStatic::SetSelection(bool *multipleSelection) { _allowMultipleSelection = true; memcpy(_multipleSelection, multipleSelection, sizeof(bool) * (_cRows * _cColumns)); if (m_hWnd) { Invalidate(FALSE); } } void CChooseColorStatic::GetMultipleSelection(bool *multipleSelection) { memcpy(multipleSelection, _multipleSelection, sizeof(bool) * (_cRows * _cColumns)); } // // CChooseBrushStatic // IMPLEMENT_DYNAMIC(CChooseBrushStatic, CChooseColorStatic) CChooseBrushStatic::CChooseBrushStatic() { _bHoverIndex = INVALID_COLORINDEX; _cRows = 0; _cColumns = 0; _fPrintIndex = FALSE; _fShowSelection = FALSE; _bSelectedColorIndex = 0; memset(_pPalette, 0, sizeof(_pPalette)); } CChooseBrushStatic::~CChooseBrushStatic() { } BEGIN_MESSAGE_MAP(CChooseBrushStatic, CChooseColorStatic) ON_WM_DRAWITEM_REFLECT() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_MOUSEMOVE() END_MESSAGE_MAP() #define PATTERN_PAINT_SIZE 16 #define PATTERN_BMP_SIZE (PATTERN_PAINT_SIZE * PATTERN_PAINT_SIZE) RGBQUAD RGBQUADFromCOLORREF(COLORREF color) { RGBQUAD quad; quad.rgbBlue = GetBValue(color); quad.rgbRed = GetRValue(color); quad.rgbGreen = GetGValue(color); quad.rgbReserved = 0; return quad; } void CChooseBrushStatic::_DrawItem(CDC *pDC, int cx, int cy) { // Fill in the background pDC->FillSolidRect(0, 0, cx, cy, g_PaintManager->GetColor(COLOR_BTNFACE)); // Create a bitmap large enough for one brush. EGACOLOR color = { 0x00, 0x00 }; // Black _DrawSelection(pDC); BYTE dataBrush[PATTERN_BMP_SIZE]; // Fake a PicData to draw into, with a visual brush. PicData data = { PicScreenFlags::Visual, (BYTE*)&dataBrush, nullptr, nullptr, nullptr, false, false, size16(DEFAULT_PIC_WIDTH, DEFAULT_PIC_HEIGHT), false, nullptr }; for (BYTE bPaletteIndex = 0; bPaletteIndex < (_cRows * _cColumns); bPaletteIndex++) { // Fill the bitmap with white each time. memset(&dataBrush, 0x0f, sizeof(dataBrush)); // Fill with white // Figure out what we want to draw (growing larger from left to right) // solid circles // pattern circles // solid squares // pattern squares PenStyle penStyle; PatternInfoFromIndex(bPaletteIndex, &penStyle); // Ask the pattern to draw itself DrawPatternInRect(PATTERN_PAINT_SIZE, PATTERN_PAINT_SIZE, &data, 8, 8, color, 0, 0, PicScreenFlags::Visual, &penStyle); // Now draw into the DC. RECT rectSquare; _MapIndexToRect(bPaletteIndex, &rectSquare); SCIBitmapInfo bmi(PATTERN_PAINT_SIZE, PATTERN_PAINT_SIZE); // Adjust the colors a little for the current scheme... COLORREF bgColor = (bPaletteIndex == _bSelectedColorIndex) ? RGB(255, 255, 255) : (g_PaintManager->GetColor(COLOR_BTNFACE)); bmi._colors[0xe] = RGBQUADFromCOLORREF(bgColor); #pragma warning(suppress: 6386) #pragma warning(suppress: 6201) bmi._colors[-1] = RGBQUADFromCOLORREF(g_PaintManager->GetColor(COLOR_BTNTEXT)); // REVIEW: Not sure why I'm using -1 StretchDIBits((HDC)*pDC, rectSquare.left, rectSquare.top, RECTWIDTH(rectSquare), RECTHEIGHT(rectSquare), 0, 0, PATTERN_PAINT_SIZE, PATTERN_PAINT_SIZE, &dataBrush, &bmi, DIB_RGB_COLORS, SRCCOPY); } _DrawHover(pDC); } // Returns inclusive start/end pairs std::vector<std::pair<uint8_t, uint8_t>> GetSelectedRanges(CChooseColorStatic &wndStatic) { std::vector<std::pair<uint8_t, uint8_t>> ranges; bool multipleSelection[256]; wndStatic.GetMultipleSelection(multipleSelection); // Calculate the ranges bool on = false; int startRange = 0; for (int i = 0; i < wndStatic.GetColorCount(); i++) { if (multipleSelection[i] && !on) { startRange = i; on = true; } if (!multipleSelection[i] && on) { ranges.emplace_back((uint8_t)startRange, (uint8_t)(i - 1)); on = false; } } if (on) { ranges.emplace_back((uint8_t)startRange, wndStatic.GetColorCount() - 1); } return ranges; } std::string GetRangeText(const std::vector<std::pair<uint8_t, uint8_t>> &ranges) { std::string rangeText; for (auto &range : ranges) { if (!rangeText.empty()) { rangeText += ",\r\n"; } if (range.first == range.second) { rangeText += fmt::format("{0}", (int)range.first); } else { rangeText += fmt::format("{0}-{1}", (int)range.first, (int)range.second); } } return rangeText; }
#include <QCoreApplication> #include <IoNetClient.h> #include <QSettings> #include <QString> #include <QStringList> #include <QDebug> #include "lireport.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QCoreApplication::setOrganizationName("Lynovitza"); QStringList hosts; bool cMode[6]; { QCoreApplication::setApplicationName("difuz"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); cMode[0]=false; } { QCoreApplication::setApplicationName("satur"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); cMode[1]=false; } { QCoreApplication::setApplicationName("viparka"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); //#define __TEST__ //#ifdef __TEST__ // cMode[2]=false; //#else cMode[2]=true; //#endif } { QCoreApplication::setApplicationName("aparat"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); cMode[3]=false; } { QCoreApplication::setApplicationName("centrif"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); cMode[4]=false; } { QCoreApplication::setApplicationName("rou"); QSettings s; hosts << s.value("/ioserv/hostname","localhost").toString(); cMode[5]=false; } IoNetClient net_d(hosts[0]); net_d.setObjectName("difuz"); net_d.setCmode(cMode[0]); IoNetClient net_s(hosts[1]); net_s.setObjectName("satur"); net_s.setCmode(cMode[1]); IoNetClient net_v(hosts[2]); net_v.setObjectName("viparka"); net_v.setCmode(cMode[2]); IoNetClient net_a(hosts[3],8185); net_a.setObjectName("aparat"); net_a.setCmode(cMode[3]); IoNetClient net_c(hosts[4],8185); net_c.setObjectName("centrif"); net_c.setCmode(cMode[4]); IoNetClient net_r(hosts[5]); net_r.setObjectName("rou"); net_r.setCmode(cMode[5]); QVector<IoNetClient*> srca; srca << &net_d << &net_s << &net_v << &net_a << &net_c << &net_r; // qDebug() << srca.size(); LiReport report(srca); return a.exec(); }
#include <string.h> #include <stdio.h> #include <switch.h> int main(int argc, char **argv) { gfxInitDefault(); consoleInit(NULL); bpcInitialize(); bpcRebootSystem(); return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int n,i,j,cnt=0,cn=0,cd=0,a,b,c; cin>>n; for(i=0;i<n;i++){ cin>>a; cnt+=a;} for(i=0;i<n-1;i++){ cin>>b; cn+=b;} for(i=0;i<n-2;i++){ cin>>c; cd+=c;} cout<<(cnt-cn)<<endl; cout<<(cn-cd)<<endl; }
/* _____ * /\ _ \ __ * \ \ \_\ \ __ __ __ /\_\ * \ \ __ \ /'_ `\ /\ \/\ \\/\ \ * \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \ * \ \_\ \_\\ \____ \\ \____/ \ \_\ * \/_/\/_/ \/____\ \\/___/ \/_/ * /\____/ * \_/__/ * * Copyright (c) 2011 Joshua Larouche * * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Agui nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Button.hpp" namespace cge { Button::~Button(void) { } Button::Button( agui::Image* defaultImage, agui::Image* hoverImage, agui::Image* clickImage, agui::Image* focusImage, agui::Image* disabledImage, agui::Image* centerImage) : m_defaultImage(defaultImage), m_hoverImage(hoverImage), m_clickImage(clickImage), m_focusImage(focusImage), m_centerImage(centerImage), m_disabledImage(disabledImage), m_contentResizeScaleX(1.0f), m_contentResizeScaleY(1.0f), m_textImage(NULL),m_scaleImg(false),m_hideDefault(false), m_imgScale(1.0f) { setTextAlignment(agui::ALIGN_MIDDLE_CENTER); } void Button::paintBackground( const agui::PaintEvent &paintEvent ) { if(!paintEvent.isEnabled() && m_disabledImage) { paintEvent.graphics()->drawNinePatchImage( m_disabledImage,agui::Point(0,0),getSize(),1.0f); } else { switch(getButtonState()) { case DEFAULT: if(!m_hideDefault) { if(isFocused() && m_focusImage) { paintEvent.graphics()->drawNinePatchImage( m_focusImage,agui::Point(0,0),getSize(), 1.0f); } else { paintEvent.graphics()->drawNinePatchImage( m_defaultImage,agui::Point(0,0),getSize(), 1.0f); } } break; case HOVERED: paintEvent.graphics()->drawNinePatchImage( m_hoverImage,agui::Point(0,0),getSize(), 1.0f); break; case CLICKED: paintEvent.graphics()->drawNinePatchImage( m_clickImage,agui::Point(0,0),getSize(), 1.0f); break; } } } void Button::paintComponent( const agui::PaintEvent &paintEvent ) { if(getTextLength() > 0 && m_textImage) { paintEvent.graphics()->drawImage( m_textImage, createAlignedPosition(agui::ALIGN_MIDDLE_CENTER,getInnerRectangle(), agui::Dimension(m_textImage->getWidth(),m_textImage->getHeight()))); } else if(m_centerImage) { if(!m_scaleImg) { paintEvent.graphics()->drawImage( m_centerImage, createAlignedPosition(agui::ALIGN_MIDDLE_CENTER,getInnerRectangle(), agui::Dimension(m_centerImage->getWidth(),m_centerImage->getHeight()))); } else { int w = getInnerWidth() > getInnerHeight() ? getInnerHeight() : getInnerWidth(); w *= getImageScale(); float aspect = m_centerImage->getHeight() / (float)m_centerImage->getWidth(); int h = w * aspect; agui::Point p = createAlignedPosition(agui::ALIGN_MIDDLE_CENTER,getInnerRectangle(), agui::Dimension(w,h)); paintEvent.graphics()->drawScaledImage(m_centerImage,p,agui::Point(),agui::Dimension( m_centerImage->getWidth(),m_centerImage->getHeight()),agui::Dimension(w,h)); } } resizableText.drawTextArea(paintEvent.graphics(),getFont(), getInnerRectangle(),getFontColor(),getAreaText(),getTextAlignment()); } bool Button::intersectionWithPoint( const agui::Point &p ) const { return agui::Rectangle(getMargin(agui::SIDE_LEFT), getMargin(agui::SIDE_TOP),getInnerWidth(), getInnerHeight()).pointInside(p); } void Button::setContentResizeScale( float w, float h ) { m_contentResizeScaleX = w; m_contentResizeScaleY = h; } void Button::resizeToContents() { float constX = 35.0f; float constY = 27.0f; int extraX = (constX * m_contentResizeScaleX) - constX; int extraY = (constY * m_contentResizeScaleY) - constY; agui::Button::resizeToContents(); setSize(getWidth() + extraX, getHeight() + extraY); } void Button::setTextImage( agui::Image* img ) { m_textImage = img; } void Button::setScaleIcon( bool scale ) { m_scaleImg = scale; } void Button::setHideDefault( bool hide ) { m_hideDefault = hide; } void Button::setImage( agui::Image* img ) { m_centerImage = img; } void Button::setImageScale( float scale ) { m_imgScale = scale; } float Button::getImageScale() const { return m_imgScale; } }
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * 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 PAINTLAYER_H #define PAINTLAYER_H #include <QMouseEvent> #include <QPainter> #include <QWidget> #include <renderablewidget.h> class PaintLayerPrivate; class PaintLayer : public QObject { Q_OBJECT public: friend class PaintLayerPrivate; PaintLayer(QObject* parent = 0); virtual ~PaintLayer(); virtual void paint(QPainter* painter) = 0; void setExportMode(bool val); bool exportMode() const; virtual void mousePressEvent(QMouseEvent* evt) { Q_UNUSED(evt) } virtual void mouseReleaseEvent(QMouseEvent* evt) { Q_UNUSED(evt) } virtual void mouseMoveEvent(QMouseEvent* evt) { Q_UNUSED(evt) } //used by the subclass QSize windowSize() const; QFont font() const; void setFont(QFont font); //used by the widget/paintlayerstack virtual void setWindowSize(QSize size); protected: signals: void windowSizeChanged(); void repaintNeeded(); private: PaintLayerPrivate* d; }; class PaintLayerWidgetPrivate; class PaintLayerWidget : public RenderableWidget { public: friend class PaintLayerWidgetPrivate; PaintLayerWidget(PaintLayer* PL); virtual ~PaintLayerWidget(); QImage renderImage(int W, int H) Q_DECL_OVERRIDE; protected: void paintEvent(QPaintEvent* evt); private: PaintLayerWidgetPrivate* d; }; #endif // PAINTLAYER_H
#include <cstdio> #include <climits> #include <cmath> #include <vector> #include <algorithm> using namespace std; typedef pair<double, double> P; // first; x, second; y const int MAX_N = 10000; const int INF = std::numeric_limits<int>::max(); //2,147,483,647 == 2^31 -1 //INPUT int N; P A[MAX_N]; // comparing function for merging by y-increasing bool compare_y(P a, P b){ return a.second < b.second; } // a is given as sorted by x increasing double closest_pair(P *a, int n){ if (n <= 1) return INF; int m = n/2; double x = a[m].first; double d = min(closest_pair(a, m), closest_pair(a+m, n-m));; //(1) inplace_merge(a, a+m, a+n, compare_y);// merge two sorted array. a is sorted by y //(2') vector<P> b; for (int i=0; i<n ; i++){ if (fabs(a[i].first - x) >= d) continue; // check vertex in b from tail to where diff in y is more than d for (int j=0; j<b.size(); j++){ double dx = a[i].first - b[b.size()-j-1].first; double dy = a[i].second - b[b.size()-j-1].second; if (dy>=d) break; d = min (d, sqrt(dx * dx + dy * dy)); } b.push_back(a[i]); } return d; } void solve(){ sort(A, A+N); printf("%f\n", closest_pair(A,N)); } int main(){ N=5; A[0].first=0, A[0].second=2; A[1].first=6, A[1].second=67; A[2].first=43, A[2].second=71; A[3].first=39, A[2].second=107; A[4].first=189, A[2].second=140; solve(); }
#pragma once #include <functional> namespace imog { class Async { using asyncFn = std::function<void(void)>; using floatFn = std::function<float(void)>; static void _periodic(const floatFn& timeFn, bool* threadFlag, const asyncFn& func); public: // Runs a function fn each wait time until flag is false; static void periodic(const floatFn& timeFn, bool* threadFlag, const asyncFn& func); }; } // namespace imog
// // BattleScene.cpp // CrossKaiser // // Created by 龚畅优 on 13-8-27. // // #include "BattleScene.h" #include "BattleController.h" #include "Constant.h" #include "json.h" #include "ResultScene.h" #include "SaveData.h" #include "UserInfo.h" const Rect ITEM_RECT = Rect(160,0, 160,40); BattleScene::BattleScene(){ m_itemSprite = NULL; m_seconds = 0; } BattleScene::~BattleScene(){ _eventDispatcher->removeEventListener(_touchListener); } Scene * BattleScene::scene(){ Scene* scene = Scene::create(); BattleScene *layer = BattleScene::create(); scene->addChild(layer); return scene; } void BattleScene::onEnter(){ Layer::onEnter(); __NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BattleScene::endMission), NC_END_MISSION_TAG, NULL); schedule(schedule_selector(BattleScene::updateEvent),1.f); } void BattleScene::onExit(){ Layer::onExit(); unschedule(schedule_selector(BattleScene::updateEvent)); __NotificationCenter::getInstance()->removeObserver(this, NC_END_MISSION_TAG); } bool BattleScene::init(){ if (!Layer::init()) { return false; } BattleController::shared()->reset(); auto director = Director::getInstance(); Point visibleOrigin = director->getVisibleOrigin(); Size visibleSize = director->getVisibleSize(); m_view = Box2DView::viewWithEntryID( 7 ); addChild(m_view); m_view->setScale(BOX2D_SCALE); m_view->setAnchorPoint( Point(0,0) ); m_view->setPosition( Point(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+BOX2D_GROUND_Y) ); log("x=%f, width=%f, y =%f, height=%f",visibleOrigin.x,visibleSize.width/2, visibleOrigin.y,BOX2D_GROUND_Y); //赋值m_contactListener m_contactListener = m_view->getContactListener(); //先渲染场上的道具 __Dictionary *itemList = BattleController::shared()->getItemList(); DictElement *ele; CCDICT_FOREACH(itemList, ele){ Item *item = dynamic_cast<Item*>(ele->getObject()); b2Fixture *itemBox2d = item->getB2fixture(); Point winPos = CommonUtils::convertBox2DToWin(Point(itemBox2d->GetBody()->GetPosition().x, itemBox2d->GetBody()->GetPosition().y)); Sprite *arrow = Sprite::create("Images/arrows.png"); arrow->setPosition(winPos); this->addChild(arrow); item->setPic(arrow); } //往controller里面添加 注意key 如果场上已经有了道具,这个起始点不是从0开始 //读取数据 __String *file = __String::createWithFormat("mission/mission%d.json", UserInfo::getInstance()->getCurMissionId()); std::string filePath = FileUtils::getInstance()->fullPathForFilename(file->getCString()); Json::Value missionData; CommonUtils::fileToJSON(filePath, missionData); //初始化item位置 Json::Value useItemList = missionData["useItemList"]; for (int i=0; i<useItemList.size(); i++) { Item * item = Item::create(); int type = useItemList[i]["type"].asInt(); item->setType(type); Sprite * itemSprite; switch (type) { case ITEM_CANNON: itemSprite = Sprite::create("Images/arrows.png"); break; default: break; } Point originPoint = Point(160 + 30 *i, 20); itemSprite->setPosition(originPoint); item->setOriginPoint(originPoint); this->addChild(itemSprite); item->setPic(itemSprite); BattleController::shared()->getItemList()->setObject(item, itemList->count()); } // Adds Touch Event Listener auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(BattleScene::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(BattleScene::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(BattleScene::onTouchEnded, this); _eventDispatcher->addEventListenerWithFixedPriority(listener, -10); _touchListener = listener; return true; } bool BattleScene::onTouchBegan(Touch* touch, Event* event) { log("x=%f, y=%f", touch->getLocation().x,touch->getLocation().y); DictElement * obj; __Dictionary * itemList = BattleController::shared()->getItemList(); CCDICT_FOREACH(itemList, obj){ Item * item = dynamic_cast<Item*>(obj->getObject()); if (item->getIsLocked()) { continue; } if (item->getPic()->getBoundingBox().containsPoint(touch->getLocation())) { m_itemSprite = item->getPic(); m_item = item; //通知box2d删除b2Fixture if (item->getB2fixture()) { //这两行顺序不能乱 delItem里面会用到b2Fixture m_contactListener->delItem(item); item->setB2fixture(NULL); } } } return true; } void BattleScene::onTouchMoved(Touch* touch, Event* event) { auto touchLocation = touch->getLocation(); auto nodePosition = convertToNodeSpace( touchLocation ); log("Box2DView::onTouchMoved, pos: %f,%f -> %f,%f", touchLocation.x, touchLocation.y, nodePosition.x, nodePosition.y); if ( m_itemSprite ){ m_itemSprite->setPosition(touchLocation); //给个阴影展示最终落到何处 Point itemBox2DPos = CommonUtils::convertWinToBox2D(m_itemSprite->getPosition()); log("itemBox2DPos x = %f, y=%f", itemBox2DPos.x, itemBox2DPos.y); Point itemFinalPos = m_contactListener->getItemFinalPos(itemBox2DPos); log("itemFinalPos x = %f, y=%f", itemFinalPos.x, itemFinalPos.y); } } void BattleScene::onTouchEnded(Touch* touch, Event* event) { auto touchLocation = touch->getLocation(); auto nodePosition = convertToNodeSpace( touchLocation ); log("Box2DView::onTouchEnded, pos: %f,%f -> %f,%f", touchLocation.x, touchLocation.y, nodePosition.x, nodePosition.y); if ( m_itemSprite ){ if (ITEM_RECT.containsPoint(m_itemSprite->getPosition())) { __Dictionary *itemList = BattleController::shared()->getItemList(); DictElement *ele; CCDICT_FOREACH(itemList, ele){ Item *item = dynamic_cast<Item*>(ele->getObject()); Point originPoint = item->getOriginPoint(); if (item->getPic() == m_itemSprite) { m_itemSprite->setPosition(originPoint); return; } } } Point itemBox2DPos = CommonUtils::convertWinToBox2D(m_itemSprite->getPosition()); Point itemFinalPos = m_contactListener->getItemFinalPos(itemBox2DPos); log("itemFinalPos x = %f, y=%f", itemFinalPos.x, itemFinalPos.y); Point endPos = CommonUtils::convertBox2DToWin(itemFinalPos); log("endPos x = %f, y=%f", endPos.x, endPos.y); //Point finalPos = endPos + Point(0, m_itemSprite->getContentSize().height); float tmpTime = .1f; m_itemSprite->runAction(MoveTo::create(tmpTime, endPos)); m_itemSprite = NULL; //告诉box2d 在finalPos处 CommonUtils::convertWinToBox2D 添加炮台或者别的item m_item->setTmpBox2dPos(itemFinalPos); Action * action = __CCCallFuncO::create(m_view, callfuncO_selector(Box2DView::setItem), m_item); this->runAction(Sequence::create(DelayTime::create(tmpTime), action, NULL)); } } void BattleScene::endMission(Object *obj){ log("battlescene change scene %d", m_seconds); //更新saveData SaveData::getInstance()->setMaxMissionId(UserInfo::getInstance()->getCurMissionId()); ResultScene *resultScene = ResultScene::create(); resultScene->setSeconds(m_seconds); CCDirector::getInstance()->replaceScene(resultScene); } void BattleScene::updateEvent(float delta){ log("delta %f", delta); m_seconds ++; }
#include <cstdio> #include <iostream> #include <string> using namespace std; // #define DEBUG const int maxn = 2505; int line; string res[maxn]; void handle(int type) { int a = 0, b = 0; for (int i = 0; i < line; ++i) { for (int j = 0; j < res[i].size(); ++j) { if (res[i][j] == 'W') ++a; else if (res[i][j] == 'L') ++b; else { cout << a << ":" << b << endl; return; } if ((a >= type && a - b >= 2) || (b >= type && b - a >= 2)) { cout << a << ":" << b << endl; a = b = 0; } } } } int main() { #ifdef DEBUG freopen("d:\\input.txt", "r", stdin); freopen("d:\\output.txt", "w", stdout); #endif for (line = 0;; ++line) { cin >> res[line]; if (res[line].empty()) break; } handle(11); cout << endl; handle(21); return 0; }
#include<bits/stdc++.h> using namespace std; vector<int>arr; bool compare(pair<int,int>& a, pair<int,int>&b){ if(a.first == b.first) return arr[a.second] < arr[b.second]; return a.first > b.first; } int mygcd(int a, int b){ if(a < b) swap(a, b); while(b){ int temp = a%b; a = b; b = temp; } return a; } int main(){ int t; cin >> t; while(t -- ){ int n; cin >> n; arr.resize(n); for(int i = 0; i < n ; i ++){ cin >> arr[i]; } vector<pair<int,int> >b(n); for(int i = 0; i < n; i ++){ b[i] = {arr[i], i}; } int g = 1; for(int i = 0; i < n; i ++){ sort(b.begin() + i, b.end(), compare); cout << arr[b[i].second] << " "; //g = mygcd(g, arr[b[i].second]); for(int j = i + 1; j < n; j ++){ b[j].first = mygcd(arr[b[i].second], b[j].first); } } cout << "\n"; } return 0; }
// ---------------------------------------------------- // Timer.cpp // Body for CPU Tick Timer class // ---------------------------------------------------- #include "Timer.h" // --------------------------------------------- Timer::Timer() { Start(); } // --------------------------------------------- void Timer::Start() { running = true; paused = false; started_at = SDL_GetTicks(); } // --------------------------------------------- void Timer::Stop() { running = false; stopped_at = SDL_GetTicks(); } void Timer::Pause() { if (paused == false) { paused = true; paused_at = SDL_GetTicks(); } } void Timer::UnPause() { if (paused == true) { paused = false; unpaused_at = SDL_GetTicks(); pausetime += (unpaused_at - paused_at); } } // --------------------------------------------- Uint32 Timer::Read() { if (running == true) { if (paused == true) return (paused_at * multiplier - started_at); else return (SDL_GetTicks() * multiplier - started_at) - pausetime; } else { return stopped_at * multiplier - started_at; } } Uint32 Timer::ReadSc() { if (running == true) { if (paused == true) return ((paused_at * multiplier - started_at) / 1000); else return (((SDL_GetTicks() * multiplier - started_at) - pausetime) / 1000); } else { return ((stopped_at * multiplier - started_at) / 1000); } } void Timer::SetMultiplier(float t) { if (t < 1) t = 1; multiplier = t; }
/* ***************************************************************************** * ___ _ _ _ _ * / _ \ __ _| |_| |__(_) |_ ___ * | (_) / _` | / / '_ \ | _(_-< * \___/\__,_|_\_\_.__/_|\__/__/ * Copyright (c) 2011 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *****************************************************************************/ /** * @author R. Picard * @date 2011/05/01 * *****************************************************************************/ #include <new> #include <dlfcn.h> #include <stdio.h> #include "ExeContext.h" /** * @date 2011/05/01 * * Constructor. * ******************************************************************************/ ExeContext::ExeContext(const CallStack &Callers, uint32_t Level): DlListItem(), Memory(0), Stack(Callers, Level), ParentContext(NULL), Id(0) { SetId(); return; } /** * @date 2011/05/01 * * Destructor. * ******************************************************************************/ ExeContext::~ExeContext() { return; } /** * @date 2013/05/22 * * resets all ExeContexts. * Warning : This should be used in unit tests only. ******************************************************************************/ void ExeContext::Reset(void) { DlList *p_ContextList = ExeContext::GetList(); ExeContext *p_Context; while(1) { p_Context = static_cast<ExeContext*>(p_ContextList->GetHead()); if(p_Context != NULL) { p_ContextList->DelItem(p_Context); delete p_Context; } else { break; } } } /** * @date 2013/03/10 * * Sets a unique Id assotiated to a context. ******************************************************************************/ void ExeContext::SetId(void) { static uint32_t NextId = 0; /** @todo : - atomic - check against integer overflow - check against already used id */ Id = NextId++; } /** * @date 2011/05/01 * * returns the first element of the context list. * * @return List of contexts. * ******************************************************************************/ DlList* ExeContext::GetList(void) { static DlList ContextList; return(&ContextList); } /** * @date 2011/05/01 * * returns an ExeContext object. if a context already exists for the specified * callers, then this context is returned. Otherwise a new context is created and * returned. * * @param Callers (in): Callstack of the callers. * @return ExeContext if success. * @return NULL otherwise. * ******************************************************************************/ ExeContext* ExeContext::Get(const CallStack &Callers) { DlList *p_ContextList = ExeContext::GetList(); ExeContext *p_Context = static_cast<ExeContext*>(p_ContextList->GetHead()); ExeContext *p_ParentContext = NULL; /* search for an existing allocer */ while(p_Context != NULL) { if(p_Context->GetCallStack() == Callers) break; else if( (p_ParentContext == NULL) && (p_Context->GetCallStack().GetDepth() == 1) && (p_Context->GetCallStack().CallerIs(Callers)) ) { p_ParentContext = p_Context; } p_Context = (ExeContext*)p_Context->Next; } /* allocate a new entry if not found */ if(p_Context == NULL) { p_Context = new(std::nothrow) ExeContext(Callers); if(p_Context != NULL) { if(Callers.GetDepth() == 1) { p_ContextList->AppendItem(p_Context); } else { /* And also allocate parent if it does not exist yet */ if(p_ParentContext == NULL) { p_ParentContext = new(std::nothrow) ExeContext(Callers, 1); if(p_ParentContext != NULL) p_ContextList->AppendItem(p_ParentContext); } if(p_ParentContext != NULL) { p_Context->ParentContext = p_ParentContext; p_ContextList->AppendItem(p_Context); } else { delete p_Context; p_Context = NULL; } } } } return(p_Context); } /** * @date 2013/03/10 * * returns an ExeContext object that matches the provided Id. * * @param Id (in): Id to search. * @return ExeContext if success. * @return NULL otherwise. ******************************************************************************/ ExeContext* ExeContext::Get(const uint32_t Id) { DlList *p_ContextList = ExeContext::GetList(); ExeContext *p_Context = static_cast<ExeContext*>(p_ContextList->GetHead()); while(p_Context != NULL) { if(p_Context->GetId() == Id) break; p_Context = (ExeContext*)p_Context->Next; } return(p_Context); }
#include "git-rev-export.hpp" #include <git-rev.hpp>
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isPossible(vector<int> &A) { long total = 0; int n = A.size(), a; for (int a : A) total += a; sort(A.begin(), A.end()); while (true) { a = A[n - 1]; if (a == 1) return true; total -= a; if (a <= total) return false; a -= total; total += a; A[n - 1] = a; sort(A.begin(), A.end()); } } };
/*********************************************************************** created: 16/1/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUIGlobalEventSet_h_ #define _CEGUIGlobalEventSet_h_ #include "CEGUI/EventSet.h" #include "CEGUI/Singleton.h" #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4275) #endif // Start of CEGUI namespace section namespace CEGUI { /*! \brief The GlobalEventSet singleton allows you to subscribe to an event for all instances of a class. The GlobalEventSet effectively supports "late binding" to events; which means you can subscribe to some event that does not actually exist (yet). */ class CEGUIEXPORT GlobalEventSet : public EventSet, public Singleton<GlobalEventSet> { public: GlobalEventSet(); ~GlobalEventSet(); /*! \brief Return singleton System object \return Singleton System object */ static GlobalEventSet& getSingleton(void); /*! \brief Return pointer to singleton System object \return Pointer to singleton System object */ static GlobalEventSet* getSingletonPtr(void); /*! \brief Fires the named event passing the given EventArgs object. \param name String object holding the name of the Event that is to be fired (triggered) \param args The EventArgs (or derived) object that is to be bassed to each subscriber of the Event. Once all subscribers have been called the 'handled' field of the event is updated appropriately. \param eventNamespace String object describing the namespace prefix to use when firing the global event. \return Nothing. */ void fireEvent(const String& name, EventArgs& args, const String& eventNamespace = "") override; }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUIGlobalEventSet_h_
//Student Name: Bair Suimaliev //Student email: bsuimaliev@myseneca.ca //Student ID: 159350198 //Date: 09.27.2021 //I have done all the coding by myselfand only copied the code //that my professor provided to complete my workshopsand assignments. #pragma once #ifndef _SDDS_TIMEDEVENTS_H_ #define _SDDS_TIMEDEVENTS_H_ #include <algorithm> #include <iostream> #include <iomanip> #include <ctime> #include <chrono> using namespace std; #define MAX 10 namespace sdds { class TimedEvents { unsigned int recNum; chrono::steady_clock::time_point eventStart; chrono::steady_clock::time_point eventEnd; struct Events { const char* eventName; const char* timeUnit; chrono::steady_clock::duration eventDuration; } records[MAX]; public: TimedEvents(); ~TimedEvents(); void startClock(); void stopClock(); void addEvent(const char* name); friend ostream& operator<<(ostream& os, const TimedEvents& obj); }; } #endif // !_SDDS_TIMEDEVENTS_H_
#include <iostream> using namespace std; class X { public: X() =default; //让编译器提供一个默认的构造函数,效率比用户写的高 X(int i) {//写了带参的构造函数,编译器不会提供无参的构造函数 a = i; } int a; }; //default只能修饰类中默认提供的构成员函数:无参构造,拷贝构造,赋值运算符重载,析构函数等 #if 0 class X2 { public: int f() = default; //err X2(int a) = default;//err }; #endif class X3 { public: X3(); //声明 X3(int i) {//写了带参的构造函数,编译器不会提供无参的构造函数 a = i; } int a; }; X3::X3() =default; //default可以放在类的外部 int main() { X obj; return 0; }
/////////////////////////////////////////////////////////////////// //Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.// //@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) // /////////////////////////////////////////////////////////////////// #pragma once #include "CoreMinimal.h" #include "GameFramework/DefaultPawn.h" #include "CPP_FlyPawn.generated.h" class ASACPPGameModeBase; UCLASS() class SACPP_API ACPP_FlyPawn : public ADefaultPawn { GENERATED_BODY() public: ACPP_FlyPawn(); virtual void Tick(float DeltaTime) override; virtual void SetupPlayerInputComponent(class UInputComponent* _playerInputComponent) override; void LeftMouseButtonPressed(); void LeftMouseButtonReleased(); void RightMouseButtonPressed(); void DoubleTouch(); void TouchPressed(); void MoveForward(float _axisValue); void MoveRight(float _axisValue); void LookUp(float _axisValue); void Turn(float _axisValue); private: bool MoveEnable = true; APlayerController* PlayerController; ASACPPGameModeBase* EditorGameMode; protected: virtual void BeginPlay() override; };
#ifndef H_BOBBLE #define H_BOBBLE #include "TranslatingGameObject.h" class Bobble : public TranslatingGameObject { public: enum Type {RED, GREEN, BLUE, YELLOW}; Bobble::Bobble(); Bobble::Bobble(Type type, int x = 0, int y = 0, double angle = 0, float speed = 0); Bobble::Bobble(const Bobble& other); //Verandert de huidige sprite naar de _SMALL variant. (nodig om in de wachtrij te plaatsen) void MakeSmallSprite(); //Verandert de huidige sprite naar de _BIG variant. (nodig om in de wachtrij te plaatsen) void MakeBigSprite(); /* Eigen functies */ Type getType(){ return type; } void setFlying(bool _flying) { flying = _flying; } bool isFlying() { return flying; } protected: //Kleur Type type; //True als bobble aan het bewegen is. bool flying; }; #endif
#include <TAH.h> int Xaxis = A1; int Yaxis = A2; int Zaxis = A0; TAH myTAH; int X,Y,Z; void setup() { Serial.begin(9600); myTAH.begin(9600); // Start TAH ble serial port pinMode(Xaxis,INPUT); pinMode(Yaxis,INPUT); pinMode(Zaxis,INPUT); myTAH.enterCommandMode(); // Enters TAH command mode myTAH.setName("Joystick"); myTAH.setWorkRole(MASTER); myTAH.setWorkType(IMMEDIATELY); myTAH.setUARTNotification(ON); myTAH.setDeviceScanFilter(ALL_BLE); myTAH.setiBeaconDeployMode(BROADCAST_AND_SCAN); myTAH.setiBeaconMode(ON); myTAH.exitCommandMode(); // Saves changed settings and exit command mode } void loop() { X = analogRead(Xaxis); Y = analogRead(Yaxis); Z = analogRead(Zaxis); if(Y >= 390) { myTAH.println("4"); Serial.println("4"); } else if(Y <= 300) { myTAH.println("3"); Serial.println("3"); } if(X >= 390) { myTAH.println("1"); Serial.println("1"); } else if(X <= 300) { myTAH.println("6"); Serial.println("6"); } if(Z >= 390) { myTAH.println("5"); Serial.println("5"); } /* else if(Z <= 300) { myTAH.println("2"); Serial.println("2"); } */ delay(500); }
#include "TaskState.h" using namespace Task; bool BarrierOn::run() { entity->barrier = true; result = true; return false; } bool BarrierOff::run() { entity->barrier = false; result = true; return false; } bool VisibleOn::run() { entity->visible = true; result = true; return false; } bool VisibleOff::run() { entity->visible = false; result = true; return false; }
#pragma once #ifndef POINT_H #define POINT_H #include <iostream> #include <cmath> class Point { public: Point(); Point(double a, double b); Point(const Point& other); double X() const; double Y() const; Point operator+ (const Point& a) const; Point operator- (const Point& a) const; Point operator* (double a) const; Point operator/ (double a) const; friend std::ostream& operator<< (std::ostream& out, const Point& a); friend std::istream& operator>> (std::istream& in, Point& a); private: double x; double y; }; #endif
// we are traversing all nodes once so // time complexity O(n) // space complexity O(n)(hash map) void solve(Node* root,int cur,int cur_level,int& max_depth,unordered_map<int,int>& hash) { if(root==NULL) { return ; } cur+= root->data; hash[cur_level]=max(hash[cur_level],cur); if(root->left==NULL && root->right==NULL) { max_depth = max(max_depth,cur_level); return ; } solve(root->left,cur,cur_level+1,max_depth,hash); solve(root->right,cur,cur_level+1,max_depth,hash); } // your task is to complete this function int sumOfLongRootToLeafPath(Node* root) { int max_depth = 0; unordered_map<int,int> hash; solve(root,0,0,max_depth,hash); return hash[max_depth]; }
/* * Patrulla.cpp * * Created on: Mar 5, 2013 * Author: j2deme */ #include "Patrulla.h" Patrulla::Patrulla() { this->sirena = "Wiu! Wiu! Wiu!"; this->choques = 99; sonarSirena(); } Patrulla::~Patrulla() {} void Patrulla::sonarSirena() { cout << this->sirena << endl; } void Patrulla::detenerDelicuente() { cout << "Estas bajo arresto!" << endl; } void Patrulla::chocar(Automovil* t) { t->chocar(); cout << "==> Crash! Crash!" << endl; if(t->getChoques() == 0){ cout << "Kaboom! GAME OVER!" << endl; } } void Patrulla::avanza(Automovil* t){ int random = aleatorio(1,7); int distancia; distancia = this->distancia; if(distancia > t->getDistancia()){ //No hace nada; } else if(distancia == t->getDistancia()-1) { chocar(t); } else{ this->distancia = this->distancia + random; } //sonarSirena(); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Phone.Management.Deployment.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a #define WINRT_GENERIC_cdb5efb3_5788_509d_9be1_71ccb8a3362a template <> struct __declspec(uuid("cdb5efb3-5788-509d-9be1-71ccb8a3362a")) __declspec(novtable) IAsyncOperation<bool> : impl_IAsyncOperation<bool> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_303665fe_c4b1_5efe_956c_47bc585892c0 #define WINRT_GENERIC_303665fe_c4b1_5efe_956c_47bc585892c0 template <> struct __declspec(uuid("303665fe-c4b1-5efe-956c-47bc585892c0")) __declspec(novtable) IVectorView<Windows::Phone::Management::Deployment::Enterprise> : impl_IVectorView<Windows::Phone::Management::Deployment::Enterprise> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_eb8eb40a_3f5c_5a3f_89d1_4a1b6e1a892e #define WINRT_GENERIC_eb8eb40a_3f5c_5a3f_89d1_4a1b6e1a892e template <> struct __declspec(uuid("eb8eb40a-3f5c-5a3f-89d1-4a1b6e1a892e")) __declspec(novtable) IAsyncOperation<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> : impl_IAsyncOperation<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> {}; #endif #ifndef WINRT_GENERIC_2b09fc25_8741_5113_8089_89df9fbb2639 #define WINRT_GENERIC_2b09fc25_8741_5113_8089_89df9fbb2639 template <> struct __declspec(uuid("2b09fc25-8741-5113-8089-89df9fbb2639")) __declspec(novtable) IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> : impl_IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_69ad6aa7_0c49_5f27_a5eb_ef4d59467b6d #define WINRT_GENERIC_69ad6aa7_0c49_5f27_a5eb_ef4d59467b6d template <> struct __declspec(uuid("69ad6aa7-0c49-5f27-a5eb-ef4d59467b6d")) __declspec(novtable) IIterable<Windows::ApplicationModel::Package> : impl_IIterable<Windows::ApplicationModel::Package> {}; #endif #ifndef WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447 #define WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447 template <> struct __declspec(uuid("b0d63b78-78ad-5e31-b6d8-e32a0e16c447")) __declspec(novtable) IIterable<Windows::Foundation::Uri> : impl_IIterable<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_d1bb509e_6989_5c69_b1ff_d1702fe8aca3 #define WINRT_GENERIC_d1bb509e_6989_5c69_b1ff_d1702fe8aca3 template <> struct __declspec(uuid("d1bb509e-6989-5c69-b1ff-d1702fe8aca3")) __declspec(novtable) IVector<Windows::ApplicationModel::Package> : impl_IVector<Windows::ApplicationModel::Package> {}; #endif #ifndef WINRT_GENERIC_0263c4d4_195c_5dc5_a7ca_6806ceca420b #define WINRT_GENERIC_0263c4d4_195c_5dc5_a7ca_6806ceca420b template <> struct __declspec(uuid("0263c4d4-195c-5dc5-a7ca-6806ceca420b")) __declspec(novtable) IVectorView<Windows::ApplicationModel::Package> : impl_IVectorView<Windows::ApplicationModel::Package> {}; #endif #ifndef WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50 #define WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50 template <> struct __declspec(uuid("4b8385bd-a2cd-5ff1-bf74-7ea580423e50")) __declspec(novtable) IVectorView<Windows::Foundation::Uri> : impl_IVectorView<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e #define WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e template <> struct __declspec(uuid("0d82bd8d-fe62-5d67-a7b9-7886dd75bc4e")) __declspec(novtable) IVector<Windows::Foundation::Uri> : impl_IVector<Windows::Foundation::Uri> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a #define WINRT_GENERIC_c1d3d1a2_ae17_5a5f_b5a2_bdcc8844889a template <> struct __declspec(uuid("c1d3d1a2-ae17-5a5f-b5a2-bdcc8844889a")) __declspec(novtable) AsyncOperationCompletedHandler<bool> : impl_AsyncOperationCompletedHandler<bool> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_9b59f83c_1878_5613_8f5d_04ffa635960d #define WINRT_GENERIC_9b59f83c_1878_5613_8f5d_04ffa635960d template <> struct __declspec(uuid("9b59f83c-1878-5613-8f5d-04ffa635960d")) __declspec(novtable) IVector<Windows::Phone::Management::Deployment::Enterprise> : impl_IVector<Windows::Phone::Management::Deployment::Enterprise> {}; #endif #ifndef WINRT_GENERIC_f5a2e51b_bfee_56f4_8f40_67c6bdaf04e0 #define WINRT_GENERIC_f5a2e51b_bfee_56f4_8f40_67c6bdaf04e0 template <> struct __declspec(uuid("f5a2e51b-bfee-56f4-8f40-67c6bdaf04e0")) __declspec(novtable) IIterator<Windows::Phone::Management::Deployment::Enterprise> : impl_IIterator<Windows::Phone::Management::Deployment::Enterprise> {}; #endif #ifndef WINRT_GENERIC_3f9a54a9_f28d_58f4_8e23_fec08e60465e #define WINRT_GENERIC_3f9a54a9_f28d_58f4_8e23_fec08e60465e template <> struct __declspec(uuid("3f9a54a9-f28d-58f4-8e23-fec08e60465e")) __declspec(novtable) IIterable<Windows::Phone::Management::Deployment::Enterprise> : impl_IIterable<Windows::Phone::Management::Deployment::Enterprise> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_ac15a9d6_c9f1_546a_a177_d654070354a6 #define WINRT_GENERIC_ac15a9d6_c9f1_546a_a177_d654070354a6 template <> struct __declspec(uuid("ac15a9d6-c9f1-546a-a177-d654070354a6")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> : impl_AsyncOperationCompletedHandler<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> {}; #endif #ifndef WINRT_GENERIC_1238919b_8b14_543f_87dd_f61016fe69c5 #define WINRT_GENERIC_1238919b_8b14_543f_87dd_f61016fe69c5 template <> struct __declspec(uuid("1238919b-8b14-543f-87dd-f61016fe69c5")) __declspec(novtable) AsyncOperationProgressHandler<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> : impl_AsyncOperationProgressHandler<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> {}; #endif #ifndef WINRT_GENERIC_a4957016_544c_5f79_b163_c695b592e043 #define WINRT_GENERIC_a4957016_544c_5f79_b163_c695b592e043 template <> struct __declspec(uuid("a4957016-544c-5f79-b163-c695b592e043")) __declspec(novtable) AsyncOperationWithProgressCompletedHandler<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> : impl_AsyncOperationWithProgressCompletedHandler<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_0217f069_025c_5ee6_a87f_e782e3b623ae #define WINRT_GENERIC_0217f069_025c_5ee6_a87f_e782e3b623ae template <> struct __declspec(uuid("0217f069-025c-5ee6-a87f-e782e3b623ae")) __declspec(novtable) IIterator<Windows::ApplicationModel::Package> : impl_IIterator<Windows::ApplicationModel::Package> {}; #endif #ifndef WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5 #define WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5 template <> struct __declspec(uuid("1c157d0f-5efe-5cec-bbd6-0c6ce9af07a5")) __declspec(novtable) IIterator<Windows::Foundation::Uri> : impl_IIterator<Windows::Foundation::Uri> {}; #endif #ifndef WINRT_GENERIC_e87c7f91_269c_5f90_9f56_3b42bbf585dc #define WINRT_GENERIC_e87c7f91_269c_5f90_9f56_3b42bbf585dc template <> struct __declspec(uuid("e87c7f91-269c-5f90-9f56-3b42bbf585dc")) __declspec(novtable) IIterable<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> : impl_IIterable<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> {}; #endif #ifndef WINRT_GENERIC_4f6ace87_9657_5e84_869a_0ecc099bf549 #define WINRT_GENERIC_4f6ace87_9657_5e84_869a_0ecc099bf549 template <> struct __declspec(uuid("4f6ace87-9657-5e84-869a-0ecc099bf549")) __declspec(novtable) IVector<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> : impl_IVector<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> {}; #endif #ifndef WINRT_GENERIC_f257cd9f_1b7e_57a0_b877_3df574097afb #define WINRT_GENERIC_f257cd9f_1b7e_57a0_b877_3df574097afb template <> struct __declspec(uuid("f257cd9f-1b7e-57a0-b877-3df574097afb")) __declspec(novtable) IVectorView<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> : impl_IVectorView<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> {}; #endif #ifndef WINRT_GENERIC_c9d7f812_6009_5e3f_ad06_2bcd6bb19cc1 #define WINRT_GENERIC_c9d7f812_6009_5e3f_ad06_2bcd6bb19cc1 template <> struct __declspec(uuid("c9d7f812-6009-5e3f-ad06-2bcd6bb19cc1")) __declspec(novtable) IIterator<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> : impl_IIterator<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> {}; #endif } namespace Windows::Phone::Management::Deployment { struct IEnterprise : Windows::Foundation::IInspectable, impl::consume<IEnterprise> { IEnterprise(std::nullptr_t = nullptr) noexcept {} }; struct IEnterpriseEnrollmentManager : Windows::Foundation::IInspectable, impl::consume<IEnterpriseEnrollmentManager> { IEnterpriseEnrollmentManager(std::nullptr_t = nullptr) noexcept {} }; struct IEnterpriseEnrollmentResult : Windows::Foundation::IInspectable, impl::consume<IEnterpriseEnrollmentResult> { IEnterpriseEnrollmentResult(std::nullptr_t = nullptr) noexcept {} }; struct IInstallationManagerStatics : Windows::Foundation::IInspectable, impl::consume<IInstallationManagerStatics> { IInstallationManagerStatics(std::nullptr_t = nullptr) noexcept {} }; struct IInstallationManagerStatics2 : Windows::Foundation::IInspectable, impl::consume<IInstallationManagerStatics2> { IInstallationManagerStatics2(std::nullptr_t = nullptr) noexcept {} }; struct IPackageInstallResult : Windows::Foundation::IInspectable, impl::consume<IPackageInstallResult> { IPackageInstallResult(std::nullptr_t = nullptr) noexcept {} }; struct IPackageInstallResult2 : Windows::Foundation::IInspectable, impl::consume<IPackageInstallResult2> { IPackageInstallResult2(std::nullptr_t = nullptr) noexcept {} }; } }
#pragma once namespace CMI { class Instrument; class Session { public: Session(); virtual ~Session(); virtual const Instrument *getInstrument(UInt32 index) const; virtual void setInstrument(UInt32 index, Instrument *instrument); private: static const UInt32 MaxInstrumentCount = 24; Instrument *_instruments[MaxInstrumentCount]; }; } //namespace CMI
#include <iostream> #include<stdlib.h> #include<stdio.h> #define STACK_INIT_SIZE 10 using namespace std; typedef struct stackList { int * base; int * top; int stacksize; } sqStack; /**初始化栈**/ void createStack(sqStack * L) { L->stacksize = STACK_INIT_SIZE; L->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int)); if(! L->base) { exit(0); } L->top = L->base; } /**push栈**/ void pushStack(sqStack * L, int e) { if (L->base - L->top >= STACK_INIT_SIZE) { L->base = (int*)realloc(L->base,(L->stacksize+10)*sizeof(int)); if(!L->base) { exit(0); } L->top = L->base + L->stacksize; L->stacksize = L->stacksize+10; } *(L->top) = e ; L->top++; } /**pop栈**/ void popStachk(sqStack * L, int & e){ //这里用 &代表没有拷贝 对原有参数进行操作 效率高. if (L->base == L->top) { printf("栈中已没数据\n"); exit(0); } L->top--; e = *(L->top); } int main() { sqStack L; createStack(&L); int e = 5; int j ; pushStack(&L , e); popStachk(&L, j); cout<< "弹出的为:"<<j <<endl; return 0; }
/** * CalcSum0to10.h * Concrete Command class which knows an operation (Calculator(Receiver) class and parameters) */ #ifndef __CALC_SUM_0TO10__ #define __CALC_SUM_0TO10__ #include "CalcCommand.h" class CalcSum0to10 : public CalcCommand { public: CalcSum0to10(Calculator &calculator); virtual void execute(); }; #endif //__CALC_SUM_0TO10__
{dede:addurls}beij.weierkq.com/zzal/{/dede:addurls} {dede:batchrule}{/dede:batchrule} {dede:regxrule}{/dede:regxrule} {dede:areastart}<div class="al_list">{/dede:areastart} {dede:areaend}<div class="zj_fenye"> {/dede:areaend}
#ifndef PROCESSSTEP_H #define PROCESSSTEP_H /* Project: Stereo-vision-client Author: Ben Description: This class holds all the data of a processstep. */ // Global includes #include <QObject> #include <QStringList> #include <QColor> //Local includes #include "DataTypes/Parameters/allparametertypes.h" class ProcessStep : public QObject { Q_OBJECT public: explicit ProcessStep(QString name, int number, QString group, QColor color = "white", QObject *parent = 0); //Get methods QString name(); QString group(); QColor color(); QStringList inputStreams(); QStringList outputStreams(); AbstractParameter* parameter( QString name ); AbstractParameter* parameter( int i ); int numberOfParameters() const; int numberOfStreams() const; int streamID( QString streamName ) const; signals: void changedParameter(); public slots: //Set methods void addParameter( BooleanParameter* parameter ); void addParameter( NumericParameter* parameter ); void addParameter( SelectParameter* parameter ); void addParameter( PerformParameter* parameter ); void addStream( QString streamname, bool isInput); void changeParameter( AbstractParameter* parameter ); void parameterChanged(); private: QString _name; int _stepNumber; QString _group; QColor _color; QStringList _inputStreams; QStringList _outputStreams; QList< AbstractParameter* > _parameters; void addParameter( AbstractParameter* parameter ); }; #endif // PROCESSSTEP_H