text
stringlengths
8
6.88M
class ItemEtool : ItemCore { scope = 2; model = "\dayz_equip\models\etool.p3d"; picture = "\dayz_equip\textures\equip_etool_ca.paa"; displayName = $STR_EQUIP_NAME_1; descriptionShort = $STR_EQUIP_DESC_1; }; class ItemEtoolBroken : ItemCore { scope = 2; model = "\dayz_equip\models\etool.p3d"; picture = "\dayz_epoch_c\icons\tools\ItemEtoolBroken.paa"; displayName = $STR_EQUIP_NAME_1_BROKEN; descriptionShort = $STR_EQUIP_DESC_1_BROKEN; class ItemActions { class Repair { text = $STR_ACTIONS_FIX_ETOOL; script = ";['Repair','CfgWeapons', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {}; output[] = {}; outputweapons[] = {"ItemEtool"}; input[] = {{"equip_duct_tape",1},{"equip_lever",1}}; inputweapons[] = {"ItemEtoolBroken"}; }; }; };
#include "shadermanager.hpp" ShaderManager::~ShaderManager() { if(!this->shaderModules.empty()) { std::cout << "Not all shader mouldes have been manually deleted. " "Automatically deleting:" << std::endl; for(const auto &[shaderName,shaderID] : this->shaderModules) { std::cout << '\t' << shaderName << std::endl; glDeleteShader(shaderID); } } if(!this->shaderPrograms.empty()) { std::cout << "Not all shader programs have been manually deleted. " "Automatically deleting:" << std::endl; for(const auto &[programName,programID] : this->shaderPrograms) { std::cout << '\t' << programName << std::endl; glDeleteShader(programID); } } } void ShaderManager::CreateShaderModule(const ShaderModuleInfo &moduleInfo) { std::ifstream shaderFile(moduleInfo.pathToShader,std::ios::in | std::ios::binary); if(!shaderFile.is_open()) { std::cout << "Shader file at location: \"" << moduleInfo.pathToShader << "\" could not be opened!" << std::endl; exit(-1); } shaderFile.seekg(0,std::ios::end); u32 fileLength = shaderFile.tellg(); shaderFile.seekg(0,std::ios::beg); std::string fileContent; fileContent.reserve(fileLength + 1); // for '\0' character shaderFile.read(const_cast<char*>(fileContent.data()),fileLength); fileContent[fileLength] = '\0'; shaderFile.close(); const char* contentLocation = fileContent.c_str(); u32 shaderID = glCreateShader(moduleInfo.type); glShaderSource(shaderID,1,&contentLocation,NULL); glCompileShader(shaderID); i32 valid; glGetShaderiv(shaderID,GL_COMPILE_STATUS,&valid); if(!valid) { i32 logLength; glGetShaderiv(shaderID,GL_INFO_LOG_LENGTH,&logLength); std::string log; log.resize(logLength); glGetShaderInfoLog(shaderID,logLength,nullptr,const_cast<char*>(log.data())); std::cout << "Invalid \"" << moduleInfo.pathToShader << "\" contents:\n" << log << std::endl; exit(-1); } this->shaderModules.insert(std::make_pair(moduleInfo.name,shaderID)); } void ShaderManager::CreateShaderProgram(const ShaderProgramInfo &programInfo) { u32 programID = glCreateProgram(); for(const std::string &moduleName : programInfo.moduleNames) glAttachShader(programID,shaderModules[moduleName]); glLinkProgram(programID); i32 valid; glGetProgramiv(programID,GL_LINK_STATUS,&valid); if(!valid) { i32 logLength; glGetProgramiv(programID,GL_INFO_LOG_LENGTH,&logLength); std::string log; log.resize(logLength); glGetProgramInfoLog(programID,logLength,nullptr,const_cast<char*>(log.data())); std::cout << "Unsucsessful shader program linking:\n" << log << std::endl; exit(-1); } if(programInfo.deleteModules) for(const std::string &moduleName : programInfo.moduleNames) { u32 shaderID = this->shaderModules[moduleName]; glDetachShader(programID,shaderID); glDeleteShader(shaderID); this->shaderModules.erase(moduleName); } else for(const std::string &moduleName : programInfo.moduleNames) glDetachShader(programID,this->shaderModules[moduleName]); this->shaderPrograms.insert(std::make_pair(programInfo.name,programID)); } void ShaderManager::UseShaderProgram(const std::string &programName) { glUseProgram(this->shaderPrograms[programName]); } void ShaderManager::DeleteSelectedShaderModules(const std::vector<std::string> &moduleNames) { for(const std::string &moduleName : moduleNames) { glDeleteShader(this->shaderModules[moduleName]); this->shaderModules.erase(moduleName); } } void ShaderManager::DeleteSelectedShaderPrograms(const std::vector<std::string> &programNames) { for(const std::string &programName : programNames) { glDeleteShader(this->shaderPrograms[programName]); this->shaderPrograms.erase(programName); } } void ShaderManager::DeleteAllShaderModules() { for(const auto &[shaderName,shaderID] : this->shaderModules) glDeleteShader(shaderID); this->shaderModules.clear(); } void ShaderManager::DeleteAllShaderPrograms() { for(const auto &[programName,programID] : this->shaderPrograms) glDeleteProgram(programID); this->shaderPrograms.clear(); } i32 ShaderManager::GetUniformLocation(const std::string &programName,const std::string &variableName) { i32 location = glGetUniformLocation(this->shaderPrograms[programName],variableName.c_str()); if(location == -1) { std::cout << "Variable \"" << variableName << "\" can't be found in the shader program \"" << programName << "\"!" << std::endl; exit(-1); } return location; } void ShaderManager::SetVariable(const ShaderVariable<i32> &submission) { glUniform1i(GetUniformLocation(submission.programName,submission.variableName),submission.newValue); } void ShaderManager::SetVariable(const ShaderVariable<f32> &submission) { glUniform1f(GetUniformLocation(submission.programName,submission.variableName),submission.newValue); } void ShaderManager::SetVariable(const ShaderVariable<glm::vec2> &submission) { glUniform2fv(GetUniformLocation(submission.programName,submission.variableName),1,glm::value_ptr(submission.newValue)); } void ShaderManager::SetVariable(const ShaderVariable<glm::vec3> &submission) { glUniform3fv(GetUniformLocation(submission.programName,submission.variableName),1,glm::value_ptr(submission.newValue)); } void ShaderManager::SetVariable(const ShaderVariable<glm::vec4> &submission) { glUniform4fv(GetUniformLocation(submission.programName,submission.variableName),1,glm::value_ptr(submission.newValue)); } void ShaderManager::SetVariable(const ShaderVariable<glm::mat4> &submission) { glUniformMatrix4fv(GetUniformLocation(submission.programName,submission.variableName),1,false,glm::value_ptr(submission.newValue)); }
// #pragma once #ifndef MJASON_H #define MJSON_H #include <iostream> #include <vector> #include <string> #endif // !MJASON_H
// HKRuleSettingDlg.cpp : implementation file // #include "stdafx.h" #include "BHMonitor.h" #include "HKRuleSettingDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CHKRuleSettingDlg dialog CHKRuleSettingDlg::CHKRuleSettingDlg(CWnd* pParent /*=NULL*/) : CDialog(CHKRuleSettingDlg::IDD, pParent) { //{{AFX_DATA_INIT(CHKRuleSettingDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_iRuleNum = -1; } void CHKRuleSettingDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CHKRuleSettingDlg) // NOTE: the ClassWizard will add DDX and DDV calls here DDX_Control(pDX, IDC_LIST_HOOKING_RULES, m_listHkRules); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CHKRuleSettingDlg, CDialog) //{{AFX_MSG_MAP(CHKRuleSettingDlg) ON_BN_CLICKED(IDC_BT_SAVE_HKRULES, OnBtSaveHkrules) ON_BN_CLICKED(IDC_BT_ADD_HKRULES, OnBtAddHkrules) ON_BN_CLICKED(IDC_BT_DEL_HKRULES, OnBtDelHkrules) ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHKRuleSettingDlg message handlers BOOL CHKRuleSettingDlg::OnInitDialog() { CDialog::OnInitDialog(); m_listHkRules.ModifyStyle(0, LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_listHkRules.SetExtendedStyle(m_listHkRules.GetExtendedStyle() |LVS_EX_FULLROWSELECT ); m_listHkRules.InsertColumn(0, _T("Rule No."), 70, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_listHkRules.InsertColumn(1, _T("Original Url"), 200, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); m_listHkRules.InsertColumn(2, _T("Replaced Url"), 210, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); // 判断是否存在影射规则的配置文件,如果没有,则创建 // 有,则读取其中的配置,并在listctrl中显示 CStdioFile cfgFile; if(!cfgFile.Open(_T("hkrules.txt"), CFile::modeRead | CFile::modeCreate | CFile::modeNoTruncate)){ AfxMessageBox(_T("Open config file failed!")); return FALSE; } CString line, oUrl, rUrl; int pos, nItem, i = 0; while(cfgFile.ReadString(line)){ pos = line.Find('-'); oUrl = line.Left(pos); rUrl = line.Right(line.GetLength() - pos - strlen("-")); // store the map relation into m_UrlMapList m_UrlMapList[i].first = oUrl; m_UrlMapList[i].second = rUrl; i++; // update the client area of CListCtrl. nItem = m_listHkRules.InsertItem(m_listHkRules.GetItemCount(), _T("Rule")); m_listHkRules.SetItemText(nItem, 1, (LPCTSTR)oUrl); m_listHkRules.SetItemText(nItem, 2, (LPCTSTR)rUrl); m_listHkRules.Update(nItem); } m_iMapNum = i; return TRUE; } void CHKRuleSettingDlg::OnBtSaveHkrules() { // TODO: Add your control notification handler code here // 保存配置信息 int nItem = m_listHkRules.GetItemCount(); int i = 0; CString oUrl, rUrl; // original url and replaced url. BOOL bFullFilled = TRUE; while(i < nItem){ oUrl = m_listHkRules.GetItemText(i, 1); rUrl = m_listHkRules.GetItemText(i, 2); oUrl.TrimLeft(); oUrl.TrimRight(); rUrl.TrimLeft(); rUrl.TrimRight(); // 这里暂时不考虑https://开头的URL if(oUrl == "" || -1 == oUrl.Find("http://") ){ AfxMessageBox(_T("Please fill the original url!")); bFullFilled = FALSE; break; }else if(rUrl == "" || -1 == rUrl.Find("http://") ){ AfxMessageBox(_T("Please fill the replaced url!")); bFullFilled = FALSE; break; } i++; } if(bFullFilled){ // 打开配置文件 CFile cfgFile; if(!cfgFile.Open(_T("./hkrules.txt"), CFile::modeReadWrite | CFile::modeCreate | CFile::modeNoTruncate)){ AfxMessageBox(_T("Open config file failed!")); }else{ // 首先将文件清零 cfgFile.SetLength(0); // 将信息写入配置文件 i = 0; CString strUrlMap; while(i < nItem){ m_UrlMapList[i].first = m_listHkRules.GetItemText(i, 1); m_UrlMapList[i].second = m_listHkRules.GetItemText(i, 2); strUrlMap = m_UrlMapList[i].first + "-" + m_UrlMapList[i].second + "\n"; cfgFile.Write((LPCTSTR)strUrlMap, strUrlMap.GetLength()); // 千万别忘记了:D i++; } m_iMapNum = i; cfgFile.Flush(); cfgFile.Close(); } CDialog::OnOK(); } } void CHKRuleSettingDlg::OnBtAddHkrules() { // TODO: Add your control notification handler code here CString itemStr; itemStr.Format("Rule %3d", m_iRuleNum+1); m_iRuleNum = m_listHkRules.InsertItem(m_listHkRules.GetItemCount(), itemStr); m_listHkRules.Update(m_iRuleNum); } void CHKRuleSettingDlg::OnBtDelHkrules() { // TODO: Add your control notification handler code here POSITION pos = m_listHkRules.GetFirstSelectedItemPosition(); int nItem = 0; // 这里需要更新item的序号 if(pos){ nItem = m_listHkRules.GetNextSelectedItem(pos); m_listHkRules.DeleteItem(nItem); m_iRuleNum--; } } void CHKRuleSettingDlg::OnClose() { // TODO: Add your message handler code here and/or call default if(AfxMessageBox(IDS_EXITHKRULES_PROMPT, MB_YESNO) == IDYES) CDialog::OnClose(); }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <math.h> using namespace std; int n, s[111][111]; void input() { scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &s[i][j]); } void solve() { } void output() { } int main() { int ntest; freopen("xoanoc.inp", "r", stdin); scanf("%d", &ntest); for (int itest = 0; itest < ntest; itest++) { input(); solve(); output(); } return 0; }
#include <stdio.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <vector> #include "discretize.h" #include "common.h" #include "decisiontree.h" void test1(){ std::vector<cv::Mat> images; std::vector<cv::Mat> patches; read_imgList("images.txt", &images); for(auto& img : images){ cv::imshow("", img); cutPatchesFromImage(img, &patches); } printf("%zu \n", patches.size()); std::vector<int> hs(patches.size(), 0); int num_of_classes, seg_idx; selectFeaturesFromPatches(patches, &hs, &num_of_classes, &seg_idx); printf("seg index %d\n", seg_idx); cv::imshow("seg", patches[seg_idx]); cv::waitKey(); for(int i = 0; i < num_of_classes; i++){ int counter = 0; for(int j = 0; j < hs.size(); j++){ if (i != hs[j]) continue; if (counter > 50) continue; char name[100]; sprintf(name, "a %d", j); cv::Mat tmp2; cv::normalize(patches[j], tmp2, 0, 255, cv::NORM_MINMAX, CV_8UC1); cv::pyrUp(tmp2, tmp2); cv::pyrUp(tmp2, tmp2); cv::imshow(name, tmp2); counter += 1; } printf(">%d\n", i); printf("\n"); cv::waitKey(); cv::destroyAllWindows(); } } void test2(){ std::vector<cv::Mat> images; char name[128]; /*for(int i = 0; i < 20; i++){ sprintf(name, "/home/daiver/dump2/neg-%d.png", i); images.push_back(cv::imread(name, 0)); }*/ for(int i = 0; i < 20; i++){ sprintf(name, "/home/daiver/dump2/pos-%d.png", i); images.push_back(cv::imread(name, 0)); } std::vector<int> hs(images.size(), 0); int num_of_classes, seg_idx; selectFeaturesFromPatches(images, &hs, &num_of_classes, &seg_idx); for(int i = 0 ; i < hs.size(); i++){ printf("%d: %d\n", i, hs[i]); } } int main(){ test2(); return 0; }
#ifndef CCATEGORYFACTORY_H #define CCATEGORYFACTORY_H #include <QObject> #include "common.h" class CDriverCategory; class CERPCategory; class CWebCategory; #define DATA QMap<QString, QMap<QString, SoftData> > #define DATATTERATOR QMapIterator<QString, QMap<QString, SoftData> > #define DATASOFT QMap<QString, SoftData> #define DATASOFTITERATOR QMapIterator<QString, SoftData> class CCategoryFactory : public QObject { Q_OBJECT public: static CCategoryFactory* Instance(); ~CCategoryFactory(); //获取本地数据 DATA LocalData()const; //加载本地数据 void LoadLocalData(); //返回已经安装至本地的品牌类型 QString GetLocalBrand()const; Q_SIGNALS: //软件更新广播消息 void upgradeNotify(SMonitor::Type type = SMonitor::Upgrade); //数据更新通知消息 void dataChangedNotify(const DATA&); //消息分发 void MessageNotify(const QDateTime& , const QString& ); //软件安装成功后提交安装完成信号 void SoftwareInstalled(const QString& name); public Q_SLOTS: //软件安装成功流程 void InstallFinished(const QString& name); //获取服务器数据后得到可更新数据 void CheckUpgradeData() ; private: static CCategoryFactory* m_Instance; //从xml文件中读取数据 bool LoadData(const QString& file, DATA& data, bool bLocal); //修改本地数据软件信息 void SetLocalData(const SoftData& data); //从XML删除数据 void DelLocalData(const SoftData& data); //设置某个品牌为已安装类型 void SetLocalBrand(const QString& brand); //获取某个类型的软件更新数据 DATASOFT GetCategoryUpgradeData(const QString& category, const DATASOFT& SvrData) const; //获取xml中的密码配置信息 void UpdateBrandPasswdBySvrFile(); //判断软件是否安装 bool IsAppInstall(const SoftData& data); private: class PrivateFree { public: PrivateFree(){} ~PrivateFree() { if( CCategoryFactory::m_Instance ) { delete CCategoryFactory::m_Instance; CCategoryFactory::m_Instance = nullptr; } } }; static PrivateFree pFree; CCategoryFactory(QObject *parent = 0); private: DATA m_pLocalData; //本地数据 DATASOFT m_pUpgradeData; //保存当前需要更新的数据 QMutex m_pXmlFileMutex; //xml文件锁 }; #define CategoryFactory CCategoryFactory::Instance() #endif // CCATEGORYFACTORY_H
#ifndef EDITWINDOW_H #define EDITWINDOW_H #include <QWidget> #include <QDebug> #include "library.h" #include "book.h" namespace Ui { class EditWindow; } class EditWindow : public QWidget { Q_OBJECT public: explicit EditWindow(QWidget *parent = nullptr); void setLibrary(Library *library, bool editMode=false, Book *book=nullptr); ~EditWindow(); private slots: void on_main_btn_clicked(); private: Ui::EditWindow *ui; Library *library; Book *selectedBook = nullptr; bool editMode = false; }; #endif // EDITWINDOW_H
#define GLUT_DISABLE_ATEXIT_HACK #include <windows.h> #include <math.h> #include "GL/glut.h" #include <iostream> #define KEY_ESC 27 using namespace std; void create_Square(double centerX, double centerY, double longitude) { glBegin(GL_LINE_LOOP); glColor3d(255, 0, 0); glVertex2f(centerX - (longitude / 2), centerY + (longitude / 2)); glVertex2f(centerX + (longitude / 2), centerY + (longitude / 2)); glVertex2f(centerX + (longitude / 2), centerY - (longitude / 2)); glVertex2f(centerX - (longitude / 2), centerY - (longitude / 2)); glVertex2f(centerX - (longitude / 2), centerY + (longitude / 2)); glEnd(); } void create_circle(double centerX, double centerY, double radius) { glBegin(GL_LINE_LOOP); for (int i = 0; i < 100; i++) { double theta = 2.0 * 3.1415926 * double(i) / 100.0; double x = radius * cosf(theta); double y = radius * sinf(theta); glVertex2f(x + centerX, y + centerY); } glEnd(); } void create_internal_circles(int circlenum, double porcent, int centerx, int centery, int radio) { double recentx = centerx; double recenty = centery; double recentradio = radio; for (int i = 0; i < circlenum; i++) { create_circle(recentx, recenty, recentradio); recentx = recentx + (recentradio * (porcent / 100.0)); recentradio = recentradio + (recentradio * (porcent / 100.0)); //cout << "recentx: " << recentx << endl; } } void create_horizontal_circles(int circlenum, double porcent, int centerx, int centery, int radio) { double recentx = centerx; double recenty = centery; double recentradio = radio; for (int i = 0; i < circlenum; i++) { create_circle(recentx, recenty, recentradio); recentx = recentx + (recentradio - (recentradio * (porcent / 100.0))) + recentradio; recentradio = recentradio - (recentradio * (porcent / 100.0)); } } void create_angle_circles(int circlenum, double porcent, int centerx, int centery, int radio, float angle) { double recentx = centerx; double recenty = centery; double recentradio = radio; for (int i = 0; i < circlenum; i++) { create_circle(recentx, recenty, recentradio); recentx = recentx + (recentradio - (recentradio * (porcent / 100.0))) + recentradio; double temporalX = recentx; double temporalY = recenty; recentx = temporalX * cosf(angle) - temporalY * sinf(angle); recenty = temporalX * sinf(angle) + temporalY * cosf(angle); recentradio = recentradio - (recentradio * (porcent / 100.0)); } } //dibuja un simple gizmo void displayGizmo() { //create_Square(10, 10, 10); //create_circle(0, 0, 20); //create_internal_circles(7, 20.0, 0, 0, 10); //create_horizontal_circles(10, 20.0, 0, 0, 5); create_angle_circles(5, 15.0, 0, 0, 5, 45.0); } // //funcion llamada a cada imagen void glPaint(void) { //El fondo de la escena al color initial glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //(R, G, B, transparencia) en este caso un fondo negro glLoadIdentity(); //dibuja el gizmo displayGizmo(); //doble buffer, mantener esta instruccion al fin de la funcion glutSwapBuffers(); } // //inicializacion de OpenGL // void init_GL(void) { //Color del fondo de la escena glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //(R, G, B, transparencia) en este caso un fondo negro //modo projeccion glMatrixMode(GL_PROJECTION); glLoadIdentity(); } //en el caso que la ventana cambie de tamaņo GLvoid window_redraw(GLsizei width, GLsizei height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0); // todas la informaciones previas se aplican al la matrice del ModelView glMatrixMode(GL_MODELVIEW); } GLvoid window_key(unsigned char key, int x, int y) { switch (key) { case KEY_ESC: exit(0); break; default: break; } } // //el programa principal // int main(int argc, char** argv) { //Inicializacion de la GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(800, 800); //tamaņo de la ventana glutInitWindowPosition(0, 0); //posicion de la ventana glutCreateWindow("TP1 OpenGL : hello_world_OpenGL"); //titulo de la ventana init_GL(); //funcion de inicializacion de OpenGL glutDisplayFunc(glPaint); glutReshapeFunc(&window_redraw); // Callback del teclado glutKeyboardFunc(&window_key); glutMainLoop(); //bucle de rendering return 0; }
#include "stdlib.h" #include "iostream" #include "stdio.h" #include "sstream" #include "serial_port.h" #include "ahrs_serial.h" #include "ros/ros.h" #include "sensor_msgs/Imu.h" #include "sensor_msgs/MagneticField.h" using namespace std; using namespace ros; /***********NOTE: set these define will cause topic frequency drop to 50%***********/ //#define SENSOR_SHOW //#define JUMP_SHOW //#define SERIAL_DATA_SHOW //#define SENSOR_ZERO_CRRECT //#define SENSOR_FILTER //#define CRC_SHOW #define FRAME_COUNTER DECODE_STATUS step; MPUSensor_RAW mpu9250; int fd; ros::Publisher imu_pub; sensor_msgs::Imu imu_msg; sensor_msgs::MagneticField mag_msg; const float accel_range = 4.000000; const float gyro_range = 250.000000; const float magn_range = 1; const float temp_range = 1; const float pressure_range = 1; const float g = 9.80665; const float pi = 3.1415926; char raw_data[12]; int crc_res; int crc_gen; unsigned char crc_l,crc_h; int dat_count; long frame_num; long error_frame_num; unsigned char buff[1]; unsigned char dat; float Camera2ImuDelay = 0.040; /*******************************CRC16 Check code****************************/ int calcByte(int crc, char b) { int i; crc = crc ^ (int)b << 8; for ( i = 0; i < 8; i++) { if ((crc & 0x8000) == 0x8000) crc = crc << 1 ^ 0x1021; else crc = crc << 1; } return crc & 0xffff; } int CRC16(char *pBuffer, int length) { int wCRC16=0; int i; if (( pBuffer==0 )||( length==0 )) { return 0; } for ( i = 0; i < length; i++) { wCRC16 = calcByte(wCRC16, pBuffer[i]); } return wCRC16; } /******************************************************************************/ void decode_loop() { UART_Recv(fd,buff,1); dat = *buff; #ifdef SERIAL_DATA_SHOW printf("dat: %x\n", dat); #endif switch(step) { case WAIT: step = WAIT; break; case FRAME_BEGIN: #ifdef JUMP_SHOW cout << "go to FRAME_BEGIN" << endl; #endif if(dat == 0xaa || dat == 0xbb) { dat_count++; } else { dat_count = 0; } if(dat_count == 2) { step = ACCEL_X; dat_count = 0; } break; case ACCEL_X: #ifdef JUMP_SHOW cout << "go to ACCEL_X" << endl; #endif if(dat_count == 0) { mpu9250.accel_raw.accel_xh = dat; raw_data[0] = dat; dat_count++; } else if(dat_count == 1) { mpu9250.accel_raw.accel_xl = dat; raw_data[1] = dat; mpu9250.accel_raw.accel_X = (((short)mpu9250.accel_raw.accel_xh) << 8) | mpu9250.accel_raw.accel_xl; dat_count = 0; imu_msg.linear_acceleration.x = g*accel_range*(float)mpu9250.accel_raw.accel_X/(float)32768; step = ACCEL_Y; } break; case ACCEL_Y: #ifdef JUMP_SHOW cout << "go to ACCEL_Y" << endl; #endif if(dat_count == 0) { mpu9250.accel_raw.accel_yh = dat; raw_data[2] = dat; dat_count++; } else if(dat_count == 1) { mpu9250.accel_raw.accel_yl = dat; raw_data[3] = dat; mpu9250.accel_raw.accel_Y = (((short)mpu9250.accel_raw.accel_yh) << 8) | mpu9250.accel_raw.accel_yl; dat_count = 0; imu_msg.linear_acceleration.y = g*accel_range*(float)mpu9250.accel_raw.accel_Y/(float)32768; step = ACCEL_Z; } break; case ACCEL_Z: #ifdef JUMP_SHOW cout << "go to ACCEL_Z" << endl; #endif if(dat_count == 0) { mpu9250.accel_raw.accel_zh = dat; raw_data[4] = dat; dat_count++; } else if(dat_count == 1) { mpu9250.accel_raw.accel_zl = dat; raw_data[5] = dat; mpu9250.accel_raw.accel_Z = (((short)mpu9250.accel_raw.accel_zh) << 8) | mpu9250.accel_raw.accel_zl; dat_count = 0; imu_msg.linear_acceleration.z = g*accel_range*(float)mpu9250.accel_raw.accel_Z/(float)32768; step = GYRO_X; } break; case GYRO_X: #ifdef JUMP_SHOW cout << "go to GYRO_X" << endl; #endif if(dat_count == 0) { mpu9250.gyro_raw.gyro_xh = dat; raw_data[6] = dat; //printf("dat: %x-", dat); dat_count++; } else if(dat_count == 1) { mpu9250.gyro_raw.gyro_xl = dat; raw_data[7] = dat; //printf("%x ", dat); mpu9250.gyro_raw.gyro_X = (((short)mpu9250.gyro_raw.gyro_xh) << 8) | mpu9250.gyro_raw.gyro_xl; imu_msg.angular_velocity.x = (pi*gyro_range*(float)mpu9250.gyro_raw.gyro_X/(float)32768)/(float)180; dat_count = 0; step = GYRO_Y; } break; case GYRO_Y: #ifdef JUMP_SHOW cout << "go to GYRO_Y" << endl; #endif if(dat_count == 0) { mpu9250.gyro_raw.gyro_yh = dat; raw_data[8] = dat; //printf("%x-", dat); dat_count++; } else if(dat_count == 1) { mpu9250.gyro_raw.gyro_yl = dat; raw_data[9] = dat; //printf("%x ", dat); mpu9250.gyro_raw.gyro_Y = (((short)mpu9250.gyro_raw.gyro_yh) << 8) | mpu9250.gyro_raw.gyro_yl; imu_msg.angular_velocity.y = (pi*gyro_range * (float)mpu9250.gyro_raw.gyro_Y/(float)32768)/(float)180; dat_count = 0; step = GYRO_Z; } break; case GYRO_Z: #ifdef JUMP_SHOW cout << "go to GYRO_Z" << endl; #endif if(dat_count == 0) { mpu9250.gyro_raw.gyro_zh = dat; raw_data[10] = dat; //printf("%x-", dat); dat_count++; } else if(dat_count == 1) { mpu9250.gyro_raw.gyro_zl = dat; raw_data[11] = dat; //printf("%x\n", dat); mpu9250.gyro_raw.gyro_Z = (((short)mpu9250.gyro_raw.gyro_zh) << 8) | mpu9250.gyro_raw.gyro_zl; imu_msg.angular_velocity.z = (pi*gyro_range * (float)mpu9250.gyro_raw.gyro_Z/(float)32768)/(float)180; dat_count = 0; step = CRC_CHECK; } break; case CRC_CHECK: #ifdef JUMP_SHOW cout << "go to CRC_CHECK" << endl; #endif if(dat_count == 0) { crc_l = dat; dat_count++; } else if(dat_count == 1) { crc_h = dat; crc_res = ((short)crc_h << 8) | crc_l; dat_count = 0; crc_gen = CRC16(raw_data,12); #ifdef CRC_SHOW cout << "crc_res " << crc_res << "--crc_gen " << crc_gen <<endl; #endif if (crc_gen != crc_res) { step = CRC_ERR; } else { #ifdef SENSOR_FILTER step = FRAME_FILTER; #else #ifdef SENSOR_SHOW step = FRAME_SHOW; #else step = FRAME_END; #endif #endif } } break; case FRAME_FILTER: #ifdef JUMP_SHOW cout << "go to FRAME_FILTER" << endl; #endif #ifdef SENSOR_SHOW step = FRAME_SHOW; #else step = FRAME_END; #endif break; case FRAME_SHOW: #ifdef JUMP_SHOW cout << "go to FRAME_SHOW" << endl; #endif // cout<< "accel_X " << mpu9250.accel_raw.accel_X << " " // "accel_Y " << mpu9250.accel_raw.accel_Y << " " // "accel_Z " << mpu9250.accel_raw.accel_Z << endl; // cout<< "gyro_X " << mpu9250.gyro_raw.gyro_X << " " // "gyro_Y " << mpu9250.gyro_raw.gyro_Y << " " // "gyro_Z " << mpu9250.gyro_raw.gyro_Z << endl; cout << imu_msg.linear_acceleration.x << "," << imu_msg.linear_acceleration.y << "," << imu_msg.linear_acceleration.z << "," << imu_msg.angular_velocity.x << "," << imu_msg.angular_velocity.y << "," << imu_msg.angular_velocity.z << endl; step = FRAME_END; break; case FRAME_END: #ifdef JUMP_SHOW cout << "go to FRAME_END" << endl; #endif if(dat == 0xcc || dat == 0xdd) { dat_count++; } else { dat_count = 0; } if(dat_count == 2) { dat_count = 0; imu_msg.orientation.w = 1; imu_msg.header.frame_id = "mpu_9250"; imu_msg.header.seq = frame_num; imu_msg.header.stamp = ros::Time::now()+ros::Duration(Camera2ImuDelay); imu_pub.publish(imu_msg); #ifdef FRAME_COUNTER ROS_INFO("Total frame receive: %ld ", frame_num); //cout << "Total frame receive: " << frame_num << endl; #endif frame_num++; step = FRAME_BEGIN; } break; case CRC_ERR: #ifdef JUMP_SHOW cout << "go to CRC_ERR" << endl; #endif error_frame_num++; ROS_ERROR("CRC16 CHECK ERROR, JUMP TO FRAME BEGIN!"); if(frame_num != 0) cout<<"Frame error rate " << (float)100*(float)error_frame_num/(float)frame_num <<"% ["<<error_frame_num<<"/"<<frame_num<<"]"<<endl; else cout<<"Frame error rate " << 0 <<"["<<error_frame_num<<"/"<<frame_num<<"]"<<endl; step = FRAME_BEGIN; break; } } void usage() { printf( "This is a imu serial data decode programm. \n" "Usage: IMU Serial Decode\n" " -p <serial device> #Serial Device path \"default </dev/ttyUSB0>\"\n" " -b <band speed> #Serial Device band speed \"default <115200>\"\n" " -x <-TODO-> #Advance Parameter still not available \"\n" " -h <help> #Show this useage \"\n" ); } int main(int argc, char ** argv) { ros::init(argc, argv, "imu_data_decode"); ros::NodeHandle n; imu_pub = n.advertise<sensor_msgs::Imu>("ahrs_data",50); // ros::Rate loop_rate(100); // string s1 = "abcdeg"; // const char *k = s1.c_str(); // const char *t = s1.data(); // std::string str = "string"; // char *cstr = new char[str.length() + 1]; // strcpy(cstr, str.c_str()); // // do stuff // delete [] cstr; int band_speed = 115200; string device_s = "/dev/ttyUSB0"; char * device = new char[device_s.length() + 1]; strcpy(device, device_s.c_str()); if(argc <= 1) { usage(); return 0; } /************************************************************************** * get parameter from command line. * * ***********************************************************************/ for(int i = 1; i < argc; i++) { const char* s = argv[i]; if(strcmp( s, "-p" ) == 0) { device = argv[++i]; } else if(strcmp( s, "-b" ) == 0) { char * ss = argv[++i]; band_speed = atoi(ss); } else if(strcmp( s, "-h" ) == 0) { usage(); } else { printf("Unsupport parameter.\n"); usage(); } } cout<< "select port "<< device << endl; fd = UART_Open(fd, device); if(UART_Set(fd, band_speed,0,8,1,'N') == FALSE) { cout << "port set fail" << endl; } step = FRAME_BEGIN; while(n.ok()) { decode_loop(); //ros::spinOnce(); // loop_rate.sleep(); } UART_Close(fd); return 0; }
#include<stdio.h> int orderSearch(int a[], int n, int key) { for (int i = 0; i < n; i ++) { if (a[i] == key) return i; } return -1; } int midSearch(int a[], int n, int key) { int low = 0, high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] == key) return mid; if (a[mid] >= key) high = mid - 1; if (a[mid] <= key) low = mid + 1; } return -1; } int main() { int a[10] = {7,9,78,45,74,12,58,45,125,789}; int b[10] = {7,9,12,45,45,45,74,78,125,789}; printf("%d\n", orderSearch(a, 10, 45)); printf("%d\n", midSearch(b, 10, 45)); }
#include <cassert> #include "LongIdRecord.h" #include <fstream> #include "StreamUtilities.h" using namespace std; using namespace OpenFlight; //------------------------------------------------------------------------- LongIdRecord::LongIdRecord(PrimaryRecord* ipParent) : AncillaryRecord(ipParent) {} //------------------------------------------------------------------------- const string& LongIdRecord::getAsciiId() const { return mAsciiId; } //------------------------------------------------------------------------- bool LongIdRecord::parseRecord(std::ifstream& iRawRecord, int iVersion) { Record::parseRecord(iRawRecord, iVersion); bool ok = true; ok &= readBytes(iRawRecord, getRecordLength() - 4, mAsciiId); return ok; }
// Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Graphic3d_CView_HeaderFile #define _Graphic3d_CView_HeaderFile #include <Aspect_RenderingContext.hxx> #include <Aspect_SkydomeBackground.hxx> #include <Aspect_Window.hxx> #include <Graphic3d_BufferType.hxx> #include <Graphic3d_CubeMap.hxx> #include <Graphic3d_DataStructureManager.hxx> #include <Graphic3d_DiagnosticInfo.hxx> #include <Graphic3d_GraduatedTrihedron.hxx> #include <Graphic3d_NMapOfTransient.hxx> #include <Graphic3d_RenderingParams.hxx> #include <Graphic3d_SequenceOfStructure.hxx> #include <Graphic3d_Structure.hxx> #include <Graphic3d_TextureEnv.hxx> #include <Graphic3d_TypeOfAnswer.hxx> #include <Graphic3d_TypeOfBackfacingModel.hxx> #include <Graphic3d_TypeOfBackground.hxx> #include <Graphic3d_TypeOfShadingModel.hxx> #include <Graphic3d_TypeOfVisualization.hxx> #include <Graphic3d_Vec3.hxx> #include <Graphic3d_ZLayerId.hxx> #include <Graphic3d_ZLayerSettings.hxx> #include <Image_PixMap.hxx> #include <Standard_Address.hxx> #include <Standard_Transient.hxx> #include <TColStd_IndexedDataMapOfStringString.hxx> class Aspect_NeutralWindow; class Aspect_XRSession; class Graphic3d_CView; class Graphic3d_Layer; class Graphic3d_StructureManager; DEFINE_STANDARD_HANDLE (Graphic3d_CView, Graphic3d_DataStructureManager) //! Base class of a graphical view that carries out rendering process for a concrete //! implementation of graphical driver. Provides virtual interfaces for redrawing its //! contents, management of displayed structures and render settings. The source code //! of the class itself implements functionality related to management of //! computed (HLR or "view-dependent") structures. class Graphic3d_CView : public Graphic3d_DataStructureManager { friend class Graphic3d_StructureManager; DEFINE_STANDARD_RTTIEXT(Graphic3d_CView, Graphic3d_DataStructureManager) public: //! Constructor. Standard_EXPORT Graphic3d_CView (const Handle(Graphic3d_StructureManager)& theMgr); //! Destructor. Standard_EXPORT virtual ~Graphic3d_CView(); //! Returns the identification number of the view. Standard_Integer Identification() const { return myId; } //! Activates the view. Maps presentations defined within structure manager onto this view. Standard_EXPORT virtual void Activate(); //! Deactivates the view. Unmaps presentations defined within structure manager. //! The view in deactivated state will ignore actions on structures such as Display(). Standard_EXPORT virtual void Deactivate(); //! Returns the activity flag of the view. Standard_Boolean IsActive() const { return myIsActive; } //! Erases the view and removes from graphic driver. //! No more graphic operations are allowed in this view after the call. Standard_EXPORT virtual void Remove(); //! Returns true if the view was removed. Standard_Boolean IsRemoved() const { return myIsRemoved; } //! Returns camera object of the view. virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; } //! Sets camera used by the view. virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) { myCamera = theCamera; } public: //! Returns default Shading Model of the view; Graphic3d_TypeOfShadingModel_Phong by default. Graphic3d_TypeOfShadingModel ShadingModel() const { return myRenderParams.ShadingModel; } //! Sets default Shading Model of the view. //! Will throw an exception on attempt to set Graphic3d_TypeOfShadingModel_DEFAULT. Standard_EXPORT void SetShadingModel (Graphic3d_TypeOfShadingModel theModel); //! Return backfacing model used for the view; Graphic3d_TypeOfBackfacingModel_Auto by default, //! which means that backface culling is defined by each presentation. Graphic3d_TypeOfBackfacingModel BackfacingModel() const { return myBackfacing; } //! Sets backfacing model for the view. void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) { myBackfacing = theModel; } //! Returns visualization type of the view. Graphic3d_TypeOfVisualization VisualizationType() const { return myVisualization; } //! Sets visualization type of the view. void SetVisualizationType (const Graphic3d_TypeOfVisualization theType) { myVisualization = theType; } //! Switches computed HLR mode in the view Standard_EXPORT void SetComputedMode (const Standard_Boolean theMode); //! Returns the computed HLR mode state Standard_Boolean ComputedMode() const { return myIsInComputedMode; } //! Computes the new presentation of the structure displayed in this view with the type Graphic3d_TOS_COMPUTED. Standard_EXPORT void ReCompute (const Handle(Graphic3d_Structure)& theStructure); //! Invalidates bounding box of specified ZLayerId. Standard_EXPORT void Update (const Graphic3d_ZLayerId theLayerId = Graphic3d_ZLayerId_UNKNOWN); //! Computes the new presentation of the structures displayed in this view with the type Graphic3d_TOS_COMPUTED. Standard_EXPORT void Compute(); //! Returns the set of structures displayed in this view. Standard_EXPORT void DisplayedStructures (Graphic3d_MapOfStructure& theStructures) const; //! Returns number of displayed structures in the view. virtual Standard_Integer NumberOfDisplayedStructures() const { return myStructsDisplayed.Extent(); } //! Returns Standard_True in case if the structure with the given <theStructId> is //! in list of structures to be computed and stores computed struct to <theComputedStruct>. Standard_EXPORT Standard_Boolean IsComputed (const Standard_Integer theStructId, Handle(Graphic3d_Structure)& theComputedStruct) const; //! Returns the bounding box of all structures displayed in the view. //! If theToIncludeAuxiliary is TRUE, then the boundary box also includes minimum and maximum limits //! of graphical elements forming parts of infinite and other auxiliary structures. //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence) //! @return computed bounding box Standard_EXPORT virtual Bnd_Box MinMaxValues (const Standard_Boolean theToIncludeAuxiliary = Standard_False) const; //! Returns the coordinates of the boundary box of all structures in the set <theSet>. //! If <theToIgnoreInfiniteFlag> is TRUE, then the boundary box //! also includes minimum and maximum limits of graphical elements //! forming parts of infinite structures. Standard_EXPORT Bnd_Box MinMaxValues (const Graphic3d_MapOfStructure& theSet, const Standard_Boolean theToIncludeAuxiliary = Standard_False) const; //! Returns the structure manager handle which manage structures associated with this view. const Handle(Graphic3d_StructureManager)& StructureManager() const { return myStructureManager; } private: //! Is it possible to display the structure in the view? Standard_EXPORT Graphic3d_TypeOfAnswer acceptDisplay (const Graphic3d_TypeOfStructure theStructType) const; //! Clears the structure in this view. Standard_EXPORT void Clear (Graphic3d_Structure* theStructure, const Standard_Boolean theWithDestruction); //! Connects the structures. Standard_EXPORT void Connect (const Graphic3d_Structure* theMother, const Graphic3d_Structure* theDaughter); //! Disconnects the structures. Standard_EXPORT void Disconnect (const Graphic3d_Structure* theMother, const Graphic3d_Structure* theDaughter); //! Displays the structure in the view. Standard_EXPORT void Display (const Handle(Graphic3d_Structure)& theStructure); //! Erases the structure from the view. Standard_EXPORT void Erase (const Handle(Graphic3d_Structure)& theStructure); //! Highlights the structure in the view. Standard_EXPORT void Highlight (const Handle(Graphic3d_Structure)& theStructure); //! Transforms the structure in the view. Standard_EXPORT void SetTransform (const Handle(Graphic3d_Structure)& theStructure, const Handle(TopLoc_Datum3D)& theTrsf); //! Suppress the highlighting on the structure <AStructure> //! in the view <me>. Standard_EXPORT void UnHighlight (const Handle(Graphic3d_Structure)& theStructure); //! Returns an index != 0 if the structure have another structure computed for the view <me>. Standard_EXPORT Standard_Integer IsComputed (const Graphic3d_Structure* theStructure) const; Standard_Integer IsComputed (const Handle(Graphic3d_Structure)& theStructure) const { return IsComputed (theStructure.get()); } //! Returns true if the structure is displayed in the view. Standard_EXPORT Standard_Boolean IsDisplayed (const Handle(Graphic3d_Structure)& theStructure) const; //! Changes the display priority of the structure. Standard_EXPORT void ChangePriority (const Handle(Graphic3d_Structure)& theStructure, const Graphic3d_DisplayPriority theOldPriority, const Graphic3d_DisplayPriority theNewPriority); //! Change Z layer of already displayed structure in the view. Standard_EXPORT void ChangeZLayer (const Handle(Graphic3d_Structure)& theStructure, const Graphic3d_ZLayerId theLayerId); //! Returns an index != 0 if the structure have the same owner than another structure //! in the sequence of the computed structures. Standard_EXPORT Standard_Integer HaveTheSameOwner (const Handle(Graphic3d_Structure)& theStructure) const; public: //! Redraw content of the view. virtual void Redraw() = 0; //! Redraw immediate content of the view. virtual void RedrawImmediate() = 0; //! Invalidates content of the view but does not redraw it. virtual void Invalidate() = 0; //! Return true if view content cache has been invalidated. virtual Standard_Boolean IsInvalidated() = 0; //! Handle changing size of the rendering window. Standard_EXPORT virtual void Resized() = 0; //! @param theDrawToFrontBuffer Advanced option to modify rendering mode: //! 1. TRUE. Drawing immediate mode structures directly to the front buffer over the scene image. //! Fast, so preferred for interactive work (used by default). //! However these extra drawings will be missed in image dump since it is performed from back buffer. //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen //! in run-time (in case of slow hardware) and/or tearing may appear. //! So this is strongly recommended to draw only simple (fast) structures. //! 2. FALSE. Drawing immediate mode structures to the back buffer. //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read //! from the back buffer. //! @return previous mode. virtual Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) = 0; //! Creates and maps rendering window to the view. //! @param[in] theParentVIew parent view or NULL //! @param[in] theWindow the window //! @param[in] theContext the rendering context; if NULL the context will be created internally virtual void SetWindow (const Handle(Graphic3d_CView)& theParentVIew, const Handle(Aspect_Window)& theWindow, const Aspect_RenderingContext theContext) = 0; //! Returns the window associated to the view. virtual Handle(Aspect_Window) Window() const = 0; //! Returns True if the window associated to the view is defined. virtual Standard_Boolean IsDefined() const = 0; //! Dump active rendering buffer into specified memory buffer. virtual Standard_Boolean BufferDump (Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType) = 0; //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated. virtual void InvalidateBVHData (const Graphic3d_ZLayerId theLayerId) = 0; //! Add a layer to the view. //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers). //! @param theSettings [in] new layer settings //! @param theLayerAfter [in] id of layer to append new layer before virtual void InsertLayerBefore (const Graphic3d_ZLayerId theNewLayerId, const Graphic3d_ZLayerSettings& theSettings, const Graphic3d_ZLayerId theLayerAfter) = 0; //! Add a layer to the view. //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers). //! @param theSettings [in] new layer settings //! @param theLayerBefore [in] id of layer to append new layer after virtual void InsertLayerAfter (const Graphic3d_ZLayerId theNewLayerId, const Graphic3d_ZLayerSettings& theSettings, const Graphic3d_ZLayerId theLayerBefore) = 0; //! Returns the maximum Z layer ID. //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax(). virtual Standard_Integer ZLayerMax() const = 0; //! Returns the list of layers. virtual const NCollection_List<Handle(Graphic3d_Layer)>& Layers() const = 0; //! Returns layer with given ID or NULL if undefined. virtual Handle(Graphic3d_Layer) Layer (const Graphic3d_ZLayerId theLayerId) const = 0; //! Returns the bounding box of all structures displayed in the Z layer. Standard_EXPORT virtual void InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId); //! Remove Z layer from the specified view. All structures //! displayed at the moment in layer will be displayed in default layer //! ( the bottom-level z layer ). To unset layer ID from associated //! structures use method UnsetZLayer (...). virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) = 0; //! Sets the settings for a single Z layer of specified view. virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId, const Graphic3d_ZLayerSettings& theSettings) = 0; //! Returns zoom-scale factor. Standard_EXPORT Standard_Real ConsiderZoomPersistenceObjects(); //! Returns pointer to an assigned framebuffer object. virtual Handle(Standard_Transient) FBO() const = 0; //! Sets framebuffer object for offscreen rendering. virtual void SetFBO (const Handle(Standard_Transient)& theFbo) = 0; //! Generate offscreen FBO in the graphic library. //! If not supported on hardware returns NULL. virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth, const Standard_Integer theHeight) = 0; //! Remove offscreen FBO from the graphic library virtual void FBORelease (Handle(Standard_Transient)& theFbo) = 0; //! Read offscreen FBO configuration. virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo, Standard_Integer& theWidth, Standard_Integer& theHeight, Standard_Integer& theWidthMax, Standard_Integer& theHeightMax) = 0; //! Change offscreen FBO viewport. virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo, const Standard_Integer theWidth, const Standard_Integer theHeight) = 0; public: //! Copy visualization settings from another view. //! Method is used for cloning views in viewer when its required to create view //! with same view properties. Standard_EXPORT virtual void CopySettings (const Handle(Graphic3d_CView)& theOther); //! Returns current rendering parameters and effect settings. const Graphic3d_RenderingParams& RenderingParams() const { return myRenderParams; } //! Returns reference to current rendering parameters and effect settings. Graphic3d_RenderingParams& ChangeRenderingParams() { return myRenderParams; } public: //! Returns background fill color. virtual Aspect_Background Background() const { return Aspect_Background (myBgColor.GetRGB()); } //! Sets background fill color. virtual void SetBackground (const Aspect_Background& theBackground) { myBgColor.SetRGB (theBackground.Color()); } //! Returns gradient background fill colors. virtual Aspect_GradientBackground GradientBackground() const = 0; //! Sets gradient background fill colors. virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) = 0; //! Returns background image texture map. const Handle(Graphic3d_TextureMap)& BackgroundImage() { return myBackgroundImage; } //! Returns cubemap being set last time on background. const Handle(Graphic3d_CubeMap)& BackgroundCubeMap() const { return myCubeMapBackground; } //! Returns cubemap being set last time on background. const Handle(Graphic3d_CubeMap)& IBLCubeMap() const { return myCubeMapIBL; } //! Sets image texture or environment cubemap as background. //! @param theTextureMap [in] source to set a background; //! should be either Graphic3d_Texture2D or Graphic3d_CubeMap //! @param theToUpdatePBREnv [in] defines whether IBL maps will be generated or not //! (see GeneratePBREnvironment()) virtual void SetBackgroundImage (const Handle(Graphic3d_TextureMap)& theTextureMap, Standard_Boolean theToUpdatePBREnv = Standard_True) = 0; //! Returns background image fill style. virtual Aspect_FillMethod BackgroundImageStyle() const = 0; //! Sets background image fill style. virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) = 0; //! Returns background type. Graphic3d_TypeOfBackground BackgroundType() const { return myBackgroundType; } //! Sets background type. void SetBackgroundType (Graphic3d_TypeOfBackground theType) { myBackgroundType = theType; } //! Returns skydome aspect; const Aspect_SkydomeBackground& BackgroundSkydome() const { return mySkydomeAspect; } //! Sets skydome aspect Standard_EXPORT void SetBackgroundSkydome (const Aspect_SkydomeBackground& theAspect, Standard_Boolean theToUpdatePBREnv = Standard_True); //! Enables or disables IBL (Image Based Lighting) from background cubemap. //! Has no effect if PBR is not used. //! @param[in] theToEnableIBL enable or disable IBL from background cubemap virtual void SetImageBasedLighting (Standard_Boolean theToEnableIBL) = 0; //! Returns environment texture set for the view. const Handle(Graphic3d_TextureEnv)& TextureEnv() const { return myTextureEnvData; } //! Sets environment texture for the view. virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) = 0; public: //! Returns list of lights of the view. virtual const Handle(Graphic3d_LightSet)& Lights() const = 0; //! Sets list of lights for the view. virtual void SetLights (const Handle(Graphic3d_LightSet)& theLights) = 0; //! Returns list of clip planes set for the view. virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const = 0; //! Sets list of clip planes for the view. virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) = 0; //! Fill in the dictionary with diagnostic info. //! Should be called within rendering thread. //! //! This API should be used only for user output or for creating automated reports. //! The format of returned information (e.g. key-value layout) //! is NOT part of this API and can be changed at any time. //! Thus application should not parse returned information to weed out specific parameters. Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict, Graphic3d_DiagnosticInfo theFlags) const = 0; //! Returns string with statistic performance info. virtual TCollection_AsciiString StatisticInformation() const = 0; //! Fills in the dictionary with statistic performance info. virtual void StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const = 0; public: //! Return unit scale factor defined as scale factor for m (meters); 1.0 by default. //! Normally, view definition is unitless, however some operations like VR input requires proper units mapping. Standard_Real UnitFactor() const { return myUnitFactor; } //! Set unit scale factor. Standard_EXPORT void SetUnitFactor (Standard_Real theFactor); //! Return XR session. const Handle(Aspect_XRSession)& XRSession() const { return myXRSession; } //! Set XR session. void SetXRSession (const Handle(Aspect_XRSession)& theSession) { myXRSession = theSession; } //! Return TRUE if there is active XR session. Standard_EXPORT bool IsActiveXR() const; //! Initialize XR session. Standard_EXPORT virtual bool InitXR(); //! Release XR session. Standard_EXPORT virtual void ReleaseXR(); //! Process input. Standard_EXPORT virtual void ProcessXRInput(); //! Compute PosedXRCamera() based on current XR head pose and make it active. Standard_EXPORT void SetupXRPosedCamera(); //! Set current camera back to BaseXRCamera() and copy temporary modifications of PosedXRCamera(). //! Calls SynchronizeXRPosedToBaseCamera() beforehand. Standard_EXPORT void UnsetXRPosedCamera(); //! Returns transient XR camera position with tracked head orientation applied. const Handle(Graphic3d_Camera)& PosedXRCamera() const { return myPosedXRCamera; } //! Sets transient XR camera position with tracked head orientation applied. void SetPosedXRCamera (const Handle(Graphic3d_Camera)& theCamera) { myPosedXRCamera = theCamera; } //! Returns anchor camera definition (without tracked head orientation). const Handle(Graphic3d_Camera)& BaseXRCamera() const { return myBaseXRCamera; } //! Sets anchor camera definition. void SetBaseXRCamera (const Handle(Graphic3d_Camera)& theCamera) { myBaseXRCamera = theCamera; } //! Convert XR pose to world space. //! @param thePoseXR [in] transformation defined in VR local coordinate system, //! oriented as Y-up, X-right and -Z-forward //! @return transformation defining orientation of XR pose in world space gp_Trsf PoseXRToWorld (const gp_Trsf& thePoseXR) const { const Handle(Graphic3d_Camera)& anOrigin = myBaseXRCamera; const gp_Ax3 anAxVr (gp::Origin(), gp::DZ(), gp::DX()); const gp_Ax3 aCameraCS (anOrigin->Eye().XYZ(), -anOrigin->Direction(), -anOrigin->SideRight()); gp_Trsf aTrsfCS; aTrsfCS.SetTransformation (aCameraCS, anAxVr); return aTrsfCS * thePoseXR; } //! Returns view direction in the world space based on XR pose. //! @param thePoseXR [in] transformation defined in VR local coordinate system, //! oriented as Y-up, X-right and -Z-forward gp_Ax1 ViewAxisInWorld (const gp_Trsf& thePoseXR) const { return gp_Ax1 (gp::Origin(), -gp::DZ()).Transformed (PoseXRToWorld (thePoseXR)); } //! Recomputes PosedXRCamera() based on BaseXRCamera() and head orientation. Standard_EXPORT void SynchronizeXRBaseToPosedCamera(); //! Checks if PosedXRCamera() has been modified since SetupXRPosedCamera() //! and copies these modifications to BaseXRCamera(). Standard_EXPORT void SynchronizeXRPosedToBaseCamera(); //! Compute camera position based on XR pose. Standard_EXPORT void ComputeXRPosedCameraFromBase (Graphic3d_Camera& theCam, const gp_Trsf& theXRTrsf) const; //! Update based camera from posed camera by applying reversed transformation. Standard_EXPORT void ComputeXRBaseCameraFromPosed (const Graphic3d_Camera& theCamPosed, const gp_Trsf& thePoseTrsf); //! Turn XR camera direction using current (head) eye position as anchor. Standard_EXPORT void TurnViewXRCamera (const gp_Trsf& theTrsfTurn); public: //! @name obsolete Graduated Trihedron functionality //! Returns data of a graduated trihedron virtual const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() { return myGTrihedronData; } //! Displays Graduated Trihedron. virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) { (void )theTrihedronData; } //! Erases Graduated Trihedron. virtual void GraduatedTrihedronErase() {} //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object. //! @param theMin [in] the minimum point of scene. //! @param theMax [in] the maximum point of scene. virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) { (void )theMin; (void )theMax; } //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; public: //! @name subview properties //! Return TRUE if this is a subview of another view. bool IsSubview() const { return myParentView != nullptr; } //! Return parent View or NULL if this is not a subview. Graphic3d_CView* ParentView() { return myParentView; } //! Return TRUE if this is view performs rendering of subviews and nothing else; FALSE by default. //! By default, view with subviews will render main scene and blit subviews on top of it. //! Rendering of main scene might become redundant in case if subviews cover entire window of parent view. //! This flag allows to disable rendering of the main scene in such scenarios //! without creation of a dedicated V3d_Viewer instance just for composing subviews. bool IsSubviewComposer() const { return myIsSubviewComposer; } //! Set if this view should perform composing of subviews and nothing else. void SetSubviewComposer (bool theIsComposer) { myIsSubviewComposer = theIsComposer; } //! Return subview list. const NCollection_Sequence<Handle(Graphic3d_CView)>& Subviews() const { return mySubviews; } //! Add subview to the list. Standard_EXPORT void AddSubview (const Handle(Graphic3d_CView)& theView); //! Remove subview from the list. Standard_EXPORT bool RemoveSubview (const Graphic3d_CView* theView); //! Return subview position within parent view; Aspect_TOTP_LEFT_UPPER by default. Aspect_TypeOfTriedronPosition SubviewCorner() const { return mySubviewCorner; } //! Set subview position within parent view. void SetSubviewCorner (Aspect_TypeOfTriedronPosition thePos) { mySubviewCorner = thePos; } //! Return subview top-left position relative to parent view in pixels. const Graphic3d_Vec2i& SubviewTopLeft() const { return mySubviewTopLeft; } //! Return TRUE if subview size is set as proportions relative to parent view. bool IsSubViewRelativeSize() const { return mySubviewSize.x() <= 1.0 && mySubviewSize.y() <= 1.0; } //! Return subview dimensions; (1.0, 1.0) by default. //! Values >= 2 define size in pixels; //! Values <= 1.0 define size as fraction of parent view. const Graphic3d_Vec2d& SubviewSize() const { return mySubviewSize; } //! Set subview size relative to parent view. void SetSubviewSize (const Graphic3d_Vec2d& theSize) { mySubviewSize = theSize; } //! Return corner offset within parent view; (0.0,0.0) by default. //! Values >= 2 define offset in pixels; //! Values <= 1.0 define offset as fraction of parent view dimensions. const Graphic3d_Vec2d& SubviewOffset() const { return mySubviewOffset; } //! Set corner offset within parent view. void SetSubviewOffset (const Graphic3d_Vec2d& theOffset) { mySubviewOffset = theOffset; } //! Return subview margins in pixels; (0,0) by default const Graphic3d_Vec2i& SubviewMargins() const { return mySubviewMargins; } //! Set subview margins in pixels. void SetSubviewMargins (const Graphic3d_Vec2i& theMargins) { mySubviewMargins = theMargins; } //! Update subview position and dimensions. Standard_EXPORT void SubviewResized (const Handle(Aspect_NeutralWindow)& theWindow); private: //! Adds the structure to display lists of the view. virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure, const Graphic3d_DisplayPriority thePriority) = 0; //! Erases the structure from display lists of the view. virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) = 0; //! Change Z layer of a structure already presented in view. virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure, const Graphic3d_ZLayerId theNewLayerId) = 0; //! Changes the priority of a structure within its Z layer in the specified view. virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure, const Graphic3d_DisplayPriority theNewPriority) = 0; protected: Standard_Integer myId; Graphic3d_RenderingParams myRenderParams; NCollection_Sequence<Handle(Graphic3d_CView)> mySubviews; //!< list of child views Graphic3d_CView* myParentView; //!< back-pointer to the parent view Standard_Boolean myIsSubviewComposer; //!< flag to skip rendering of viewer contents Aspect_TypeOfTriedronPosition mySubviewCorner; //!< position within parent view Graphic3d_Vec2i mySubviewTopLeft; //!< subview top-left position relative to parent view Graphic3d_Vec2i mySubviewMargins; //!< subview margins in pixels Graphic3d_Vec2d mySubviewSize; //!< subview size Graphic3d_Vec2d mySubviewOffset; //!< subview corner offset within parent view Handle(Graphic3d_StructureManager) myStructureManager; Handle(Graphic3d_Camera) myCamera; Graphic3d_SequenceOfStructure myStructsToCompute; Graphic3d_SequenceOfStructure myStructsComputed; Graphic3d_MapOfStructure myStructsDisplayed; Standard_Boolean myIsInComputedMode; Standard_Boolean myIsActive; Standard_Boolean myIsRemoved; Graphic3d_TypeOfBackfacingModel myBackfacing; Graphic3d_TypeOfVisualization myVisualization; Quantity_ColorRGBA myBgColor; Handle(Graphic3d_TextureMap) myBackgroundImage; Handle(Graphic3d_CubeMap) myCubeMapBackground; //!< Cubemap displayed at background Handle(Graphic3d_CubeMap) myCubeMapIBL; //!< Cubemap used for environment lighting Handle(Graphic3d_TextureEnv) myTextureEnvData; Graphic3d_GraduatedTrihedron myGTrihedronData; Graphic3d_TypeOfBackground myBackgroundType; //!< Current type of background Aspect_SkydomeBackground mySkydomeAspect; Standard_Boolean myToUpdateSkydome; Handle(Aspect_XRSession) myXRSession; Handle(Graphic3d_Camera) myBackXRCamera; //!< camera projection parameters to restore after closing XR session (FOV, aspect and similar) Handle(Graphic3d_Camera) myBaseXRCamera; //!< neutral camera orientation defining coordinate system in which head tracking is defined Handle(Graphic3d_Camera) myPosedXRCamera; //!< transient XR camera orientation with tracked head orientation applied (based on myBaseXRCamera) Handle(Graphic3d_Camera) myPosedXRCameraCopy; //!< neutral camera orientation copy at the beginning of processing input Standard_Real myUnitFactor; //!< unit scale factor defined as scale factor for m (meters) }; #endif // _Graphic3d_CView_HeaderFile
// Created on: 1995-06-13 // Created by: Jacques GOUSSARD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepFeat_MakeCylindricalHole_HeaderFile #define _BRepFeat_MakeCylindricalHole_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <gp_Ax1.hxx> #include <BRepFeat_Status.hxx> #include <TopoDS_Face.hxx> #include <BRepFeat_Builder.hxx> // resolve name collisions with X11 headers #ifdef Status #undef Status #endif //! Provides a tool to make cylindrical holes on a shape. class BRepFeat_MakeCylindricalHole : public BRepFeat_Builder { public: DEFINE_STANDARD_ALLOC //! Empty constructor. BRepFeat_MakeCylindricalHole(); //! Sets the axis of the hole(s). void Init (const gp_Ax1& Axis); //! Sets the shape and axis on which hole(s) will be //! performed. void Init (const TopoDS_Shape& S, const gp_Ax1& Axis); //! Performs every holes of radius <Radius>. This //! command has the same effect as a cut operation //! with an infinite cylinder defined by the given //! axis and <Radius>. Standard_EXPORT void Perform (const Standard_Real Radius); //! Performs evry hole of radius <Radius> located //! between PFrom and PTo on the given axis. If //! <WithControl> is set to Standard_False no control //! are done on the resulting shape after the //! operation is performed. Standard_EXPORT void Perform (const Standard_Real Radius, const Standard_Real PFrom, const Standard_Real PTo, const Standard_Boolean WithControl = Standard_True); //! Performs the first hole of radius <Radius>, in the //! direction of the defined axis. First hole signify //! first encountered after the origin of the axis. If //! <WithControl> is set to Standard_False no control //! are done on the resulting shape after the //! operation is performed. Standard_EXPORT void PerformThruNext (const Standard_Real Radius, const Standard_Boolean WithControl = Standard_True); //! Performs evry holes of radius <Radius> located //! after the origin of the given axis. If //! <WithControl> is set to Standard_False no control //! are done on the resulting shape after the //! operation is performed. Standard_EXPORT void PerformUntilEnd (const Standard_Real Radius, const Standard_Boolean WithControl = Standard_True); //! Performs a blind hole of radius <Radius> and //! length <Length>. The length is measured from the //! origin of the given axis. If <WithControl> is set //! to Standard_False no control are done after the //! operation is performed. Standard_EXPORT void PerformBlind (const Standard_Real Radius, const Standard_Real Length, const Standard_Boolean WithControl = Standard_True); //! Returns the status after a hole is performed. BRepFeat_Status Status() const; //! Builds the resulting shape (redefined from //! MakeShape). Invalidates the given parts of tools //! if any, and performs the result of the local //! operation. Standard_EXPORT void Build(); protected: //! Unhide the base class member to avoid Clang warnings using BRepFeat_Builder::Perform; private: Standard_EXPORT BRepFeat_Status Validate(); gp_Ax1 myAxis; Standard_Boolean myAxDef; BRepFeat_Status myStatus; Standard_Boolean myIsBlind; Standard_Boolean myValidate; TopoDS_Face myTopFace; TopoDS_Face myBotFace; }; #include <BRepFeat_MakeCylindricalHole.lxx> #endif // _BRepFeat_MakeCylindricalHole_HeaderFile
#include "Vector.h" Vector::Vector() { _x = 0; _y = 0; _z = 0; } Vector::Vector(float x, float y, float z) { _x = x; _y = y; _z = z; } float Vector::GetX() const { return _x; } void Vector::SetX(const float x) { _x = x; } float Vector::GetY() const { return _y; } void Vector::SetY(const float y) { _y = y; } float Vector::GetZ() const { return _z; } void Vector::SetZ(const float z) { _z = z; } float Vector::DotProduct(Vector a, Vector b) { // Takes the x, y and z values from both vectors and multiplies them together respectively before adding the results together float x = a.GetX() * b.GetX(); float y = a.GetY() * b.GetY(); float z = a.GetZ() * b.GetZ(); return x + y + z; } Vector Vector::CrossProduct(Vector a, Vector b) { // Given vectors (a1,a2,a3) and (b1,b2,b3) // the cross product is (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) // Which is the same as (aY*bZ - aZ*bY, aZ*bX - aX*bZ, aX*bY - aY*bX) float x = a.GetY() * b.GetZ() - a.GetZ() * b.GetY(); float y = a.GetZ() * b.GetX() - a.GetX() * b.GetZ(); float z = a.GetX() * b.GetY() - a.GetY() * b.GetX(); return Vector(x,y,z); } const Vector Vector::operator-(const Vector& rhs) const { float x = this->GetX() - rhs.GetX(); float y = this->GetY() - rhs.GetY(); float z = this->GetZ() - rhs.GetZ(); return Vector(x, y, z); } Vector& Vector::Copy(const Vector& rhs) { if (this != &rhs) { this->SetX(rhs.GetX()); this->SetY(rhs.GetY()); this->SetZ(rhs.GetZ()); } return *this; } const Vector Vector::GetUnitVector() const { // Gets the length of the vector float x = GetVectorLength(); return Vector(GetX() / x, GetY() / x, GetZ() / x); } float Vector::GetVectorLength() const { return static_cast<float>(sqrt(pow(GetX(), 2) + pow(GetY(), 2) + pow(GetZ(), 2))); } Vector Vector::operator+(const Vector& rhs) { return Vector(_x + rhs.GetX(), _y + rhs.GetY(), _z + rhs.GetZ()); } Vector& Vector::operator=(const Vector& rhs) { if (this != &rhs) { Copy(rhs); } return *this; } void Vector::DivideBy(float f) { _x /= f; _y /= f; _z /= f; }
// // Created by ischelle on 05/05/2021. // #include "Board.hpp" #include <fstream> #include <iostream> #include <istream> #include <sstream> #include <string> namespace pandemic { Board::Board() { //Populate color_map color_map.insert(std::make_pair("Yellow", Color::Yellow)); color_map.insert(std::make_pair("Black", Color::Black)); color_map.insert(std::make_pair("Blue", Color::Blue)); color_map.insert(std::make_pair("Red", Color::Red)); // populate enum_map std::unordered_map<std::string, City> enum_map; std::string file_path = "cities_map.txt"; std::ifstream is(file_path); std::string str; int enum_counter = 0; while (std::getline(is, str)) { size_t index = str.find_first_of(' '); // Tokyo Yellow std::string substr = str.substr(0, index); std::cout << " initializing enum_map with: " << str + "\n"; std::cout << " substr is: " + substr + " with counter " << enum_counter << std::endl; enum_map.insert(std::make_pair(substr, City(enum_counter))); board.insert(std::make_pair(City(enum_counter), CityData{})); enum_counter++; } std::cout << "Finished initialization! \n"; std::ifstream ifs(file_path); str = ""; while (std::getline(ifs, str)) { Color c = Color::Yellow; City cit = City::Algiers; std::istringstream istr(str); std::cout << " ** STARTING NEIGHBOR/COLOR INITIALIZATION ** \n"; int counter = 0; do { std::string sub; istr >> sub; std::cout << "sub is: " + sub + ".\n"; if (sub.empty()) { break; } if (counter == 0) { // Update current city std::cout << " Counter " << counter << " getting city from enum_map\n"; cit = enum_map.at(sub); } if (counter == 1) { // Initialize color std::cout << " Counter " << counter << " getting color from " << sub + ".\n"; c = color_map.at(sub); board.at(cit).col = c; } if (counter > 1) { // Update Neighbors // Neighbors City ni = enum_map.at(sub); // insert neighbor to my city board.at(cit).neighbors.push_front(ni); } counter++; } while (istr); } } bool Board::cured(Color c) { return cured_diseases.find(c) != cured_diseases.end(); } int &Board::operator[](City c) { if (board.find(c) == board.end()) { std::string empty = std::to_string(board.empty()); throw std::invalid_argument("No such city exists " + empty); } return *(board.at(c).level); } bool Board::is_clean() { for(auto &it : board) { if(it.second.level != 0) { return false; } } return true; } void Board::remove_cures() { cured_diseases.clear(); // for testing purposes } std::ostream &operator<<(std::ostream &os, const Board &b) { return os; } } // namespace pandemic
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: inifile.cpp,v 1.4.4.3 2005/02/17 15:29:21 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <nspr/nspr.h> #include <nspr/plstr.h> #include "../skcoreconfig.h" #include "../machine.h" #include "../error.h" #include "../refcount.h" #include "../skptr.h" #include "skfopen.h" #include "file.h" #include "textfile.h" #include "inifile.h" // ------------------------------------------------------------------- // // GetINILine // // reads [token = value] lines from a windows INI file // returns the section, token, value in uppercase // skip blank lines // strips C++ comments // returns false on EOF // // ------------------------------------------------------------------- PRBool IniParser::readIniLine(char** pszSection, char** pszToken, char** pszVal, PRUint32* piLine) { char *p, *q, *r; // check for invalid parameters if(!m_pTextFile || !pszSection || !pszToken || !pszVal) return false; // initialization *pszSection = &m_pszCurrentSection[0]; *pszToken = NULL; *pszVal = NULL; char *pszLine = NULL; SKERR err = noErr; while(err == noErr) { err = m_pTextFile->GetLine(&pszLine); if((err != noErr) || !pszLine) break; // increment line number if applicable if(piLine != NULL) ++*piLine; // strip comments p = PL_strstr(pszLine, "//"); if(p) *p = 0; // right trim for(p = pszLine + PL_strlen(pszLine); p >= pszLine && *p <= 0x20; p--) *p = 0; // left trim for(p = pszLine; *p && *p <= 0x20; p++) {} // section if (*p == '[') { q = PL_strchr(p, ']'); if (q) *q = 0; p++; PL_strncpy(m_pszCurrentSection, p, sizeof(m_pszCurrentSection) - 1); m_pszCurrentSection[sizeof(m_pszCurrentSection) - 1] = '\0'; break; } // look for token = val pairs q = PL_strchr(p, '='); if (!q) { // skip ill-formed lines continue; } // right trim for (r = q ; r >= p && (*r <= 0x20 || *r == '=') ; r--) *r = 0; // found token *pszToken = p; // left trim for (q++; *q <= 0x20; q++) { if (!*q) break; } /* if (!*q) { // skip ill-formed lines SKError(err_invalid, "[IniParser] invalid line: %s", pszLine); continue; } */ // found value *pszVal = q; break; } // true on success return (err == noErr) && pszLine; }
#pragma once #include "EnemyObject.h" class EnemyShobonTower : public EnemyObject { public: EnemyShobonTower(const long x, const long y, const long animeNo); virtual ~EnemyShobonTower(); void Init(); // 初期化 void Move(); // 移動 void Draw(); // 描画 private: float accelY; // 加速度Y float gravity; // 重量 };
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; -*- * * Copyright (C) 2007-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef POSIX_OK_SIGNAL #include "platforms/posix/posix_signal_watcher.h" #ifdef sun /* On sun, actual signal is one-shot, reverting to SIG_DFL, which is terminate; * sun's sigset does what signal does elsewhere, so use it instead. */ #define signal sigset #endif void PosixSignalWatcher::SigClear() { sigemptyset(m_mask); sigemptyset(m_mask + 1); } inline PosixSignalWatcher::SingleSignal *PosixSignalWatcher::Find(int signum) { for (SingleSignal* run = First(); run; run = run->Suc()) if (run->GetSigNum() == signum) return run; return NULL; } inline OP_STATUS PosixSignalWatcher::Add(int signum, PosixSignalListener* listener) { if (SingleSignal* sig = Find(signum)) { listener->Into(sig); return OpStatus::OK; } SingleSignal *fresh = OP_NEW(SingleSignal, (signum, this)); if (fresh == 0) return OpStatus::ERR_NO_MEMORY; OP_STATUS res = fresh->Init(); if (OpStatus::IsSuccess(res)) { fresh->Into(this); listener->Into(fresh); } else OP_DELETE(fresh); return res; } // static OP_STATUS PosixSignalWatcher::Watch(int signum, PosixSignalListener * listener) { if (!g_opera) return OpStatus::ERR_NULL_POINTER; PosixSignalWatcher * vakt = g_opera->posix_module.GetSignalWatcher(); if (!vakt) { vakt = OP_NEW(PosixSignalWatcher, ()); if (vakt == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS res = vakt->Ready(); if (OpStatus::IsSuccess(res)) g_opera->posix_module.SetSignalWatcher(vakt); else { OP_DELETE(vakt); return res; } } else if (vakt->Empty()) // => paused vakt->Resume(); return vakt->Add(signum, listener); } inline void PosixSignalWatcher::SingleSignal::SignalAll() { for (PosixSignalListener *run = First(); run; run = static_cast<PosixSignalListener *>(run->Suc())) run->OnSignalled(m_signum); } void PosixSignalWatcher::OnPressed() { if (Empty()) return; // assert: m_mask[!m_flip] is currently clear m_flip = !m_flip; m_count = 0; /* It's possible for signals to arrive during our calls back to listeners; * and, indeed, while we're scanning a signal mask to see which to have been * relevant lately. Hence the need for two signal masks; we can now report * what's held in m_mask[!m_flip], which was m_mask[m_flip] until we toggled * m_flip and transcribed m_count. We only care about the signals for which * we have listeners; and we may as well purge any signals which used to * have listeners but no longer do. */ SingleSignal* run = First(); while (run) { SingleSignal* next = run->Suc(); if (run->Empty()) { // All its listeners have gone away: kill it ! run->Out(); OP_DELETE(run); } else switch (sigismember(m_mask + !m_flip, run->GetSigNum())) // should be 0 or 1 { case 1: run->SignalAll(); break; default: OP_ASSERT(!"How did a bad signal number get in here ?"); /* A return of -1 means bad signal number, which I read as "not * a member of our set". */ case 0: break; } run = next; } sigemptyset(m_mask + !m_flip); if (m_count != 0) Press(); // We need to do this again already ! } PosixSignalWatcher::SingleSignal::~SingleSignal() { #ifdef POSIX_USE_SIGNAL if (m_prior != SIG_ERR && signal(m_signum, m_prior) == SIG_ERR) #else if (m_prior.sa_handler != SIG_ERR && sigaction(m_signum, &m_prior, NULL)) #endif OP_ASSERT(!"Failed to restore prior signal handler !"); } #ifdef POSIX_USE_SIGNAL inline void PosixSignalWatcher::SingleSignal::Relay() { if (m_prior != SIG_ERR && m_prior != SIG_DFL && m_prior != SIG_IGN && (UINTPTR) m_prior > 0xff) // in case there are further magic values (*m_prior)(m_signum); } inline void PosixSignalWatcher::Witness(int signum) { sigaddset(m_mask + m_flip, signum); m_count++; // FIXME: is it safe to call Find in a signal handler ? if (SingleSignal *sig = Find(signum)) sig->Relay(); Press(); } static void generic_handler(int signum) { if (g_opera) if (PosixSignalWatcher *eye = g_opera->posix_module.GetSignalWatcher()) eye->Witness(signum); } #else inline void PosixSignalWatcher::SingleSignal::Relay(siginfo_t *info, void *data) { if (m_prior.sa_flags & SA_SIGINFO) m_prior.sa_sigaction(m_signum, info, data); else if (m_prior.sa_handler != SIG_ERR && m_prior.sa_handler != SIG_DFL && m_prior.sa_handler != SIG_IGN && (UINTPTR) m_prior.sa_handler > 0xff) // in case there are further magic values (*m_prior.sa_handler)(m_signum); } inline void PosixSignalWatcher::Witness(int signum, siginfo_t *info, void *data) { sigaddset(m_mask + m_flip, signum); m_count++; // FIXME: is it safe to call Find in a signal handler ? if (SingleSignal *sig = Find(signum)) sig->Relay(info, data); Press(); } static void generic_handler(int signum, siginfo_t *info, void *data) { if (g_opera) if (PosixSignalWatcher *eye = g_opera->posix_module.GetSignalWatcher()) eye->Witness(signum, info, data); } /** Transcribe signal mask. * * Effectively does *dst = *src; except that sigset_t may be too big to let us * do that. Sadly, there is no sigcopyset() function in POSIX, so we have to * roll our own. * * @param dst Signal mask to populate. * @param src Signal mask to duplicate. */ static void op_sigcopyset(sigset_t *dst, const sigset_t *src) { #if 1 op_memcpy(dst, src, sizeof(sigset_t)); #else const int sig_max = CHAR_BIT * sizeof(sigset_t); for (int sig = 0; sig < sig_max; sig++) /* FIXME: Mac's sigismember apparently doesn't fail (return -1) when sig * is out of range - it just merrily returns 0. For that matter, do we * know Linux does any better ? Apparently POSIX 1988 specified only 0 * and 1 as returns; a later spec has added the option of failing. */ switch (sigismember(src, sig)) { case 1: sigaddset(dst, sig); break; case 0: break; default: return; } #endif } #endif // POSIX_USE_SIGNAL OP_STATUS PosixSignalWatcher::SingleSignal::Init() { /* An alternative strategy would be to set the process's signal mask, using * pthread_sigmask (or just sigmask if no THREAD_SUPPORT), and have * OnPressed call sigpending() to find out what signals have happened since * last time. It could open up the signal mask with sigsuspend (to let * these signals all happen) then resume blocking them and talk to the * call-backs about them. * * This would have the advantage of not changing the handlers for signals * (which we don't, really, need to do), thereby reducing the scope for * collisions with other things frobbing the signal handlers. */ errno = 0; #ifdef POSIX_USE_SIGNAL m_prior = signal(m_signum, &generic_handler); if (m_prior != SIG_ERR) return OpStatus::OK; #else struct sigaction fresh; fresh.sa_sigaction = &generic_handler; sigemptyset(&(fresh.sa_mask)); // but see below, if run. fresh.sa_flags = SA_SIGINFO; if (sigaction(m_signum, &fresh, &m_prior) == 0) { bool run = false; if (m_prior.sa_flags & SA_SIGINFO) run = true; else if (m_prior.sa_handler != SIG_ERR && m_prior.sa_handler != SIG_DFL && m_prior.sa_handler != SIG_IGN && (UINTPTR) m_prior.sa_handler > 0xff) // in case there are further magic values run = true; if (run) { // We'll recurse into the prior handler, so set mask and flags the way it likes: op_sigcopyset(&fresh.sa_mask, &m_prior.sa_mask); fresh.sa_flags = SA_SIGINFO | m_prior.sa_flags; sigaction(m_signum, &fresh, NULL); } return OpStatus::OK; } // Make sure we know not to ignore m_prior hereafter: m_prior.sa_handler = SIG_ERR; m_prior.sa_flags = 0; #endif switch (errno) { case EINVAL: return OpStatus::ERR_OUT_OF_RANGE; case ENOTSUP: // SA_SIGINFO requires us to set sa_sigaction, not sa_handler. OP_ASSERT(!"This should only happen if we set the SA_SIGINFO flag - which we shouldn't !"); return OpStatus::ERR_NOT_SUPPORTED; } return OpStatus::ERR; } #endif // POSIX_OK_SIGNAL
/* * Copyright (c) 2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_MAKE_ARRAY_H_ #define CPPSORT_DETAIL_MAKE_ARRAY_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <array> #include <cstddef> #include <utility> namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // The constexpr capabilities of std::array are seriously // underpowered in C++14, so we instead fill C arrays in // some algorithms and use the following function to turn // them into std::array template<typename T, std::size_t N, std::size_t... Indices> constexpr auto make_array_impl(T(&arr)[N], std::index_sequence<Indices...>) -> std::array<T, N> { return std::array<T, N>{{ arr[Indices]... }}; } template<typename T, std::size_t N> constexpr auto make_array(T(&arr)[N]) -> std::array<T, N> { using indices = std::make_index_sequence<N>; return make_array_impl(arr, indices{}); } }} #endif // CPPSORT_DETAIL_MAKE_ARRAY_H_
#include <iostream> #include <vector> #include <algorithm> #include <string> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int a, b; std::cin >> a >> b; auto func = [](int n) { int r{}; while (n) { r = r * 10 + n % 10; n /= 10; } return r; }; int ra = func(a), rb = func(b); std::cout << (ra > rb ? ra : rb) << '\n'; return 0; }
#include <iostream> double add(double n, double m) { return n + m; } double subtract(double n, double m) { return n - m; } double multiply(double n, double m) { return n * m; } double divide(double n, double m) { return n / m; } using namespace std; int main() { double n, m; char op; cout << "Enter operation: "; cin >> op; if (op != '+' && op != '-' && op != '*' && op != '/') { cout << "Invalid operation\n"; return -1; } cout << "Enter arg1: "; cin >> n; cout << "Enter arg2: "; cin >> m; switch (op) { case '+': cout << "Result: " << add(n, m) << endl; break; case '-': cout << "Result: " << subtract(n, m) << endl; break; case '*': cout << "Result: " << multiply(n, m) << endl; break; case '/': cout << "Result: " << divide(n, m) << endl; break; default: break; } return 0; }
#ifndef SYNC_H #define SYNC_H #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QTimer> #include "Database.h" namespace Qai { class Sync : public QObject { Q_OBJECT public: explicit Sync(QObject *parent = 0); void setDatabase(Database *database); void start(); signals: private slots: void onFinished(QNetworkReply *reply); void onTimeout(); private: Database *mDatabase; QNetworkAccessManager *mNetworkAccessManager; QTimer *mTimer; }; } #endif // SYNC_H
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, m, h[111][111]; int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, -1, 1}; int add[111][111]; int main() { freopen("forest.in", "r", stdin); freopen("forest.out", "w", stdout); scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) for (int j = 0; j < m; ++j) { scanf("%d", &h[i][j]); } vector< pair<int, int> > q1, q2; vector< pair<int, int> > *curq = &q1, *notcurq = &q2; for (int i = 0; i < n; i++) for (int j = 0; j < m; ++j) { for (int k = 0; k < 4; k++) { int newx = i + dx[k]; int newy = j + dy[k]; if (newx < 0 || newy < 0 || newx >= n || newy >= m) continue; if (h[newx][newy] == h[i][j] + 1) { curq->push_back(make_pair(i, j)); // cerr << i << " " << j << endl; break; } } } int ans = 0; while (!curq->empty()) { cerr << " === " << endl; ++ans; for (int i = 0; i < curq->size(); ++i) { const pair<int, int>& p = curq->operator[](i); ++h[p.first][p.second]; } for (int i = 0; i < curq->size(); ++i) { const pair<int, int>& p = curq->operator[](i); for (int j = 0; j < 4; j++) { int newx = p.first + dx[j]; int newy = p.second + dy[j]; if (newx < 0 || newy < 0 || newx >= n || newy >= m) continue; if (add[p.first][p.second] != ans && h[newx][newy] == h[p.first][p.second] + 1) { add[p.first][p.second] = ans; notcurq->push_back(make_pair(p.first, p.second)); // cerr << p.first << " " << p.second << endl; } if (add[newx][newy] != ans && h[newx][newy] + 1 == h[p.first][p.second]) { add[newx][newy] = ans; notcurq->push_back(make_pair(newx, newy)); // cerr << newx << " " << newy << endl; } } } curq->clear(); swap(notcurq, curq); } printf("%d\n", ans); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { printf("%d ", h[i][j]); } puts(""); } return 0; }
#include "routed.hpp" #include "client.hpp" #include "log.hpp" #include "utils/time_utils.hpp" #include "utils/client_process_mgr.hpp" #include "proto/ss_route.pb.h" namespace nora { namespace route { using client_mgr = client_process_mgr<client>; routed::routed(const shared_ptr<service_thread>& st) : st_(st) { if (!st_) { st_ = make_shared<service_thread>("routed"); st_->start(); } client_mgr::static_init(); } void routed::start() { register_signals(); auto ptt = PTTS_GET_COPY(options, 1); ASSERT(ptt.route_info().ipport_size() > 0); client_mgr::instance().init(ptt.route_info().id()); client_mgr::instance().start(ptt.route_info().ipport(0).ip(), (unsigned short)(ptt.route_info().ipport(0).port())); add_broadcast_route_table_timer(); } void routed::add_broadcast_route_table_timer() { ASSERT(st_); ADD_TIMER( st_, ([this, self = this->shared_from_this()] (auto canceled, const auto& timer) { if (!canceled) { ps::base notice_msg; pd::route_table data; client::serialize_route_table(data); auto *notice = notice_msg.MutableExtension(ps::r2s_sync_route_table::rsrt); *notice->mutable_route_table() = data; client_mgr::instance().broadcast_msg(notice_msg); this->add_broadcast_route_table_timer(); } }), 5s); } void routed::stop() { client_mgr::instance().stop(); clock::instance().stop(); st_->stop(); } void routed::register_signals() { if (!signals_) { signals_ = make_unique<ba::signal_set>(st_->get_service()); signals_->add(SIGTERM); signals_->add(SIGINT); } signals_->async_wait( [this] (auto ec, auto sig) { if (ec) { return; } if (sig == SIGTERM || sig == SIGINT) { ROUTE_ILOG << "received SIGTERM or SIGINT, stop"; signals_->cancel(); this->stop(); } else { this->register_signals(); } }); } } }
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: fs.h,v 1.30.2.3 2005/02/21 14:22:45 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __FS_H_ #define __FS_H_ #define err_fs_invalid 3000 #define err_fs_malloc 3001 class SKFSObject; class SKFSFile; class SKFSDirectory; #define SK_SKFILESYSTEM_IID \ { 0xe9d2b1f1, 0xca0d, 0x455d, \ { 0xb5, 0x8f, 0x57, 0x96, 0xd2, 0xce, 0x3f, 0x4e } } class SKAPI SKFileSystem : public SKTextFile { friend class SKFSDirectory; friend class SKFSFile; public: SK_REFCOUNT_INTF_DEFAULT(SKFileSystem) SK_REFCOUNT_INTF_IID(SKFileSystem, SK_SKFILESYSTEM_IID) SKFileSystem(); // ------------------------------------------------------------------- // configuration interface // it could change when a table manager will be here to handle table // creation // for file configuration virtual SKERR SetFileName(const char* pszFileName, const char *pszDefaultFileName = NULL); // for specific options... virtual SKERR ConfigureItem( char* szSection, char* szToken, char* szValue); // ------------------------------------------------------------------- // user interface SKERR GetRootDir(SKFSDirectory** ppRootDir); SKERR GetDir(const char* pszName, SKFSDirectory** ppDir); SKERR GetDirByPath( const char* pszName, SKFSDirectory** ppDir) { return GetDir(pszName, ppDir);} SKERR GetFile(const char* pszName, SKFSFile** ppFile); SKERR GetFileByPath( const char* pszName, SKFSFile** ppFile) { return GetFile(pszName, ppFile);} SKERR GetObject( const char* pszName, SKFSObject** ppObject); SKERR GetObjectByPath( const char* pszName, SKFSObject** ppObject) { return GetObject(pszName, ppObject);} SKERR GetDir(PRUint32 lIdx, SKFSDirectory** ppDir); SKERR GetFile(PRUint32 lIdx, SKFSFile** ppFile); private: SKERR GetRecordSetField(SKIRecordSet *pRecordSet, const char *pszFieldName, SKIField **ppField); SKERR GetFieldSubField(SKIField *pField, const char *pszSubFieldName, SKIField **ppSubField); skPtr<SKIRecordSet> m_pDirRecordSet; skPtr<SKIField> m_pDirNameField; skPtr<SKIField> m_pDirParentField; skPtr<SKIField> m_pDirChildrenField; skPtr<SKIField> m_pDirChildrenSubField; skPtr<SKIField> m_pDirFilesField; skPtr<SKIField> m_pDirFilesSubField; skPtr<SKIRecordSet> m_pFileRecordSet; skPtr<SKIField> m_pFileNameField; skPtr<SKIField> m_pFileParentField; skPtr<SKIField> m_pFileTitleField; skPtr<SKIField> m_pFileContentField; }; SK_REFCOUNT_DECLARE_INTERFACE(SKFileSystem, SK_SKFILESYSTEM_IID) #define SK_SKFSOBJECT_IID \ { 0x312c2bfe, 0x93c4, 0x4118, \ { 0x88, 0x4f, 0xe3, 0x6d, 0x3e, 0x14, 0x05, 0x1f } } class SKAPI SKFSObject : public SKRefCount { public: SK_REFCOUNT_INTF_IID(SKFSObject, SK_SKFSOBJECT_IID) SKFSObject(SKFileSystem* pFileSystem, SKIRecord* pRecord); virtual ~SKFSObject(); const char* GetSharedName() const { return m_pszName; }; SKERR GetName(char** ppcName) const { *ppcName = PL_strdup(GetSharedName()); return noErr; } const char* GetSharedPath() { if(!m_pszPath) { SKERR err = FetchParents(); SK_ASSERT(err == noErr); if(err == noErr) ComputePath(); } return m_pszPath; }; SKERR GetPath(char** ppcPath) { *ppcPath = PL_strdup(GetSharedPath()); return noErr; } SKERR GetLocation(SKFSDirectory **ppDir); SKERR GetParentDir(SKFSDirectory **ppDir); SKERR GetFSObjectId(PRUint32 *piId); virtual PRPackedBool SharedIsFile() const = 0; virtual SKERR IsFile(PRBool* pBool) const { *pBool = SharedIsFile(); return noErr; } SKERR FetchParents(); protected: virtual SKERR FetchParent() = 0; void ComputePath(); skPtr<SKFileSystem> m_pFileSystem; skPtr<SKIRecord> m_pRecord; skPtr<SKFSDirectory> m_pParentDir; char* m_pszName; char* m_pszPath; public: // This is needed by the skPtr class for a dark reason. This // constructor must NOT be used/called/anythingelse. -- bozo SKFSObject(); }; SK_REFCOUNT_DECLARE_INTERFACE(SKFSObject, SK_SKFSOBJECT_IID) #define SK_SKFSDIRECTORY_IID \ { 0x30653ab1, 0x3845, 0x497d, \ { 0x8c, 0xb7, 0x1b, 0xdc, 0xe5, 0x17, 0x67, 0xf1 } } class SKAPI SKFSDirectory : public SKFSObject { public: SK_REFCOUNT_INTF(SKFSDirectory) SK_REFCOUNT_INTF_CREATOR(SKFSDirectory)(SKFileSystem* pFileSystem, SKIRecord* pRecord); SK_REFCOUNT_INTF_IID(SKFSDirectory, SK_SKFSDIRECTORY_IID) // configuration interface SKFSDirectory(SKFileSystem* pFileSystem, SKIRecord* pRecord) : SKFSObject(pFileSystem, pRecord) { }; virtual ~SKFSDirectory() {}; SKERR Init() { return FetchInfo(); } // user interface SKERR GetDirCount(PRUint32 *plCount) const; SKERR GetDir(PRUint32 lRank, SKFSDirectory** ppDir) const; SKERR GetFileCount(PRUint32 *plCount) const; SKERR GetFile(PRUint32 lRank, SKFSFile** ppFile) const; SKERR GetDir(const char* pszName, SKFSDirectory** ppDir); SKERR GetDirByPath( const char* pszName, SKFSDirectory** ppDir) { return GetDir(pszName, ppDir); } SKERR GetFile(const char* pszName, SKFSFile** ppFile); SKERR GetFileByPath( const char* pszName, SKFSFile** ppFile) { return GetFile(pszName, ppFile); } SKERR GetObject(const char* pszName, SKFSObject** ppObject); SKERR GetObjectByPath(const char* pszName, SKFSObject** ppObject) { return GetObject(pszName, ppObject); } virtual PRPackedBool SharedIsFile() const { return PR_FALSE; } protected: SKERR FetchInfo(); virtual SKERR FetchParent(); private: // This is needed by the skPtr class for a dark reason. This // constructor must NOT be used/called/anythingelse. -- bozo SKFSDirectory(); }; SK_REFCOUNT_DECLARE_INTERFACE(SKFSDirectory, SK_SKFSDIRECTORY_IID) #define SK_SKFSFILE_IID \ { 0xbe9c3845, 0x7d9f, 0x4fb3, \ { 0x8a, 0x4e, 0xfc, 0xfc, 0xea, 0x1b, 0x3b, 0xc9 } } class SKAPI SKFSFile : public SKFSObject { public: SK_REFCOUNT_INTF(SKFSFile) SK_REFCOUNT_INTF_CREATOR(SKFSFile)(SKFileSystem* pFileSystem, SKIRecord* pRecord); SK_REFCOUNT_INTF_IID(SKFSFile, SK_SKFSFILE_IID) SKFSFile(SKFileSystem* pFileSystem, SKIRecord* pRecord) : SKFSObject(pFileSystem, pRecord) {}; virtual ~SKFSFile() {}; SKERR Init() { return FetchInfo(); } // user interface SKERR GetData(SKBinary** ppBinary); SKERR GetTitle(SKBinary** ppBinary); virtual PRPackedBool SharedIsFile() const { return PR_TRUE; } protected: SKERR FetchInfo(); virtual SKERR FetchParent(); private: // This is needed by the skPtr class for a dark reason. This // constructor must NOT be used/called/anythingelse. -- bozo SKFSFile(); }; SK_REFCOUNT_DECLARE_INTERFACE(SKFSFile, SK_SKFSFILE_IID) #define err_fs_fopen 702 #endif
#include <reactor/base/Timestamp.h> #include <reactor/base/SimpleLogger.h> #include <reactor/net/EventLoop.h> #include <reactor/net/TimerId.h> #include <reactor/net/TimerQueue.h> using namespace reactor; using namespace reactor::base; using namespace reactor::net; EventLoop loop; TimerQueue queue(&loop); TimerId id1; TimerId id2; TimerId id3; TimerId id4; void bar() { static int cnt = 0; LOG(Info) << "timer1 " << ++cnt; if (cnt == 10) { LOG(Debug) << "cancel timer 1"; queue.cancel(id1); } } void foo() { static int cnt = 0; LOG(Info) << "timer2 " << ++cnt; if (cnt == 10) { LOG(Debug) << "cancel timer 2"; queue.cancel(id2); } } void cancel() { LOG(Debug) << "cancel invalid timer id"; queue.cancel(id1); queue.cancel(id2); } void quit() { loop.quit(); } int main() { Timestamp now(Timestamp::current()); id1 = queue.add_timer(now.add_seconds(1), bar, 1); id2 = queue.add_timer(now.add_seconds(2), foo, 2); id3 = queue.add_timer(now.add_seconds(21), cancel, 0); id4 = queue.add_timer(now.add_seconds(22), quit, 0); loop.loop(); return 0; }
#ifndef CNASCOM_H #define CNASCOM_H #include <CZ80.h> #include <CImagePtr.h> #include <CRGBA.h> class CNascomPortData; class CNascomRenderer { public: CNascomRenderer() { } virtual ~CNascomRenderer() { } virtual void clear(const CRGBA &bg) = 0; virtual void drawImage(int x, int y, CImagePtr image) = 0; }; class CNascom { public: CNascom(); ~CNascom(); void setInvert(bool invert) { invert_ = invert; } bool getInvert() { return invert_; } void setScale(int scale) { scale_ = scale; } int getScale() const { return scale_; } CZ80 *getZ80() { return &z80_; } static uint getScreenPixelWidth (); static uint getScreenPixelHeight(); static uint getScreenCharWidth () { return 48; } static uint getScreenCharHeight() { return 16; } static uint getCharWidth () { return 8; } static uint getCharHeight() { return 16; } static uint getScreenMemStart() { return 0x0800; } static uint getScreenMemEnd () { return 0x0C00; } static uint getScreenMemLineStart(ushort line_num); bool onScreen(ushort pos, ushort len); bool getScreenPos(ushort pos, int *x, int *y); bool loadChars(const std::string &filename); CImagePtr getCharImage(uchar c); void draw(CNascomRenderer *renderer, int border=2); private: bool loadChars(); bool loadChars(const CImagePtr &image); private: CZ80 z80_; CNascomPortData *port_data_ { nullptr }; bool invert_ { false }; int scale_ { 1 }; bool chars_loaded_ { false }; CImagePtr char_images_[256]; }; #endif
#include "recupPageHTML.hpp" #include <QtCore/QUrl> #include <QtCore/QEventLoop> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> void RecupPageHTML::recuperationAsynchrone( const std::string & inUrl ) { connect( &nam_, SIGNAL( finished( QNetworkReply * ) ), this, SLOT( telechargementPageFini( QNetworkReply * ) ) ); QUrl url; url.setEncodedUrl( inUrl.c_str() ); nam_.get( QNetworkRequest( url ) ); } std::string RecupPageHTML::recuperationSynchrone( const std::string & inUrl ) { QUrl url; url.setEncodedUrl( inUrl.c_str() ); QNetworkReply * reponse; while( 1 ) { reponse = nam_.get( QNetworkRequest( url ) ); QEventLoop eLoop; connect( &nam_, SIGNAL( finished( QNetworkReply * ) ), &eLoop, SLOT( quit() ) ); eLoop.exec(); QUrl redirection = reponse->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl(); if ( redirection.isValid() ) { url = redirection; reponse->deleteLater(); } else { break; } } return telechargementPageFini( reponse ); } std::string RecupPageHTML::telechargementPageFini( QNetworkReply * inReponse ) { QUrl redirection = inReponse->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl(); if ( redirection.isValid() ) { nam_.get( QNetworkRequest( redirection ) ); return ""; } disconnect( &nam_, SIGNAL( finished( QNetworkReply * ) ), this, SLOT( telechargementPageFini( QNetworkReply * ) ) ); erreurReception_ = inReponse->error(); if ( erreurReception_ == QNetworkReply::NoError ) { pageHTML_ = QString( inReponse->readAll() ).toStdString(); emit envoiePage( pageHTML_ ); } else { pageHTML_ = ""; emit erreurTelechargement( inReponse->error() ); } inReponse->deleteLater(); return pageHTML_; }
#include "Animaux.h" //Le constructeur de Animal qui prend un cri, un age et un age Max en paramètres Animal::Animal(string cri,int age,int ageMax) { //on met à jour les variables de la classes grace aux paramètres : this->cri=cri; this->age=age; this->ageMaximum=ageMax; } //le destructeur de Animal : Animal::~Animal() { cout<<"L'animal a ete saigne"<<endl; } //La fonction qui affiche le cri de l'animal : void Animal::crie() { cout<<this->cri<<endl; } //La fonction qui affiche le déplacement de l'animal : void Animal::seDeplace(int nbM) { //on teste si on est encore vivant : if(this->age>=this->ageMaximum){ cout<<"l'animal est mort... il ne bouge donc plus..."<<endl; }else cout<<"L'animal se deplace de "<<nbM<<" metres"<<endl; } //La fonction qui vieillit d'un an l'animal : void Animal::vieillie() { cout<<"je vieilli d'un an..."<<endl; this->age=this->age+1; //on teste si on a dépassé l'age max : if(this->age>=this->ageMaximum){ cout<<"Et je meurt..."<<endl; } } //La fonction qui vieillit de plusieurs années l'animal : void Animal::vieillie(int a) { cout<<"je vieilli de "<<a<<" ans..."<<endl; this->age=this->age+a; //on teste si on a dépassé l'age max : if(this->age>=this->ageMaximum){ cout<<"Et je meurt..."<<endl; } } //La fonction qui permet à l'animal de manger : void Animal::mange() { //on teste si on est encore vivant : if(this->age>=this->ageMaximum){ cout<<"l'animal est mort... il ne peut plus manger..."<<endl; }else{ cout<<"L'animal mange"<<endl; this->crie(); } } //La fonction qui affiche les caractéristiques de base de l'animal : void Animal::affiche() { cout<<endl; cout<<"Le cri de l'animal est : "<<this->cri<<endl; cout<<"L'age de l'animal est : "<<this->age<<endl; cout<<"L'age maximum de l'animal est :"<<this->ageMaximum<<endl; if(this->age>=this->ageMaximum){ cout<<"Je suis mort..."<<endl; } cout<<endl; }
// Copyright (C) 2014, 2015, 2016 Alexander Golant // // This file is part of csys project. This project is free // software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (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, see <http://www.gnu.org/licenses/> #include <cstdlib> #include <sstream> #include "discrete.h" #include "protocol.h" #include "io.h" #include "commac.h" using namespace std; using namespace csys; dI::dI(const char *lbl, int position): dev(lbl, time::Sec1), pos_(position) { prot::type::AI; pair<devMapIterator, bool> ret; ret = deviceMap_.insert(pair<string, dev*>(label_, this)); if (false == ret.second) { exit(1); } timeout_ = time(time::Sec1); time_redge_ = time_global + timeout_; } dI::~dI() { devMapIterator it = deviceMap_.find(label_); if(it != deviceMap_.end()) { delete(it->second); deviceMap_.erase(it); } } void dI::process() { emit_ = false; /* poll IO */ if(!init_) { init_ = true; } /* emulate here state flipping */ if(time_redge_ < time_global) { cs_.state_ = (cs_.state_) ? false : true; time_redge_ = time_global + timeout_; } error_handler(); request_handler(); /* notify CLIENT that something has changed */ if(rts_ || cs_ != ps_) { rts_ = false; emit_ = true; } ps_ = cs_; } /***************** internal methods **********************/ void dI::error_handler() { } void dI::request_handler() { } void dI::serialize() { os_.serialize<char>(cs_.error_); os_.serialize<bool>(cs_.state_); os_.sign_block(label_.c_str()); } void dI::unserialize() { }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "TransactionExtra.h" #include "crypto/chacha8.h" #include "Common/int-util.h" #include "Common/MemoryInputStream.h" #include "Common/StreamTools.h" #include "Common/StringTools.h" #include "Common/Varint.h" #include "CryptoNoteTools.h" #include "Serialization/BinaryOutputStreamSerializer.h" #include "Serialization/BinaryInputStreamSerializer.h" using namespace crypto; using namespace common; namespace cn { bool parseTransactionExtra(const std::vector<uint8_t> &transactionExtra, std::vector<TransactionExtraField> &transactionExtraFields) { transactionExtraFields.clear(); if (transactionExtra.empty()) return true; try { MemoryInputStream iss(transactionExtra.data(), transactionExtra.size()); BinaryInputStreamSerializer ar(iss); int c = 0; while (!iss.endOfStream()) { c = read<uint8_t>(iss); switch (c) { case TX_EXTRA_TAG_PADDING: { size_t size = 1; for (; !iss.endOfStream() && size <= TX_EXTRA_PADDING_MAX_COUNT; ++size) { if (read<uint8_t>(iss) != 0) { return false; // all bytes should be zero } } if (size > TX_EXTRA_PADDING_MAX_COUNT) { return false; } transactionExtraFields.push_back(TransactionExtraPadding{size}); break; } case TX_EXTRA_TAG_PUBKEY: { TransactionExtraPublicKey extraPk; ar(extraPk.publicKey, "public_key"); transactionExtraFields.push_back(extraPk); break; } case TX_EXTRA_NONCE: { TransactionExtraNonce extraNonce; uint8_t size = read<uint8_t>(iss); if (size > 0) { extraNonce.nonce.resize(size); read(iss, extraNonce.nonce.data(), extraNonce.nonce.size()); } transactionExtraFields.push_back(extraNonce); break; } case TX_EXTRA_MERGE_MINING_TAG: { TransactionExtraMergeMiningTag mmTag; ar(mmTag, "mm_tag"); transactionExtraFields.push_back(mmTag); break; } case TX_EXTRA_MESSAGE_TAG: { tx_extra_message message; ar(message.data, "message"); transactionExtraFields.push_back(message); break; } case TX_EXTRA_TTL: { uint8_t size; readVarint(iss, size); TransactionExtraTTL ttl; readVarint(iss, ttl.ttl); transactionExtraFields.push_back(ttl); break; } } } } catch (std::exception &) { return false; } return true; } struct ExtraSerializerVisitor : public boost::static_visitor<bool> { std::vector<uint8_t> &extra; ExtraSerializerVisitor(std::vector<uint8_t> &tx_extra) : extra(tx_extra) {} bool operator()(const TransactionExtraPadding &t) { if (t.size > TX_EXTRA_PADDING_MAX_COUNT) { return false; } extra.insert(extra.end(), t.size, 0); return true; } bool operator()(const TransactionExtraPublicKey &t) { return addTransactionPublicKeyToExtra(extra, t.publicKey); } bool operator()(const TransactionExtraNonce &t) { return addExtraNonceToTransactionExtra(extra, t.nonce); } bool operator()(const TransactionExtraMergeMiningTag &t) { return appendMergeMiningTagToExtra(extra, t); } bool operator()(const tx_extra_message &t) { return append_message_to_extra(extra, t); } bool operator()(const TransactionExtraTTL &t) { appendTTLToExtra(extra, t.ttl); return true; } }; bool writeTransactionExtra(std::vector<uint8_t> &tx_extra, const std::vector<TransactionExtraField> &tx_extra_fields) { ExtraSerializerVisitor visitor(tx_extra); for (const auto &tag : tx_extra_fields) { if (!boost::apply_visitor(visitor, tag)) { return false; } } return true; } PublicKey getTransactionPublicKeyFromExtra(const std::vector<uint8_t> &tx_extra) { std::vector<TransactionExtraField> tx_extra_fields; parseTransactionExtra(tx_extra, tx_extra_fields); TransactionExtraPublicKey pub_key_field; if (!findTransactionExtraFieldByType(tx_extra_fields, pub_key_field)) return boost::value_initialized<PublicKey>(); return pub_key_field.publicKey; } bool addTransactionPublicKeyToExtra(std::vector<uint8_t> &tx_extra, const PublicKey &tx_pub_key) { tx_extra.resize(tx_extra.size() + 1 + sizeof(PublicKey)); tx_extra[tx_extra.size() - 1 - sizeof(PublicKey)] = TX_EXTRA_TAG_PUBKEY; *reinterpret_cast<PublicKey *>(&tx_extra[tx_extra.size() - sizeof(PublicKey)]) = tx_pub_key; return true; } bool addExtraNonceToTransactionExtra(std::vector<uint8_t> &tx_extra, const BinaryArray &extra_nonce) { if (extra_nonce.size() > TX_EXTRA_NONCE_MAX_COUNT) { return false; } size_t start_pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size()); //write tag tx_extra[start_pos] = TX_EXTRA_NONCE; //write len ++start_pos; tx_extra[start_pos] = static_cast<uint8_t>(extra_nonce.size()); //write data ++start_pos; memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size()); return true; } bool appendMergeMiningTagToExtra(std::vector<uint8_t> &tx_extra, const TransactionExtraMergeMiningTag &mm_tag) { BinaryArray blob; if (!toBinaryArray(mm_tag, blob)) { return false; } tx_extra.push_back(TX_EXTRA_MERGE_MINING_TAG); std::copy(reinterpret_cast<const uint8_t *>(blob.data()), reinterpret_cast<const uint8_t *>(blob.data() + blob.size()), std::back_inserter(tx_extra)); return true; } bool getMergeMiningTagFromExtra(const std::vector<uint8_t> &tx_extra, TransactionExtraMergeMiningTag &mm_tag) { std::vector<TransactionExtraField> tx_extra_fields; parseTransactionExtra(tx_extra, tx_extra_fields); return findTransactionExtraFieldByType(tx_extra_fields, mm_tag); } bool append_message_to_extra(std::vector<uint8_t> &tx_extra, const tx_extra_message &message) { BinaryArray blob; if (!toBinaryArray(message, blob)) { return false; } tx_extra.reserve(tx_extra.size() + 1 + blob.size()); tx_extra.push_back(TX_EXTRA_MESSAGE_TAG); std::copy(reinterpret_cast<const uint8_t *>(blob.data()), reinterpret_cast<const uint8_t *>(blob.data() + blob.size()), std::back_inserter(tx_extra)); return true; } std::vector<std::string> get_messages_from_extra(const std::vector<uint8_t> &extra, const crypto::PublicKey &txkey, const crypto::SecretKey *recepient_secret_key) { std::vector<TransactionExtraField> tx_extra_fields; std::vector<std::string> result; if (!parseTransactionExtra(extra, tx_extra_fields)) { return result; } size_t i = 0; for (const auto &f : tx_extra_fields) { if (f.type() != typeid(tx_extra_message)) { continue; } std::string res; if (boost::get<tx_extra_message>(f).decrypt(i, txkey, recepient_secret_key, res)) { result.push_back(res); } ++i; } return result; } void appendTTLToExtra(std::vector<uint8_t> &tx_extra, uint64_t ttl) { std::string ttlData = tools::get_varint_data(ttl); std::string extraFieldSize = tools::get_varint_data(ttlData.size()); tx_extra.reserve(tx_extra.size() + 1 + extraFieldSize.size() + ttlData.size()); tx_extra.push_back(TX_EXTRA_TTL); std::copy(extraFieldSize.begin(), extraFieldSize.end(), std::back_inserter(tx_extra)); std::copy(ttlData.begin(), ttlData.end(), std::back_inserter(tx_extra)); } void setPaymentIdToTransactionExtraNonce(std::vector<uint8_t> &extra_nonce, const Hash &payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID); const uint8_t *payment_id_ptr = reinterpret_cast<const uint8_t *>(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } bool getPaymentIdFromTransactionExtraNonce(const std::vector<uint8_t> &extra_nonce, Hash &payment_id) { if (sizeof(Hash) + 1 != extra_nonce.size()) return false; if (TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast<const Hash *>(extra_nonce.data() + 1); return true; } bool parsePaymentId(const std::string &paymentIdString, Hash &paymentId) { return common::podFromHex(paymentIdString, paymentId); } bool createTxExtraWithPaymentId(const std::string &paymentIdString, std::vector<uint8_t> &extra) { Hash paymentIdBin; if (!parsePaymentId(paymentIdString, paymentIdBin)) { return false; } std::vector<uint8_t> extraNonce; cn::setPaymentIdToTransactionExtraNonce(extraNonce, paymentIdBin); if (!cn::addExtraNonceToTransactionExtra(extra, extraNonce)) { return false; } return true; } bool getPaymentIdFromTxExtra(const std::vector<uint8_t> &extra, Hash &paymentId) { std::vector<TransactionExtraField> tx_extra_fields; if (!parseTransactionExtra(extra, tx_extra_fields)) { return false; } TransactionExtraNonce extra_nonce; if (findTransactionExtraFieldByType(tx_extra_fields, extra_nonce)) { if (!getPaymentIdFromTransactionExtraNonce(extra_nonce.nonce, paymentId)) { return false; } } else { return false; } return true; } #define TX_EXTRA_MESSAGE_CHECKSUM_SIZE 4 #pragma pack(push, 1) struct message_key_data { KeyDerivation derivation; uint8_t magic1, magic2; }; #pragma pack(pop) static_assert(sizeof(message_key_data) == 34, "Invalid structure size"); bool tx_extra_message::encrypt(size_t index, const std::string &message, const AccountPublicAddress *recipient, const KeyPair &txkey) { size_t mlen = message.size(); std::unique_ptr<char[]> buf(new char[mlen + TX_EXTRA_MESSAGE_CHECKSUM_SIZE]); memcpy(buf.get(), message.data(), mlen); memset(buf.get() + mlen, 0, TX_EXTRA_MESSAGE_CHECKSUM_SIZE); mlen += TX_EXTRA_MESSAGE_CHECKSUM_SIZE; if (recipient) { message_key_data key_data; if (!generate_key_derivation(recipient->spendPublicKey, txkey.secretKey, key_data.derivation)) { return false; } key_data.magic1 = 0x80; key_data.magic2 = 0; Hash h = cn_fast_hash(&key_data, sizeof(message_key_data)); uint64_t nonce = SWAP64LE(index); chacha8(buf.get(), mlen, reinterpret_cast<uint8_t *>(&h), reinterpret_cast<uint8_t *>(&nonce), buf.get()); } data.assign(buf.get(), mlen); return true; } bool tx_extra_message::decrypt(size_t index, const crypto::PublicKey &txkey, const crypto::SecretKey *recepient_secret_key, std::string &message) const { size_t mlen = data.size(); if (mlen < TX_EXTRA_MESSAGE_CHECKSUM_SIZE) { return false; } const char *buf; std::unique_ptr<char[]> ptr; if (recepient_secret_key != nullptr) { ptr.reset(new char[mlen]); assert(ptr); message_key_data key_data; if (!generate_key_derivation(txkey, *recepient_secret_key, key_data.derivation)) { return false; } key_data.magic1 = 0x80; key_data.magic2 = 0; Hash h = cn_fast_hash(&key_data, sizeof(message_key_data)); uint64_t nonce = SWAP64LE(index); chacha8(data.data(), mlen, reinterpret_cast<uint8_t *>(&h), reinterpret_cast<uint8_t *>(&nonce), ptr.get()); buf = ptr.get(); } else { buf = data.data(); } mlen -= TX_EXTRA_MESSAGE_CHECKSUM_SIZE; for (size_t i = 0; i < TX_EXTRA_MESSAGE_CHECKSUM_SIZE; i++) { if (buf[mlen + i] != 0) { return false; } } message.assign(buf, mlen); return true; } bool tx_extra_message::serialize(ISerializer &s) { s(data, "data"); return true; } } // namespace cn
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; vector<int> v(n+1); int ans = 0; for(int i=0; i<n; i++){ int a; cin >> a; if(a > n) ans++; else v[a]++; } for(int i=1; i<=n; i++){ if(v[i] >= i) ans += v[i] - i; else ans += v[i]; } cout << ans << endl; return 0; }
#include "Q45.h" BiTree* createBTree(){ /** A * / \ * B C * / \ / \ * D E F G */ vector<char> names = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; vector<int> data = {1, 2, 3, 4, 5, 6, 7}; BiTree* tree = new BiTree(names, data); return tree; } BiTree* createBST(){ vector<char> names = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; vector<int> data = {4, 2, 6, 1, 3, 5, 7}; // bug: BE位置互换时,无法判断为排序树 BiTree* tree = new BiTree(names, data); return tree; } // 4.5-综06:判断二叉树是否是二叉排序树 // 用中序遍历判断是否为升序 int JudgeBST(Node* root, int &pred){ // pred 前驱节点的值,前驱节点一般在左子树上的 int b1, b2; if(!root) return 1; else{ b1 = JudgeBST(root->lChild, pred); if(b1 == 0 || pred >= root->data) // 左子树返回0或前驱节点大于当前节点 return 0; pred = b1; // 保存当前结点的值 b2 = JudgeBST(root->rChild, pred); // 判断右子树 return b2; // 返回右子树的结果 } } void hw06_(){ /** A4 * / \ * B2 C6 * / \ / \ * D1 3E F5 7G */ int pred = -32767; BiTree* tree = createBST(); if(JudgeBST(tree->getRoot(), pred)) cout << "是二叉排序树" << endl; else cout << "不是二叉排序树" << endl; pred = -32767; Node* root2 = createBTree()->getRoot(); if(JudgeBST(root2, pred)) cout << "是二叉排序树" << endl; else cout << "不是二叉排序树" << endl; } // 4.5-综07:求出指定节点在给定二叉排序树中的层次 int findLevel(Node* root, int key){ int n=0; if(root){ Node* t = root; n++; while (t->data != key) { if(t->data < key) t = t->rChild; else t = t->lChild; n++; if(!t) return 0; } } return n; } void hw07_(){ /** A4 * / \ * B2 C6 * / \ / \ * D1 3E F5 7G */ BiTree* tree = createBST(); int level = findLevel(tree->getRoot(), 5); // int level = findLevel(tree->getRoot(), level); cout << "level: " << level << endl; } // 4.5-综08:利用二叉树遍历的思想编写一个判断二叉树是否是平衡二叉树的算法 /** * (1) 高度为0, 空树,平衡 * (2) 高度为1, 只有根节点,平衡 * (3) 对采用后序遍历,返回左右子树的高度和平衡标记,二叉树的高度为最高子树的高度加1. * 若左右子树的高度差大于1,则balance=0; 若左右子树的高度小于等于1,且左右子树都平衡,返回1,否则返回0 */ void JudgeAVL(Node* root, int &balance, int &h){ int bl=0, br=0, hl=0, hr=0; if(root == nullptr){ h = 0; balance = 1; } else if(root->lChild==nullptr && root->rChild==nullptr){ h = 1; balance = 1; } else{ JudgeAVL(root->lChild, bl, hl); JudgeAVL(root->rChild, br, hr); h = (hl > hr ? hl : hr) + 1; if(abs(hl - hr) < 2) balance = bl && br; else balance = 0; } } void hw08_(){ BiTree* tree = createBTree(); int h = 0, balance = 1; Node* root = tree->getRoot(); root->rChild = nullptr; JudgeAVL(root, balance, h); if(balance) cout << "平衡二叉树" << endl; else cout << "非平衡二叉树" << endl; } // 4.5-综09:设计算法,求出给定二叉排序树中最小和最大的关键字 int minKey(Node* root){ if(!root) return -1; while (root->lChild) root = root->lChild; return root->data; } int maxKey(Node* root){ if(!root) return -1; while (root->rChild) root = root->rChild; return root->data; } void hw09_(){ BiTree* tree = createBST(); cout << "最小值:" << minKey(tree->getRoot()) << " 最大值:" << maxKey(tree->getRoot()) << endl; } // 4.5-综10:设计算法,从大到小,输出二叉排序树中所有其值不小与k的关键字 // 中序遍历: 从大小输出值(改变左子树和右子树的访问顺序) void output(Node* root, int key){ if(!root) return; output(root->rChild, key); if (root->data >= key) cout << root->data << ' '; output(root->lChild, key); } void hw10_(){ /** A4 * / \ * B2 C6 * / \ / \ * D1 3E F5 7G */ BiTree* tree = createBST(); Node* root = tree->getRoot(); output(root, 4); cout << endl; }
#pragma once #include "FileManager.h" #include "ICleanUp.h" #include "IUpdate.h" #include <vector> class RenderableObject; class NonRenderableObject; class Renderer:public ICleanUp { private: glm::vec3 cameraPos; static Renderer* instance; std::vector< RenderableObject*> renderObjList; std::vector< NonRenderableObject*> nonrenderObjList; public: static Renderer* GetInstance() { if (instance == 0) { instance = new Renderer(); } return instance; }; void addRenderObject(RenderableObject* obj); void addNonRenderObject(NonRenderableObject* obj); int init(); void update(); void render(); virtual void shutDown() override; void renderUp(); void renderDown(); GLFWwindow* window; };
#include "spell_code.h" #include "../use_code/use_code.h" #include "../define_host.h" #include "../function_host.h" #include "../function_both.h" /* First Circle */ U6O_SPELL_FUNCTION(create_food) { object * myobj2; int amount; if (stormcloakcheck2(x,y,myplr)) { return SPELL_INVALID; } if ((myobj2=OBJfindlast(x,y))){ if (!(obji[sprlnk[myobj2->type&1023]+(myobj2->type>>10)].flags&512)) { return SPELL_INVALID; } /* luteijn: this looks redundant, previous case already applied! */ /* if ((bt[y][x]&1024)==0){ if (!(obji[sprlnk[myobj2->type&1023]+(myobj2->type>>10)].flags&512)) { return SPELL_INVALID; } } */ } /* OK, can create food here */ amount=3+(caster->i>>4)+1; amount=(int)(rnd*amount); if (amount){ myobj2=OBJnew(); myobj2->type=129; //meat myobj2->more2=amount; myobj2->info|=112; //set flags as temp OBJ OBJadd(x,y,myobj2); return SPELL_SUCCESS; } return SPELL_FAILURE; } U6O_SPELL_FUNCTION(detect_magic) { return SPELL_NOTDONE; } U6O_SPELL_FUNCTION(detect_trap) { int x3,y3; int x4; object * myobj2; static txt * t=txtnew(); static txt * t2=txtnew(); if (stormcloakcheck2(x,y,myplr)) { return SPELL_INVALID; } //check for failure here first x3=(int)(rnd*(8+5*1)); x4=(int)(rnd*(caster->i+1)); if (x4<x3) { return SPELL_FAILURE; } x4=0; // counts number of traps found. for (int spellx=-20;spellx<=20;spellx++){ for (int spelly=-16;spelly<=16;spelly++){ // x3=tpx+15+spellx; y3=tpyy+11+spelly; // caster may not be centered on the screen! x3=x+spellx; y3=y+spelly; if ((x3>=0)&&(y3>=0)&&(x3<=2047)&&(y3<=1023)){ if (myobj2=od[y3][x3]){ if (myobj2->type==173){ //trap x4++; myobj2->info|=(1<<9); //make visible }//trap }//myobj2 }//x3,y3 }}//x,y if (x4){ txtset(t,"?"); t->d2[0]=8; txtnumint(t2,x4); txtadd(t,t2); if (x4==1) txtadd(t," trap detected!"); else txtadd(t," traps detected!"); }else{ txtset(t,"?"); t->d2[0]=8; txtadd(t,"No traps detected."); } NET_send(NETplayer,myplr->net,t); return SPELL_SUCCESS; } U6O_SPELL_FUNCTION(dispel_magic) { return SPELL_NOTDONE; } U6O_SPELL_FUNCTION(douse) { object *myobj2; unsigned long special_effect; int x1; int x2; int x3; int x4; if (stormcloakcheck2(x,y,myplr)) { return SPELL_INVALID; } if (myobj2=OBJfindlast(x,y)){ x3=myobj2->type&1023; x4=myobj2->type>>10; switch (x3) { case 206: //brazier if (x4>1) { //holy flames, no touch return SPELL_FAILURE; } //fall through on purpose case 253: //campfire case 164: //fireplace case 122: //candle case 145: //candelabra case 223: //powder keg x1=(int)(rnd*(8+5*1)); x2=(int)(rnd*(caster->i+1)); if (x2<x1){ //fail return SPELL_FAILURE; } OBJsave(myobj2->x,myobj2->y); if (x4&1) { if (x3==223) { //powder keg special more value. myobj2->more2=myplr->id; } use_basic_toggle(NULL,myobj2); } break; default: return SPELL_INVALID; } special_effect=SFnew(x,y); //destination is more important than the source sf[special_effect].type=SF_BLUE_BOLT; if ( (myobj2=npc_to_obj(caster,myplr)) ) { // get the corresponding npc pointer. sf[special_effect].x=myobj2->x; /* the caster's x and y */ sf[special_effect].y=myobj2->y; } else { sf[special_effect].x=x; /* appear right at the target instead */ sf[special_effect].y=y; } sf[special_effect].x2=x; sf[special_effect].y2=y; sf[special_effect].more=0xFFFF; sf[special_effect].wait=1; return SPELL_SUCCESS; } return SPELL_INVALID; } U6O_SPELL_FUNCTION(explosion) { return 0; } U6O_SPELL_FUNCTION(harm) { return 0; } U6O_SPELL_FUNCTION(heal) { return 0; } U6O_SPELL_FUNCTION(help) { return 0; } U6O_SPELL_FUNCTION(ignite) { object *myobj2; unsigned long special_effect; int x1; int x2; int x3; int x4; if (stormcloakcheck2(x,y,myplr)) { return SPELL_INVALID; } if (myobj2=OBJfindlast(x,y)){ x3=myobj2->type&1023; x4=myobj2->type>>10; switch (x3) { case 206: //brazier if (x4>1) { //holy flames, no touch return SPELL_FAILURE; } //fall through on purpose case 253: //campfire case 164: //fireplace case 122: //candle case 145: //candelabra case 223: //powder keg case 53: //web x1=(int)(rnd*(8+5*1)); x2=(int)(rnd*(caster->i+1)); if (x2<x1){ //fail return SPELL_SUCCESS; } OBJsave(myobj2->x,myobj2->y); //if (!x4&1){ //original thing. suspect operator precendence issues //if (!x4&1 || ((x3==164) && (x4==2))){ //fix for fireplace if (!(x4&1)){ // fix for operator precedence thing. we want to check if bit 1 of x4 (0,1,2,3) is not set, not if bit 1 is set on the negated version of x4 (which will be 1 or 0) if (x3==223) { //powder keg myobj2->info|=7680; //1111000000000 obj reserved timer myobj2->more2=tplayer->id; stealing(tplayer,myobj2); } else if (x3==53){ //web /* luteijn: does x4&1 have to be 0? mose: doesn't have to be 0, but atm it doesn't get another values, but in future it might change so its probably a good idea to keep it inside the check */ VLNKremove(myobj2); OBJremove(myobj2); myobj2=NULL; } else { use_basic_toggle(NULL,myobj2); } } break; default: return SPELL_INVALID; } special_effect=SFnew(x,y); //destination is more important than the source sf[special_effect].type=SF_RED_BOLT; if ( (myobj2=npc_to_obj(caster,myplr)) ) { // get the corresponding npc pointer. sf[special_effect].x=myobj2->x; /* the caster's x and y */ sf[special_effect].y=myobj2->y; } else { sf[special_effect].x=x; /* appear right at the target instead */ sf[special_effect].y=y; } sf[special_effect].x2=x; sf[special_effect].y2=y; sf[special_effect].more=0xFFFF; sf[special_effect].wait=1; return SPELL_SUCCESS; } return SPELL_INVALID; } U6O_SPELL_FUNCTION(light) { return 0; } /* Second Circle */ U6O_SPELL_FUNCTION(infravision) { return 0; } U6O_SPELL_FUNCTION(magic_arrow) { return 0; } U6O_SPELL_FUNCTION(poison) { return 0; } U6O_SPELL_FUNCTION(reappear) { return 0; } U6O_SPELL_FUNCTION(sleep) { return 0; } U6O_SPELL_FUNCTION(telekinesis) { object *myobj2; int x3; int x4; if (stormcloakcheck2(x,y,myplr)) { return SPELL_INVALID; } myobj2=OBJfindlast(x,y); if (myobj2){ switch (myobj2->type&1023) { case 268: //lever case 174: //switch case 288: //crank x3=(int)rnd*(8+5*2); x4=(int)rnd*(caster->i+1); if (x4>=x3){ use_toggle(NULL,myobj2); return SPELL_SUCCESS; } return SPELL_FAILURE; break; //lever, switch or crank default: //other objects are not yet implemented. refund. return SPELL_INVALID; } }//myobj2 return SPELL_INVALID; //should be targeting an object. } U6O_SPELL_FUNCTION(trap) { return 0; } U6O_SPELL_FUNCTION(unlock_magic) { return 0; } U6O_SPELL_FUNCTION(untrap) { return 0; } U6O_SPELL_FUNCTION(vanish) { return 0; } /* Third Circle */ /* Fourth Circle */ /* Fifth Circle */ /* Sixth Circle */ /* Seventh Circle */ /* Eight Circle */ U6O_SPELL_FUNCTION(armageddon) { /* placeholder */ return 0; } /* Original spells and reagents (using originals reagent bit values) # First Circle # Create Food IMY 0x61 # Harm AM 0x12 # Detect Magic WO 0x82 # Heal IM 0x50 # Detect Trap WJ 0x82 # Help KL 0x00 # Dispel Magic AJO 0x60 # Ignite IF 0x84 # Douse AF 0x24 # Light IL 0x80 # # Second Circle # Infravision QL 0x82 # Telekinesis OPY 0x0d # Magic Arrow OJ 0x84 # Trap IJ 0x12 # Poison INP 0x0e # Unlock Magic EP 0x88 # Reappear IY 0x1c # Untrap AJ 0x88 # Sleep IZ 0x16 # Vanish AY 0x2c # # Third Circle # Curse AS 0xa2 # Mass Awaken AVZ 0x60 # Dispel Field AG 0x84 # Mass Sleep VZ 0x52 # Fireball PF 0x84 # Peer VWY 0x03 # Great Light VL 0x81 # Protection IS 0xe0 # Lock AP 0xa8 # Repel Undead AXC 0xa0 # # Fourth Circle # Animate OY 0x89 # Locate IW 0x02 # Conjure KX 0x11 # Mass Dispel VAJO 0x60 # Disable AVM 0x13 # Poison Field ING 0x56 # Fire Field IFG 0x94 # Sleep Field IZG 0x54 # Great Heal VM 0x51 # Wind Change RH 0x88 # # Fifth Circle # Energy Field ISG 0x15 # Paralyze AXP 0x96 # Explosion VPF 0x8d # Pickpocket PY 0x1a # Insect Swarm KBX 0x98 # Reveal ASL 0x13 # Invisibility SL 0x0a # Seance KMC 0x9b # Lightning OG 0x85 # X-ray WY 0x81 # # Sixth Circle # Charm AXE 0x16 # Mass Protect VIS 0xe8 # Clone IQX 0xdb # Negate Magic AO 0xa1 # Confuse VQ 0x03 # Poison Wind NH 0x8a # Flame Wind FH 0x89 # Replicate IQY 0xda # Hail Storm KDY 0x0d # Web IDP 0x10 # # Seventh Circle # Chain Bolt VOG 0x8d # Kill IC 0x86 # Enchant IOY 0x91 # Mass Curse VAS 0xa3 # Energy Wind GH 0x8b # Mass Invis VSL 0x0f # Fear QC 0x23 # Wing Strike KOX 0x99 # Gate Travel VRP 0x85 # Wizard Eye POW 0x9f # # Eighth Circle # Armageddon VCBM 0xff # Resurrect IMC 0xf9 # Death Wind CH 0x8b # Slime VRX 0x0b # Eclipse VAL 0xab # Summon KXC 0x39 # Mass Charm VAXE 0x17 # Time Stop AT 0x29 # Mass Kill VC 0x87 # Tremor VPY 0x89 */
#include "error.hh" using namespace ten; template <typename Result> msgpack::object return_thunk(const std::function<Result ()> &f, msgpack::object &o, msgpack::zone *z) { if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 0) throw errorx("wrong number of method params. expected %d got %d.", 0, o.via.array.size); Result r = f(); return msgpack::object(r, z); } template <typename Result, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result>, f); } template <typename Result, typename A0> msgpack::object return_thunk(const std::function<Result (A0)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 1) throw errorx("wrong number of method params. expected %d got %d.", 1, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); Result r = f(p.a0); return msgpack::object(r, z); } template <typename Result, typename A0, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0>, f, _1); } template <typename Result, typename A0, typename A1> msgpack::object return_thunk(const std::function<Result (A0, A1)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 2) throw errorx("wrong number of method params. expected %d got %d.", 2, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); Result r = f(p.a0, p.a1); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1>, f, _1, _2); } template <typename Result, typename A0, typename A1, typename A2> msgpack::object return_thunk(const std::function<Result (A0, A1, A2)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 3) throw errorx("wrong number of method params. expected %d got %d.", 3, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); Result r = f(p.a0, p.a1, p.a2); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2>, f, _1, _2, _3); } template <typename Result, typename A0, typename A1, typename A2, typename A3> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 4) throw errorx("wrong number of method params. expected %d got %d.", 4, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); Result r = f(p.a0, p.a1, p.a2, p.a3); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3>, f, _1, _2, _3, _4); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3, A4)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; A4 a4; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 5) throw errorx("wrong number of method params. expected %d got %d.", 5, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); o.via.array.ptr[4].convert(&p.a4); Result r = f(p.a0, p.a1, p.a2, p.a3, p.a4); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3, A4>, f, _1, _2, _3, _4, _5); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3, A4, A5)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 6) throw errorx("wrong number of method params. expected %d got %d.", 6, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); o.via.array.ptr[4].convert(&p.a4); o.via.array.ptr[5].convert(&p.a5); Result r = f(p.a0, p.a1, p.a2, p.a3, p.a4, p.a5); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3, A4, A5>, f, _1, _2, _3, _4, _5, _6); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3, A4, A5, A6)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; A6 a6; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 7) throw errorx("wrong number of method params. expected %d got %d.", 7, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); o.via.array.ptr[4].convert(&p.a4); o.via.array.ptr[5].convert(&p.a5); o.via.array.ptr[6].convert(&p.a6); Result r = f(p.a0, p.a1, p.a2, p.a3, p.a4, p.a5, p.a6); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3, A4, A5, A6>, f, _1, _2, _3, _4, _5, _6, _7); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3, A4, A5, A6, A7)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; A6 a6; A7 a7; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 8) throw errorx("wrong number of method params. expected %d got %d.", 8, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); o.via.array.ptr[4].convert(&p.a4); o.via.array.ptr[5].convert(&p.a5); o.via.array.ptr[6].convert(&p.a6); o.via.array.ptr[7].convert(&p.a7); Result r = f(p.a0, p.a1, p.a2, p.a3, p.a4, p.a5, p.a6, p.a7); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3, A4, A5, A6, A7>, f, _1, _2, _3, _4, _5, _6, _7, _8); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> msgpack::object return_thunk(const std::function<Result (A0, A1, A2, A3, A4, A5, A6, A7, A8)> &f, msgpack::object &o, msgpack::zone *z) { struct params { A0 a0; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; A6 a6; A7 a7; A8 a8; }; params p; if (o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } if (o.via.array.size != 9) throw errorx("wrong number of method params. expected %d got %d.", 9, o.via.array.size); o.via.array.ptr[0].convert(&p.a0); o.via.array.ptr[1].convert(&p.a1); o.via.array.ptr[2].convert(&p.a2); o.via.array.ptr[3].convert(&p.a3); o.via.array.ptr[4].convert(&p.a4); o.via.array.ptr[5].convert(&p.a5); o.via.array.ptr[6].convert(&p.a6); o.via.array.ptr[7].convert(&p.a7); o.via.array.ptr[8].convert(&p.a8); Result r = f(p.a0, p.a1, p.a2, p.a3, p.a4, p.a5, p.a6, p.a7, p.a8); return msgpack::object(r, z); } template <typename Result, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename F> std::function<msgpack::object (msgpack::object &o, msgpack::zone *z)> thunk(F *f) { using namespace std::placeholders; return std::bind(return_thunk<Result, A0, A1, A2, A3, A4, A5, A6, A7, A8>, f, _1, _2, _3, _4, _5, _6, _7, _8, _9); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Portability.h> #include <quic/codec/PacketNumber.h> #include <quic/codec/QuicInteger.h> #include <quic/codec/Types.h> #include <quic/common/BufAccessor.h> #include <quic/common/BufUtil.h> #include <quic/handshake/HandshakeLayer.h> namespace quic { // maximum length of packet length. constexpr auto kMaxPacketLenSize = sizeof(uint16_t); // We reserve 2 bytes for packet length in the long headers constexpr auto kReservedPacketLenSize = sizeof(uint16_t); // We reserve 4 bytes for packet number in the long headers. constexpr auto kReservedPacketNumSize = kMaxPacketNumEncodingSize; // Note a full PacketNum has 64 bits, but LongHeader only uses 32 bits of them // This is based on Draft-22 constexpr auto kLongHeaderHeaderSize = sizeof(uint8_t) /* Type bytes */ + sizeof(QuicVersionType) /* Version */ + 2 * sizeof(uint8_t) /* DCIL + SCIL */ + kDefaultConnectionIdSize * 2 /* 2 connection IDs */ + kReservedPacketLenSize /* minimal size of length */ + kReservedPacketNumSize /* packet number */; // Appender growth byte size for in PacketBuilder: constexpr size_t kAppenderGrowthSize = 100; class PacketBuilderInterface { public: virtual ~PacketBuilderInterface() = default; // TODO: Temporarily let this interface be reusable across different concrete // builder types. But this isn't optimized for builder that writes both header // and body into a continuous memory. struct Packet { RegularQuicWritePacket packet; Buf header; Buf body; Packet(RegularQuicWritePacket packetIn, Buf headerIn, Buf bodyIn) : packet(std::move(packetIn)), header(std::move(headerIn)), body(std::move(bodyIn)) {} }; FOLLY_NODISCARD virtual uint32_t remainingSpaceInPkt() const = 0; virtual void encodePacketHeader() = 0; // Functions to write bytes to the packet virtual void writeBE(uint8_t data) = 0; virtual void writeBE(uint16_t data) = 0; virtual void writeBE(uint64_t data) = 0; virtual void write(const QuicInteger& quicInteger) = 0; virtual void appendBytes(PacketNum value, uint8_t byteNumber) = 0; virtual void appendBytes(BufAppender& appender, PacketNum value, uint8_t byteNumber) = 0; virtual void appendBytes(BufWriter& writer, PacketNum value, uint8_t byteNumber) = 0; virtual void insert(std::unique_ptr<folly::IOBuf> buf) = 0; virtual void insert(std::unique_ptr<folly::IOBuf> buf, size_t limit) = 0; virtual void insert(const BufQueue& buf, size_t limit) = 0; virtual void push(const uint8_t* data, size_t len) = 0; // Append a frame to the packet. virtual void appendFrame(QuicWriteFrame frame) = 0; virtual void appendPaddingFrame() = 0; virtual void markNonEmpty() = 0; // Returns the packet header for the current packet. FOLLY_NODISCARD virtual const PacketHeader& getPacketHeader() const = 0; virtual void accountForCipherOverhead(uint8_t overhead) = 0; /** * Whether the packet builder is able to build a packet. This should be * checked right after the creation of a packet builder object. */ FOLLY_NODISCARD virtual bool canBuildPacket() const noexcept = 0; /** * Return an estimated header bytes count. * * For short header, this is the exact header bytes. For long header, since * the writing of packet length and packet number field are deferred to the * buildPacket() call, this is an estimate header bytes count that's the sum * of header bytes already written, the maximum possible packet length field * bytes count and packet number field bytes count. */ FOLLY_NODISCARD virtual uint32_t getHeaderBytes() const = 0; FOLLY_NODISCARD virtual bool hasFramesPending() const = 0; virtual Packet buildPacket() && = 0; virtual void releaseOutputBuffer() && = 0; }; /** * Build packet into user provided IOBuf */ class InplaceQuicPacketBuilder final : public PacketBuilderInterface { public: ~InplaceQuicPacketBuilder() override; InplaceQuicPacketBuilder( BufAccessor& bufAccessor, uint32_t remainingBytes, PacketHeader header, PacketNum largestAckedPacketNum, uint8_t frameHint = 8); // PacketBuilderInterface FOLLY_NODISCARD uint32_t remainingSpaceInPkt() const override; void encodePacketHeader() override; void writeBE(uint8_t data) override; void writeBE(uint16_t data) override; void writeBE(uint64_t data) override; void write(const QuicInteger& quicInteger) override; void appendBytes(PacketNum value, uint8_t byteNumber) override; void appendBytes(BufAppender&, PacketNum, uint8_t) override { CHECK(false) << "Invalid appender"; } void appendBytes(BufWriter& writer, PacketNum value, uint8_t byteNumber) override; void insert(std::unique_ptr<folly::IOBuf> buf) override; void insert(std::unique_ptr<folly::IOBuf> buf, size_t limit) override; void insert(const BufQueue& buf, size_t limit) override; void push(const uint8_t* data, size_t len) override; void appendFrame(QuicWriteFrame frame) override; void appendPaddingFrame() override; void markNonEmpty() override; FOLLY_NODISCARD const PacketHeader& getPacketHeader() const override; PacketBuilderInterface::Packet buildPacket() && override; FOLLY_NODISCARD bool canBuildPacket() const noexcept override; void accountForCipherOverhead(uint8_t overhead) noexcept override; FOLLY_NODISCARD uint32_t getHeaderBytes() const override; FOLLY_NODISCARD bool hasFramesPending() const override; void releaseOutputBuffer() && override; private: void releaseOutputBufferInternal(); private: BufAccessor& bufAccessor_; Buf iobuf_; BufWriter bufWriter_; uint32_t remainingBytes_; PacketNum largestAckedPacketNum_; RegularQuicWritePacket packet_; uint32_t cipherOverhead_{0}; folly::Optional<PacketNumEncodingResult> packetNumberEncoding_; // The offset in the IOBuf writable area to write Packet Length. size_t packetLenOffset_{0}; // The offset in the IOBuf writable area to write Packet Number. size_t packetNumOffset_{0}; // The position to write body. const uint8_t* bodyStart_{nullptr}; // The position to write header. const uint8_t* headerStart_{nullptr}; }; /** * Build packet into IOBufs created by Builder */ class RegularQuicPacketBuilder final : public PacketBuilderInterface { public: ~RegularQuicPacketBuilder() override = default; RegularQuicPacketBuilder(RegularQuicPacketBuilder&&) = default; using Packet = PacketBuilderInterface::Packet; RegularQuicPacketBuilder( uint32_t remainingBytes, PacketHeader header, PacketNum largestAckedPacketNum, uint8_t frameHint = 8); FOLLY_NODISCARD uint32_t getHeaderBytes() const override; void encodePacketHeader() override; // PacketBuilderInterface FOLLY_NODISCARD uint32_t remainingSpaceInPkt() const override; void writeBE(uint8_t data) override; void writeBE(uint16_t data) override; void writeBE(uint64_t data) override; void write(const QuicInteger& quicInteger) override; void appendBytes(PacketNum value, uint8_t byteNumber) override; void appendBytes(BufAppender& appender, PacketNum value, uint8_t byteNumber) override; void appendBytes(BufWriter&, PacketNum, uint8_t) override { CHECK(false) << "Invalid BufWriter"; } void insert(std::unique_ptr<folly::IOBuf> buf) override; void insert(std::unique_ptr<folly::IOBuf> buf, size_t limit) override; void insert(const BufQueue& buf, size_t limit) override; void push(const uint8_t* data, size_t len) override; void appendFrame(QuicWriteFrame frame) override; void appendPaddingFrame() override; void markNonEmpty() override; FOLLY_NODISCARD const PacketHeader& getPacketHeader() const override; Packet buildPacket() && override; /** * Whether the packet builder is able to build a packet. This should be * checked right after the creation of a packet builder object. */ FOLLY_NODISCARD bool canBuildPacket() const noexcept override; void accountForCipherOverhead(uint8_t overhead) noexcept override; FOLLY_NODISCARD bool hasFramesPending() const override; void releaseOutputBuffer() && override; private: void encodeLongHeader( const LongHeader& longHeader, PacketNum largestAckedPacketNum); void encodeShortHeader( const ShortHeader& shortHeader, PacketNum largestAckedPacketNum); private: uint32_t remainingBytes_; PacketNum largestAckedPacketNum_; RegularQuicWritePacket packet_; std::unique_ptr<folly::IOBuf> header_; std::unique_ptr<folly::IOBuf> body_; BufAppender headerAppender_; BufAppender bodyAppender_; uint32_t cipherOverhead_{0}; folly::Optional<PacketNumEncodingResult> packetNumberEncoding_; }; /** * A less involving interface for packet builder, this enables polymorphism * for wrapper-like packet builders (e.g. RegularSizeEnforcedPacketBuilder). */ class WrapperPacketBuilderInterface { public: using Packet = PacketBuilderInterface::Packet; virtual ~WrapperPacketBuilderInterface() = default; FOLLY_NODISCARD virtual bool canBuildPacket() const noexcept = 0; virtual Packet buildPacket() && = 0; }; /** * This builder will enforce the packet size by appending padding frames for * chained memory. This means appending IOBuf at the end of the chain. The * caller should ensure canBuildPacket() returns true before constructing the * builder. */ class RegularSizeEnforcedPacketBuilder : public WrapperPacketBuilderInterface { public: using Packet = PacketBuilderInterface::Packet; explicit RegularSizeEnforcedPacketBuilder( Packet packet, uint64_t enforcedSize, uint32_t cipherOverhead); /** * Returns true when packet has short header, and that enforced size > * current packet size + cipher overhead, otherwise false */ FOLLY_NODISCARD bool canBuildPacket() const noexcept override; Packet buildPacket() && override; private: RegularQuicWritePacket packet_; Buf header_; Buf body_; BufAppender bodyAppender_; uint64_t enforcedSize_; uint32_t cipherOverhead_; }; /** * This builder will enforce the packet size by appending padding frames for * continuous memory. This means pushing padding frame directly to the current * tail offset. The caller should ensure canBuildPacket() returns true before * constructing the builder. */ class InplaceSizeEnforcedPacketBuilder : public WrapperPacketBuilderInterface { public: using Packet = PacketBuilderInterface::Packet; explicit InplaceSizeEnforcedPacketBuilder( BufAccessor& bufAccessor, Packet packet, uint64_t enforcedSize, uint32_t cipherOverhead); /** * Returns true when packet has short header, and that enforced size> current * packet size + cipher oveahead and that iobuf has enough tailroom, * otherwise false */ FOLLY_NODISCARD bool canBuildPacket() const noexcept override; Packet buildPacket() && override; private: BufAccessor& bufAccessor_; Buf iobuf_; RegularQuicWritePacket packet_; Buf header_; Buf body_; uint64_t enforcedSize_; uint32_t cipherOverhead_; }; class VersionNegotiationPacketBuilder { public: explicit VersionNegotiationPacketBuilder( ConnectionId sourceConnectionId, ConnectionId destinationConnectionId, const std::vector<QuicVersion>& versions); virtual ~VersionNegotiationPacketBuilder() = default; uint32_t remainingSpaceInPkt(); std::pair<VersionNegotiationPacket, Buf> buildPacket() &&; /** * Whether the packet builder is able to build a packet. This should be * checked right after the creation of a packet builder object. */ FOLLY_NODISCARD bool canBuildPacket() const noexcept; private: void writeVersionNegotiationPacket(const std::vector<QuicVersion>& versions); FOLLY_NODISCARD uint8_t generateRandomPacketType() const; private: uint32_t remainingBytes_; VersionNegotiationPacket packet_; std::unique_ptr<folly::IOBuf> data_; }; /* * Used to construct a pseudo-retry packet, as described in the QUIC-TLS * draft 29. */ class PseudoRetryPacketBuilder { public: PseudoRetryPacketBuilder( uint8_t initialByte, ConnectionId sourceConnectionId, ConnectionId destinationConnectionId, ConnectionId originalDestinationConnectionId, QuicVersion quicVersion, Buf&& token); Buf buildPacket() &&; private: void writePseudoRetryPacket(); Buf packetBuf_; uint8_t initialByte_; ConnectionId sourceConnectionId_; ConnectionId destinationConnectionId_; ConnectionId originalDestinationConnectionId_; QuicVersion quicVersion_; Buf token_; }; class RetryPacketBuilder { public: RetryPacketBuilder( ConnectionId sourceConnectionId, ConnectionId destinationConnectionId, QuicVersion quicVersion, std::string&& retryToken, Buf&& integrityTag); uint32_t remainingSpaceInPkt(); Buf buildPacket() &&; /** * Whether the RetryPacketBuilder is able to build a packet. This should be * checked right after the creation of the RetryPacketBuilder. */ FOLLY_NODISCARD bool canBuildPacket() const noexcept; private: void writeRetryPacket(); Buf packetBuf_; ConnectionId sourceConnectionId_; ConnectionId destinationConnectionId_; QuicVersion quicVersion_; std::string retryToken_; Buf integrityTag_; uint32_t remainingBytes_; }; class StatelessResetPacketBuilder { public: StatelessResetPacketBuilder( uint16_t maxPacketSize, const StatelessResetToken& resetToken); Buf buildPacket() &&; private: std::unique_ptr<folly::IOBuf> data_; }; /** * A PacketBuilder that wraps in another PacketBuilder that may have a different * writableBytes limit. The minimum between the limit will be used to limit the * packet it can build. */ class PacketBuilderWrapper : public PacketBuilderInterface { public: ~PacketBuilderWrapper() override = default; PacketBuilderWrapper( PacketBuilderInterface& builderIn, uint32_t writableBytes) : builder(builderIn), diff( writableBytes > builder.remainingSpaceInPkt() ? 0 : builder.remainingSpaceInPkt() - writableBytes) {} FOLLY_NODISCARD uint32_t remainingSpaceInPkt() const override { return builder.remainingSpaceInPkt() > diff ? builder.remainingSpaceInPkt() - diff : 0; } void encodePacketHeader() override { CHECK(false) << "We only support wrapping builder that has already encoded header"; } void write(const QuicInteger& quicInteger) override { builder.write(quicInteger); } void writeBE(uint8_t value) override { builder.writeBE(value); } void writeBE(uint16_t value) override { builder.writeBE(value); } void writeBE(uint64_t value) override { builder.writeBE(value); } void appendBytes(PacketNum value, uint8_t byteNumber) override { builder.appendBytes(value, byteNumber); } void appendBytes(BufAppender& appender, PacketNum value, uint8_t byteNumber) override { builder.appendBytes(appender, value, byteNumber); } void appendBytes(BufWriter& writer, PacketNum value, uint8_t byteNumber) override { builder.appendBytes(writer, value, byteNumber); } void insert(std::unique_ptr<folly::IOBuf> buf) override { builder.insert(std::move(buf)); } void insert(std::unique_ptr<folly::IOBuf> buf, size_t limit) override { builder.insert(std::move(buf), limit); } void insert(const BufQueue& buf, size_t limit) override { builder.insert(buf, limit); } void appendFrame(QuicWriteFrame frame) override { builder.appendFrame(std::move(frame)); } void appendPaddingFrame() override { builder.appendPaddingFrame(); } void markNonEmpty() override { builder.markNonEmpty(); } void push(const uint8_t* data, size_t len) override { builder.push(data, len); } FOLLY_NODISCARD const PacketHeader& getPacketHeader() const override { return builder.getPacketHeader(); } PacketBuilderInterface::Packet buildPacket() && override { return std::move(builder).buildPacket(); } void accountForCipherOverhead(uint8_t overhead) noexcept override { builder.accountForCipherOverhead(overhead); } FOLLY_NODISCARD bool canBuildPacket() const noexcept override { return builder.canBuildPacket(); } FOLLY_NODISCARD uint32_t getHeaderBytes() const override { return builder.getHeaderBytes(); } FOLLY_NODISCARD bool hasFramesPending() const override { return builder.hasFramesPending(); } void releaseOutputBuffer() && override { std::move(builder).releaseOutputBuffer(); } private: PacketBuilderInterface& builder; uint32_t diff; }; } // namespace quic
#ifndef _GUARD_PERM_GROUP_H #define _GUARD_PERM_GROUP_H #include <cassert> #include <iterator> #include <map> #include <tuple> #include <type_traits> #include <vector> #include "bsgs.h" #include "perm.h" #include "perm_set.h" /** * @file perm_group.h * @brief Defines `PermGroup`. * * @author Timo Nicolai */ namespace cgtl { class BlockSystem; /** A permutation group representation. * * This class provides a useful abstraction encapsulating several complex * algorithms and data structures used to efficiently represent a permutation * group defined by a set of generating permutations without the need to store * elements explicitely for very large groups. */ class PermGroup { friend std::ostream &operator<<(std::ostream &os, PermGroup const &pg); public: class const_iterator : std::iterator<std::forward_iterator_tag, Perm> { public: const_iterator() : _end(true) {}; const_iterator(PermGroup const &pg); const_iterator operator++(); const_iterator operator++(int) { next_state(); return *this; } Perm const & operator*() const { return _current_result; } Perm const * operator->() const { return &_current_result; } bool operator==(const_iterator const &rhs) const; bool operator!=(const_iterator const &rhs) const { return !((*this) == rhs); } private: void next_state(); void update_result(); std::vector<unsigned> _state; bool _trivial; bool _end; std::vector<PermSet> _transversals; PermSet _current_factors; Perm _current_result; }; /// TODO explicit PermGroup(unsigned degree = 1) : _bsgs(degree), _order(1) {} /// TODO explicit PermGroup(BSGS const &bsgs) : _bsgs(bsgs), _order(bsgs.order()) {} /** Construct a permutation group. * * Constructs a permutation group representation from a given set of * generating permutations. The generators and group elements might not be * stored explicitly in the resulting object. Instead some variation of the * *Schreier-Sims* algorithm (see \cite holt05, chapter 4.4.2) might be used * to compute a *base* and *strong generating* set for the group which * describes the group completely and can be used to, among others, test * element membership and iterate through all group elements efficiently. * * \param degree the permutation group's *degree*, must be the same as the * degree of all given generators (which in turn implies that * they map from the set \f$\{1, \dots, degree\}\f$ to itself) * otherwise this constructor's behaviour is undefined * * \param generators a generating set for the permutation group */ PermGroup(unsigned degree, PermSet const &generators); /** Check two permutation groups for equality. * * Two permutation groups are equal exactly when they contain the same * elements. Although it it possible to use the PermGroup class to represent * permutation groups containing a very large number of elements, this * operation is guaranteed to be performed in \f$O(|bsgs.sgs()|)\f$ time. If * `(*this).degree() != rhs.degree()`, this function's behaviour is undefined. * * \return `true`, if `*this` and `rhs` describe permutation groups containing * the same elements, else `false` */ bool operator==(PermGroup const &rhs) const; /** Check two permutation groups for inequality. * * The result is always equal to `!(*this == rhs)`. * * \return `true`, if `*this` and `rhs` describe permutation groups not * containing the same elements, else `false` */ bool operator!=(PermGroup const &rhs) const; /** Construct a symmetric permutation group. * * \param degree * degree \f$n\f$ of the resulting group, for `degree == 0u` this * function's behaviour is undefined * * \return the symmetric group \f$S_n\f$ */ static PermGroup symmetric(unsigned degree); /** Construct a cyclic permutation group. * * \param degree * degree \f$n\f$ of the resulting group, for `degree == 0u` this * function's behaviour is undefined * * \return the cyclic group \f$C_n\f$ */ static PermGroup cyclic(unsigned degree); /** Construct an alternating permutation group. * * \param degree * degree \f$n\f$ of the resulting group, for `degree == 0u` this * function's behaviour is undefined * * \return the alternating group \f$A_n\f$ */ static PermGroup alternating(unsigned degree); /** Construct a dihedral permutation group. * * \param degree * degree \f$n\f$ of the resulting group (except when `degree == 1u` or * `degree == 2u`), for `degree == 0u` this function's behaviour is * undefined * * \return the dihedral group \f$D_n\f$ (or \f$D_2n\f$ in a different notation) */ static PermGroup dihedral(unsigned degree); /// TODO template<typename IT> static PermGroup direct_product(IT first, IT last, BSGS::Options const *bsgs_options = nullptr) { assert(std::distance(first, last) > 0); unsigned current_degree = 0u; unsigned total_degree = 0u; for (auto it = first; it != last; ++it) total_degree += it->degree(); PermSet generators; for (auto it = first; it != last; ++it) { for (Perm const &perm : it->generators()) generators.insert(perm.shifted(current_degree).extended(total_degree)); current_degree += it->degree(); } generators.minimize_degree(); return PermGroup(BSGS(total_degree, generators, bsgs_options)); } /** Compute the wreath product of two permutation groups. * * \param lhs left hand side permutation group operand * * \param rhs right hand side permutation group operand * * \return the permutation group wreath product of `lhs` and `rhs` */ static PermGroup wreath_product(PermGroup const &lhs, PermGroup const &rhs, BSGS::Options const *bsgs_options = nullptr); /** Obtain a constant iterator iterating over this group's elements. * * Note that the permutation group elements might not be stored explicitly * and could instead be constructed by the iterator "on the fly" which means * that storing references or pointers to the partial permutation pointed to * by any iterator iterating over a permutation group will result in * undefined behaviour. The elements are not guaranteed to be returned in any * particular order but every element will be returned exactly once.The * elements will also be returned in the same order on subsequent iterations * through the permutation group. This last point is not necessarily true for * other equal (in the sense of `operator==`) permutation groups. * * Iterating through a permutation group could thus look like this: * * ~~~~~{.cpp} * PermGroup pg(degree, generators); * * for (auto const &perm : pg) * std::cout << perm; * * for (auto const it = pg.begin(); it != pg.end(); ++i) * std::cout << *it; * ~~~~~ * * \return a constant iterator pointing to some element in this permutation * group, incrementing it will yield all other group members exactly * once (in no particular order) until end() is reached. */ const_iterator begin() const { return const_iterator(*this); } /** Obtain a contant iterator signifying a permutation group's "end". * * \return a contant iterator signifying a permutation group's "end" */ const_iterator end() const { return const_iterator(); } /** Obtain a permutation group's *degree*. * * A permutation group's degree is the positive integer \f$n\f$ such that * all its elements map from the set \f$\{1, \dots, n\}\f$ to itself. * * \return this permutation group's degree */ unsigned degree() const { return _bsgs.degree(); } /** Obtain a permutation group's *order*. * * A permutation group \f$G\f$ 's order is equal to the number of elements it * contains, i.e. \f$|G|\f$. Note that every permutation group must at least * contain an identity and thus it is always true that `order() > 0u`. * * \return this permutation group's order */ BSGS::order_type order() const { return _order; } /** Obtain permutation group generators. * * \return a generating set for this group. */ PermSet generators() const { return _bsgs.strong_generators(); } /** Obtain a permutation group's base and strong generating set. * * This function is only meaningful is the permutation group's elements are * not stored explicitely, which can be determined via TODO. * * \return a BSGS object representing this permutation group's base and strong * generating set */ BSGS &bsgs() { return _bsgs; } /// TODO BSGS const &bsgs() const { return _bsgs; } /** Check whether a permutation group is *trivial*. * * A permutation group is trivial by definition if it only contains an * identity permutation on the set \f$\{1, \dots, n\}\f$ (where \f$n\f$ is the * group's degree()). This is equivalent to testing whether `order() == 1u`. * * \return `true` if this permutation group is trivial, else `false` */ bool is_trivial() const { return _bsgs.base_empty(); } /** Check whether a permutation group is symmetric. * * \return `true` if the permutation group \f$G \leq Sym(\Omega)\f$ * represented by this object is in fact equal to \f$Sym(\Omega)\f$, * else `false` */ bool is_symmetric() const; /** Check whether a permutation group is symmetric. * * \return `true` if the permutation group \f$G \leq S_n\f$ represented by * this object is the alternating group \f$A_n\f$, else `false` */ bool is_alternating() const; /** Check whether a permutation group is *transitive*. * * A permutation group acting on a set \f$\Omega$\f is transitive by * definition if the group orbit of any \f$x \in \Omega$\f, * \f$G(x) = \{g \cdot x \in \{1, \dots, n\} : g \in G\} = \{1, \dots, n\}\f$ * (where \f$n\f$ is the group's degree()). * * \return `true` if this permutation group is transitive, else `false`. */ bool is_transitive() const; /** Check whether a permutation group contains a given permutation. * * Note that the group's elements may not be stored explicitly so while * efficient, this operation is not trivial. if `perm.degree() != * (*this).degree()` this function's behaviour is undefined. * * \return `true` if this permutation group contains the permutation `perm`, * else `false` */ bool contains_element(Perm const &perm) const; /** Construct a random group element. * * This function makes no guarantees about the returned elements distribution * of cryptographic security. Repeated calls to this function may not be very * efficient, use TODO instead. * * \return some element \f$x\f$ of this permutation group */ Perm random_element() const; /** Find a *disjoint subgroup decomposition* of a permutation group * * This function's implementation is based on \cite donaldson09. * * A disjoint subgroup decomposition of a permutation group \f$G\f$ is a set * \f$\{H_1, \dots, H_k\}\f$ where \f$H_1, \dots, H_k\f$ are subgroups of * \f$G\f$ such that \f$G = \{\alpha_1 \cdot \alpha_2 \dots \alpha_k : * \alpha_i \in H_i, (1 \leq i \leq k)\}\f$ and \f$\forall (i, j) \in \{1, * \dots, k\}^2 : i \neq j \Rightarrow moved(H_i) \cap moved(H_j) = * \emptyset\f$. Here, \f$moved(H_i)\f$ is the set \f$\{x : (x \in \{1, * \dots, n\} \land \exists \alpha \in H_i : \alpha(x) \neq x)\}\f$. * * \param complete * if this is `true` the function will always return the *finest* possible * disjoint subgroup decomposition (i.e. one in which no subgroup can be * further decomposed into disjoint subgroups), this might be more * computationally expensive * * \param disjoint_orbit_optimization * if this is `true`, the optimization described in \cite donaldson09, * chapter 5.2.1 is applied, this is only meaningful if `complete = true`, * otherwise this argument is ignored. * * \return a disjoint subgroup decomposition of this permutation group given * as a vector of subgroups as described above, in no particular * order, if no disjoint subgroup partition could be found, the vector * contains the group itself as its only element. */ std::vector<PermGroup> disjoint_decomposition( bool complete = true, bool disjoint_orbit_optimization = false) const; /** Find a *wreath product decomposition* of a permutation group * * This function's implementation is based on \cite donaldson09. * * A wreath product decomposition of a permutation group \f$G \leq S_n\f$ is * (using the notation in \cite donaldson09) a triple \f$(H, K, * \mathcal{X})\f$. Here\f$H \leq S_m\f$, \f$K \leq S_d\f$ and \f$n = m \cdot * d\f$, \f$\mathcal{X}\f$ is a set \f$\{X_1, \dots, X_d\}\f$ of sets * \f$X_i\f$ (with \f$|X_i| = m\f$) which partition the set \f$X = \{1, * \dots, n\}\f$ on which \f$G\f$ operates and \f$G = \{\sigma(\beta)\ * \sigma_1(\alpha_1) \dots \sigma_d(\alpha_d) : \beta \in K, \alpha_i \in H * \ (1 \leq i \leq d)\}\f$. \f$\sigma\f$ is the permutation representation * of the action of \f$K\f$ on \f$\mathcal{X}\f$ which permutes the sets * \f$X_i\f$ "among themselves" and the \f$\sigma_i\f$ are the permutation * representations of the obvious actions of \f$K\f$ on the sets \f$X_i\f$. * This is conventionally written as: \f$G = H \wr K\f$. * * \return a wreath product decomposition of \f$G\f$ as described above in * the form of the vector of permutation groups \f$[\sigma(K), * \sigma_1(H_1), \dots, \sigma_d(H_d)]\f$, if no wreath product * decomposition could be found (either because none exists or the * algorithm is unable to determine a valid decomposition, which is * currently possible due to limitations in the implementation) an * empty vector is returned */ std::vector<PermGroup> wreath_decomposition() const; private: // complete disjoint decomposition bool disjoint_decomp_orbits_dependent( Orbit const &orbit1, Orbit const &orbit2) const; void disjoint_decomp_generate_dependency_classes( OrbitPartition &orbits) const; static bool disjoint_decomp_restricted_subgroups( OrbitPartition const &orbit_split, PermGroup const &perm_group, std::pair<PermGroup, PermGroup> &restricted_subgroups); static std::vector<PermGroup> disjoint_decomp_join_results( std::vector<PermGroup> const &res1, std::vector<PermGroup> const &res2); static std::vector<PermGroup> disjoint_decomp_complete_recursive( OrbitPartition const &orbits, PermGroup const &perm_group); std::vector<PermGroup> disjoint_decomp_complete( bool disjoint_orbit_optimization = true) const; // incomplete disjoint decomposition struct MovedSet : public std::vector<unsigned> { void init(Perm const &perm); bool equivalent(MovedSet const &other) const; void extend(MovedSet const &other); }; struct EquivalenceClass { EquivalenceClass(Perm const &init, MovedSet const &moved) : generators({init}), moved(moved), merged(false) {} PermSet generators; MovedSet moved; bool merged; }; std::vector<EquivalenceClass> disjoint_decomp_find_equivalence_classes() const; void disjoint_decomp_merge_equivalence_classes( std::vector<EquivalenceClass> &equivalence_classes) const; std::vector<PermGroup> disjoint_decomp_incomplete() const; // wreath decomposition std::vector<PermGroup> wreath_decomp_find_stabilizers( BlockSystem const &block_system, PermGroup const &block_permuter) const; PermSet wreath_decomp_construct_block_permuter_image( BlockSystem const &block_system, PermGroup const &block_permuter) const; bool wreath_decomp_reconstruct_block_permuter( BlockSystem const &block_system, PermGroup const &block_permuter, PermSet const &block_permuter_image) const; BSGS _bsgs; BSGS::order_type _order; }; std::ostream &operator<<(std::ostream &os, PermGroup const &pg); } // namespace cgtl #endif // _GUARD_PERM_GROUP_H
#include <iostream> #include <vector> #include <string> #include <algorithm> int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int n, m; std::cin >> n >> m; std::vector<int> ATK; std::vector<std::string> name; for(int i = 0; i < n; i++) { std::string n; int idx; std::cin >> n >> idx; ATK.push_back(idx); name.push_back(n); } for(int i = 0; i < m; i++) { int X; std::cin >> X; auto lit = std::lower_bound(ATK.begin(), ATK.end(), X); std::cout << name[lit - ATK.begin()] << '\n'; } return 0; }
#ifndef HEADER_CURL_SSH_H #define HEADER_CURL_SSH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_LIBSSH2_H #include <libssh2.h> #include <libssh2_sftp.h> #endif /* HAVE_LIBSSH2_H */ /**************************************************************************** * SSH unique setup ***************************************************************************/ namespace youmecommon { typedef enum { SSH_NO_STATE = -1, /* Used for "nextState" so say there is none */ SSH_STOP = 0, /* do nothing state, stops the state machine */ SSH_INIT, /* First state in SSH-CONNECT */ SSH_S_STARTUP, /* Session startup */ SSH_HOSTKEY, /* verify hostkey */ SSH_AUTHLIST, SSH_AUTH_PKEY_INIT, SSH_AUTH_PKEY, SSH_AUTH_PASS_INIT, SSH_AUTH_PASS, SSH_AUTH_AGENT_INIT, /* initialize then wait for connection to agent */ SSH_AUTH_AGENT_LIST, /* ask for list then wait for entire list to come */ SSH_AUTH_AGENT, /* attempt one key at a time */ SSH_AUTH_HOST_INIT, SSH_AUTH_HOST, SSH_AUTH_KEY_INIT, SSH_AUTH_KEY, SSH_AUTH_DONE, SSH_SFTP_INIT, SSH_SFTP_REALPATH, /* Last state in SSH-CONNECT */ SSH_SFTP_QUOTE_INIT, /* First state in SFTP-DO */ SSH_SFTP_POSTQUOTE_INIT, /* (Possibly) First state in SFTP-DONE */ SSH_SFTP_QUOTE, SSH_SFTP_NEXT_QUOTE, SSH_SFTP_QUOTE_STAT, SSH_SFTP_QUOTE_SETSTAT, SSH_SFTP_QUOTE_SYMLINK, SSH_SFTP_QUOTE_MKDIR, SSH_SFTP_QUOTE_RENAME, SSH_SFTP_QUOTE_RMDIR, SSH_SFTP_QUOTE_UNLINK, SSH_SFTP_TRANS_INIT, SSH_SFTP_UPLOAD_INIT, SSH_SFTP_CREATE_DIRS_INIT, SSH_SFTP_CREATE_DIRS, SSH_SFTP_CREATE_DIRS_MKDIR, SSH_SFTP_READDIR_INIT, SSH_SFTP_READDIR, SSH_SFTP_READDIR_LINK, SSH_SFTP_READDIR_BOTTOM, SSH_SFTP_READDIR_DONE, SSH_SFTP_DOWNLOAD_INIT, SSH_SFTP_DOWNLOAD_STAT, /* Last state in SFTP-DO */ SSH_SFTP_CLOSE, /* Last state in SFTP-DONE */ SSH_SFTP_SHUTDOWN, /* First state in SFTP-DISCONNECT */ SSH_SCP_TRANS_INIT, /* First state in SCP-DO */ SSH_SCP_UPLOAD_INIT, SSH_SCP_DOWNLOAD_INIT, SSH_SCP_DONE, SSH_SCP_SEND_EOF, SSH_SCP_WAIT_EOF, SSH_SCP_WAIT_CLOSE, SSH_SCP_CHANNEL_FREE, /* Last state in SCP-DONE */ SSH_SESSION_DISCONNECT, /* First state in SCP-DISCONNECT */ SSH_SESSION_FREE, /* Last state in SCP/SFTP-DISCONNECT */ SSH_QUIT, SSH_LAST /* never used */ } sshstate; /* this struct is used in the HandleData struct which is part of the SessionHandle, which means this is used on a per-easy handle basis. Everything that is strictly related to a connection is banned from this struct. */ struct SSHPROTO { char *path; /* the path we operate on */ }; /* ssh_conn is used for struct connection-oriented data in the connectdata struct */ struct ssh_conn { const char *authlist; /* List of auth. methods, managed by libssh2 */ #ifdef USE_LIBSSH2 const char *passphrase; /* pass-phrase to use */ char *rsa_pub; /* path name */ char *rsa; /* path name */ bool authed; /* the connection has been authenticated fine */ sshstate state; /* always use ssh.c:state() to change state! */ sshstate nextstate; /* the state to goto after stopping */ CURLcode actualcode; /* the actual error code */ struct curl_slist *quote_item; /* for the quote option */ char *quote_path1; /* two generic pointers for the QUOTE stuff */ char *quote_path2; LIBSSH2_SFTP_ATTRIBUTES quote_attrs; /* used by the SFTP_QUOTE state */ bool acceptfail; /* used by the SFTP_QUOTE (continue if quote command fails) */ char *homedir; /* when doing SFTP we figure out home dir in the connect phase */ /* Here's a set of struct members used by the SFTP_READDIR state */ LIBSSH2_SFTP_ATTRIBUTES readdir_attrs; char *readdir_filename; char *readdir_longentry; int readdir_len, readdir_totalLen, readdir_currLen; char *readdir_line; char *readdir_linkPath; /* end of READDIR stuff */ int secondCreateDirs; /* counter use by the code to see if the second attempt has been made to change to/create a directory */ char *slash_pos; /* used by the SFTP_CREATE_DIRS state */ LIBSSH2_SESSION *ssh_session; /* Secure Shell session */ LIBSSH2_CHANNEL *ssh_channel; /* Secure Shell channel handle */ LIBSSH2_SFTP *sftp_session; /* SFTP handle */ LIBSSH2_SFTP_HANDLE *sftp_handle; int orig_waitfor; /* default READ/WRITE bits wait for */ #ifdef HAVE_LIBSSH2_AGENT_API LIBSSH2_AGENT *ssh_agent; /* proxy to ssh-agent/pageant */ struct libssh2_agent_publickey *sshagent_identity, *sshagent_prev_identity; #endif /* note that HAVE_LIBSSH2_KNOWNHOST_API is a define set in the libssh2.h header */ #ifdef HAVE_LIBSSH2_KNOWNHOST_API LIBSSH2_KNOWNHOSTS *kh; #endif #endif /* USE_LIBSSH2 */ }; #ifdef USE_LIBSSH2 /* Feature detection based on version numbers to better work with non-configure platforms */ #if !defined(LIBSSH2_VERSION_NUM) || (LIBSSH2_VERSION_NUM < 0x001000) # error "SCP/SFTP protocols require libssh2 0.16 or later" #endif #if LIBSSH2_VERSION_NUM >= 0x010000 #define HAVE_LIBSSH2_SFTP_SEEK64 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010100 #define HAVE_LIBSSH2_VERSION 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010205 #define HAVE_LIBSSH2_INIT 1 #define HAVE_LIBSSH2_EXIT 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010206 #define HAVE_LIBSSH2_KNOWNHOST_CHECKP 1 #define HAVE_LIBSSH2_SCP_SEND64 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010208 #define HAVE_LIBSSH2_SESSION_HANDSHAKE 1 #endif extern const struct Curl_handler Curl_handler_scp; extern const struct Curl_handler Curl_handler_sftp; #endif /* USE_LIBSSH2 */ } #endif /* HEADER_CURL_SSH_H */
#include"cMission.h" #include <iostream> int main(int argc, char* argv[]) { /*if (argc==2) { cMission Mission(argv[1]); if (!Mission.getConfig()) return 0; else std::cout<<"CONFIG LOADED\n"; if (!Mission.getMap()) { std::cout<<"Program terminated.\n"; return 0; } else std::cout<<"MAP LOADED\n"; Mission.createSearch(); Mission.createLog(); Mission.startSearch(); Mission.printSearchResultsToConsole(); Mission.saveSearchResultsToLog(); } return 1;*/ std::vector<std::string> names = {"brc202d","den520d","ost003d"}; std::vector<int> agents = {32,64,96,128,160}; //for(int j=0; j<3; j++) for(int k=4; k<agents.size(); k++) for(int i=0; i<500; i++) { //int k = 4; //int i = 16; std::cout<<i<<" "; std::string path="D:/Users/andreychuk/Documents/GitHub/xml/Warehouse_WFI/"+std::to_string(agents[k])+"/"+std::to_string(i)+".xml"; cMission Mission(path.c_str()); if (!Mission.getConfig()) return 0; if (!Mission.getMap()) { std::cout<<"Program terminated.\n"; return 0; } Mission.createSearch(); Mission.createLog(); Mission.startSearch(); Mission.saveSearchResultsToLog(); } }
#include<bits/stdc++.h> using namespace std; const int c[]={2,3,5,7,11,13}; long long l,r; int ans=0; void readit(){ scanf("%d%d",&l,&r); } void writeit(){ printf("%d\n",ans); } long long power(long long a,long long b,long long p){ if (!b) return 1%p; long long t=power(a,b/2,p); t=t*t%p; if (b&1) t=t*a%p; return t; } bool check(long long n){ bool f=1; for (int i=0;i<=5;i++) if (c[i]!=n&&power(c[i],n-1,n)!=1){ f=0; break; } return f; } void work(){ if (l<=2) ans=1; if (!(l%2)) l++; for (long long i=l;i<=r;i+=2) if (check(i)) ans++; } int main(){ readit(); work(); writeit(); return 0; }
#ifndef RECOGNIZERLISTENER_HH_ #define RECOGNIZERLISTENER_HH_ #include <pthread.h> #include "RecognizerStatus.hh" #include "msg.hh" /** Class for reading in queue and handling the incoming messages. Operates * in an own thread. */ class RecognizerListener { public: /** Constructs a new in queue listener. * \param in_queue In queue to listen. * \param recognition Recognition messages are passed to this object. */ RecognizerListener(msg::InQueue *in_queue, RecognizerStatus *recognition); /** Destructs the object. */ ~RecognizerListener(); /** Starts a new thread to read the in queue. * \return false if thread already active or thread creation failed. */ bool start(); /** Stops the thread. When function returns, you can be sure that the * thread has really finished. */ void stop(); /** Enables in queue reading. */ void enable(); /** Disables in queue reading. When disabled the thread doesn't do * anything. When the function returns, you can be sure that the thread has * really stopped reading in queue and handling the message. */ void disable(); /** If in queue has a broken pipe this flag is raised. Should be checked * often. This class does't do any broken pipe handling. * \return true if in queue has a broken pipe. */ inline bool is_broken_pipe() const; /** Ignores recognition messages until receives ready message. */ inline void wait_for_ready(); /** \return true if not waiting for a ready message. */ inline bool is_ready() const; private: /** Callback function for the pthread. * \param user_data this pointer to the object itself. * \return Return value of the thread, we use NULL. */ static void* callback(void *user_data); /** Does the reading of the in queue and handling incoming messages. If * in queue has a broken pipe, it throws an exception to quit the the * thread and raise a broken pipe flag. */ void run() throw(msg::ExceptionBrokenPipe); RecognizerStatus *m_recognition; //!< Object for recognition message parsing. msg::InQueue *m_in_queue; //!< The in queue to read. bool m_stop; //!< Flag telling when to quit the thread. bool m_enabled; //!< Flag telling if in queue should be read. bool m_thread_created; //!< Flag telling if thread is already active. bool m_broken_pipe; //!< Flag telling if in queue has a broken pipe. pthread_t m_thread; //!< Thread structure. pthread_mutex_t m_disable_lock; //!< Lock to make disabling safe. // TODO: This waiting should be done with an ID. An ID of the ready message // that should be waited is given. This prevents some reseting bugs. // unsigned int m_wait_ready; bool m_wait_ready; //!< true when should ignore recognitions until M_READY. }; bool RecognizerListener::is_broken_pipe() const { return this->m_broken_pipe; } void RecognizerListener::wait_for_ready() { pthread_mutex_lock(&this->m_disable_lock); // this->m_wait_ready++; this->m_wait_ready = true; pthread_mutex_unlock(&this->m_disable_lock); } bool RecognizerListener::is_ready() const { return this->m_wait_ready == 0; } #endif /*RECOGNIZERLISTENER_HH_*/
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "TcpConnector.h" #include <cassert> #include <stdexcept> #include <fcntl.h> #include <netdb.h> #include <unistd.h> #include <sys/epoll.h> #include <System/InterruptedException.h> #include <System/Ipv4Address.h> #include "Dispatcher.h" #include "ErrorMessage.h" #include "TcpConnection.h" namespace platform_system { namespace { struct TcpConnectorContextExt : public OperationContext { int connection; }; } TcpConnector::TcpConnector() : dispatcher(nullptr) { } TcpConnector::TcpConnector(Dispatcher& dispatcher) : dispatcher(&dispatcher), context(nullptr) { } TcpConnector::TcpConnector(TcpConnector&& other) : dispatcher(other.dispatcher) { if (other.dispatcher != nullptr) { assert(other.context == nullptr); context = nullptr; other.dispatcher = nullptr; } } TcpConnector::~TcpConnector() { } TcpConnector& TcpConnector::operator=(TcpConnector&& other) { dispatcher = other.dispatcher; if (other.dispatcher != nullptr) { assert(other.context == nullptr); context = nullptr; other.dispatcher = nullptr; } return *this; } TcpConnection TcpConnector::connect(const Ipv4Address& address, uint16_t port) { assert(dispatcher != nullptr); assert(context == nullptr); if (dispatcher->interrupted()) { throw InterruptedException(); } std::string message; int connection = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connection == -1) { message = "socket failed, " + lastErrorMessage(); } else { sockaddr_in bindAddress; bindAddress.sin_family = AF_INET; bindAddress.sin_port = 0; bindAddress.sin_addr.s_addr = INADDR_ANY; if (bind(connection, reinterpret_cast<sockaddr*>(&bindAddress), sizeof bindAddress) != 0) { message = "bind failed, " + lastErrorMessage(); } else { int flags = fcntl(connection, F_GETFL, 0); if (flags == -1 || fcntl(connection, F_SETFL, flags | O_NONBLOCK) == -1) { message = "fcntl failed, " + lastErrorMessage(); } else { sockaddr_in addressData; addressData.sin_family = AF_INET; addressData.sin_port = htons(port); addressData.sin_addr.s_addr = htonl(address.getValue()); int result = ::connect(connection, reinterpret_cast<sockaddr *>(&addressData), sizeof addressData); if (result == -1) { if (errno == EINPROGRESS) { ContextPair contextPair; TcpConnectorContextExt connectorContext; connectorContext.interrupted = false; connectorContext.context = dispatcher->getCurrentContext(); connectorContext.connection = connection; contextPair.readContext = nullptr; contextPair.writeContext = &connectorContext; epoll_event connectEvent; connectEvent.events = EPOLLOUT | EPOLLRDHUP | EPOLLERR | EPOLLONESHOT; connectEvent.data.ptr = &contextPair; if (epoll_ctl(dispatcher->getEpoll(), EPOLL_CTL_ADD, connection, &connectEvent) == -1) { message = "epoll_ctl failed, " + lastErrorMessage(); } else { context = &connectorContext; dispatcher->getCurrentContext()->interruptProcedure = [&] { TcpConnectorContextExt* connectorContext1 = static_cast<TcpConnectorContextExt*>(context); if (!connectorContext1->interrupted) { if (close(connectorContext1->connection) == -1) { throw std::runtime_error("TcpListener::stop, close failed, " + lastErrorMessage()); } connectorContext1->interrupted = true; dispatcher->pushContext(connectorContext1->context); } }; dispatcher->dispatch(); dispatcher->getCurrentContext()->interruptProcedure = nullptr; assert(dispatcher != nullptr); assert(connectorContext.context == dispatcher->getCurrentContext()); assert(contextPair.readContext == nullptr); assert(context == &connectorContext); context = nullptr; connectorContext.context = nullptr; if (connectorContext.interrupted) { throw InterruptedException(); } if (epoll_ctl(dispatcher->getEpoll(), EPOLL_CTL_DEL, connection, NULL) == -1) { message = "epoll_ctl failed, " + lastErrorMessage(); } else { if((connectorContext.events & (EPOLLERR | EPOLLHUP)) != 0) { int result = close(connection); assert(result != -1); throw std::runtime_error("TcpConnector::connect, connection failed"); } int retval = -1; socklen_t retValLen = sizeof(retval); int s = getsockopt(connection, SOL_SOCKET, SO_ERROR, &retval, &retValLen); if (s == -1) { message = "getsockopt failed, " + lastErrorMessage(); } else { if (retval != 0) { message = "getsockopt failed, " + lastErrorMessage(); } else { return TcpConnection(*dispatcher, connection); } } } } } } else { return TcpConnection(*dispatcher, connection); } } } int result = close(connection); assert(result != -1); } throw std::runtime_error("TcpConnector::connect, "+message); } }
//=========================================================================== //! @file manager_base.h //! @brief マネージャーの基底クラス //=========================================================================== #pragma once //=========================================================================== //! @class ManagerBase //=========================================================================== class ManagerBase { public: //----------------------------------------------------------------------- //! @name 初期化 //----------------------------------------------------------------------- //@{ //! @brief コンストラクタ ManagerBase() = default; //! @brief デストラクタ virtual ~ManagerBase() = default; //@} //----------------------------------------------------------------------- //! @name タスク //----------------------------------------------------------------------- //@{ //----------------------------------------------------------------------- //! @brief 初期化 //! @return true 正常終了 //! @return false エラー終了 //----------------------------------------------------------------------- virtual bool initialize() { return true; } //! @brief 更新 virtual void update() {}; //! @brief 描画 virtual void render() {}; //----------------------------------------------------------------------- //! @brief 描画(描画モード指定) //! @param [in] renderMode 描画したいモード //----------------------------------------------------------------------- virtual void render([[maybe_unused]] RenderMode renderMode){}; //! @brief 解放 virtual void cleanup() {}; //@} private: };
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> using namespace std; bool kiemTra(int a, int b, int c); float dienTich(int a, int b, int c); int main() { freopen("choinon7.inp","r",stdin); freopen("choinon7.out","w",stdout); int a,b,c; scanf("%d %d %d",&a,&b,&c); if(kiemTra(a,b,c)){ printf("%f",dienTich(a,b,c)); }else{ printf("Khong phai tam giac"); } return 0; } bool kiemTra(int a, int b, int c){ if(a>0&& b>0 &&c>0 && (a+b>c) &&(a+c>b) && (b+c>a)){ return true; }else{ return false; } return false; } float dienTich(int a, int b, int c){ float dienTich,p; p = (float)(a+b+c)/2; dienTich = sqrt(p*(p-a)*(p-b)*(p-c)); return dienTich; }
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <vector> #include "camera.h" #include "shader.h" #include "window.h" camera::camera(window* win, glm::vec3* target) { win_ptr = win; // pos + offset glm::vec3 offset(0.0f, 5.0f, 3.0f); pos = *target + offset; // front float yaw_angle = -35.0f; glm::vec3 direction(0.0f, sin(glm::radians(yaw_angle)), -1.0f * cos(glm::radians(yaw_angle))); front = glm::normalize(direction); // up up = glm::vec3(0.0f, 1.0f, 0.0f); view = glm::lookAt(pos, pos + front, up); } void camera::update() { const float camera_speed = 2.5f * win_ptr->delta_time; // move dir glm::vec3 move_vec(0.0f, 0.0f, -1.0f); if (glfwGetKey(win_ptr->ptr, GLFW_KEY_W) == GLFW_PRESS) pos += move_vec * camera_speed; if (glfwGetKey(win_ptr->ptr, GLFW_KEY_S) == GLFW_PRESS) pos -= move_vec * camera_speed; if (glfwGetKey(win_ptr->ptr, GLFW_KEY_A) == GLFW_PRESS) pos -= glm::normalize(glm::cross(move_vec, up)) * camera_speed; if (glfwGetKey(win_ptr->ptr, GLFW_KEY_D) == GLFW_PRESS) pos += glm::normalize(glm::cross(move_vec, up)) * camera_speed; } void camera::set_view(shader* p) { // look at update view = glm::lookAt(pos, pos + front, up); int view_loc = glGetUniformLocation(p->p_id, "view"); glUniformMatrix4fv(view_loc, 1, GL_FALSE, glm::value_ptr(view)); }
// // Created by pierreantoine on 08/01/2020. // #pragma once #include <string> class lexer_interface { public: virtual void lex() = 0; virtual void lineno() = 0; virtual void match(const std::string & a_string) =0; ~lexer_interface() = default; };
#pragma once #include "Drawable.h" class MultiDrawable : public Drawable { public: MultiDrawable(); void draw(sf::RenderWindow&); void setPosition(sf::Vector2f); sf::Vector2f getPosition(); void move(sf::Vector2f); void reverseMove(); protected: std::vector < std::shared_ptr < sf::RectangleShape >> shapes; sf::Vector2f lastMove; };
class ItemStone: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_ItemStone;//"Rough Stone" picture = "\z\addons\dayz_buildings\equip\rocks.paa"; model = "z\addons\dayz_buildings\models\rocks.p3d"; descriptionShort = $STR_BLD_desc_ItemStone;//"Rough Stone" class ItemActions { class Crafting { text = $STR_EPOCH_ACTION_CONCRETE_BLOCK; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox","ItemEtool"}; output[] = {{"ItemConcreteBlock",1}}; input[] = {{"ItemStone",6},{"CementBag",1}}; }; class Crafting1 { text = $STR_BLD_name_WoodenFence_1_foundation; script = ";['Crafting1','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"woodfence_foundation_kit",1}}; input[] = {{"ItemStone",8},{"MortarBucket",1},{"ItemPlank",1}}; }; class Crafting2 { text = $STR_BLD_name_MetalFence_1_foundation; script = ";['Crafting2','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"metalfence_foundation_kit",1}}; input[] = {{"ItemStone",8},{"MortarBucket",1},{"ItemRSJ",1}}; }; }; }; class ItemConcreteBlock: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_BLD_name_ItemConcreteBlock;//"Concrete Block" picture = "\z\addons\dayz_buildings\equip\concreteblock.paa"; model = "z\addons\dayz_buildings\models\concreteblock.p3d"; descriptionShort = $STR_BLD_desc_ItemConcreteBlock;//"Concrete Block" class ItemActions { class Crafting { text = $STR_EPOCH_ACTION_CONCRETE_BUNKER; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinder_bunker_kit",1}}; input[] = {{"full_cinder_wall_kit",3},{"ItemConcreteBlock",5},{"equip_metal_sheet",3},{"ItemScrews",1}}; }; }; }; class CinderBlocks: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_CINDERBLOCKS; model = "\z\addons\dayz_epoch\models\cinder_stack.p3d"; picture = "\z\addons\dayz_epoch\pictures\epuip_cinder_blocks_CA.paa"; descriptionShort = $STR_EPOCH_CINDERBLOCKS_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_252; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"half_cinder_wall_kit",1}}; input[] = {{"CinderBlocks",3},{"MortarBucket",1}}; }; class Crafting1 { text = $STR_EPOCH_PLAYER_252_1; script = ";['Crafting1','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"full_cinder_wall_kit",1}}; input[] = {{"CinderBlocks",7},{"MortarBucket",2}}; }; class Crafting2 { text = $STR_EPOCH_PLAYER_239_1_3; script = ";['Crafting2','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinderwall_window_kit",1}}; input[] = {{"CinderBlocks",5},{"MortarBucket",1},{"ItemTankTrap",1},{"ItemPole",1}}; }; class Crafting3 { text = $STR_EPOCH_PLAYER_234; script = ";['Crafting3','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinder_door_frame_kit",1}}; input[] = {{"CinderBlocks",4},{"MortarBucket",1},{"ItemTankTrap",1}}; }; class Crafting4 { text = $STR_EPOCH_PLAYER_253; script = ";['Crafting4','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinder_garage_frame_kit",1}}; input[] = {{"CinderBlocks",3},{"MortarBucket",1},{"ItemTankTrap",1}}; }; class Crafting5 { text = $STR_EPOCH_PLAYER_253_1_1; script = ";['Crafting5','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinder_garage_top_open_frame_kit",1}}; input[] = {{"CinderBlocks",4},{"MortarBucket",1}}; }; class Crafting6 { text = $STR_EPOCH_PLAYER_253_1; script = ";['Crafting6','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox"}; output[] = {{"cinder_gate_frame_kit",1}}; input[] = {{"CinderBlocks",8},{"MortarBucket",4}}; }; }; }; class MortarBucket: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BUCKETOFMORTAR; model = "\z\addons\dayz_epoch\models\mortar.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_mortar_CA.paa"; descriptionShort = $STR_EPOCH_BUCKETOFMORTAR_DESC; }; class equip_brick : CA_Magazine { scope = 2; count = 1; model = "\z\addons\dayz_communityassets\models\brick.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_brick.paa"; displayName = $STR_ITEM_NAME_equip_brick; descriptionShort = $STR_ITEM_DESC_equip_brick; }; class CementBag: CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_CEMENT_BAG; descriptionShort = $STR_ITEM_DESC_CEMENT_BAG; picture = "\dayz_epoch_c\icons\equipment\ItemCementBag.paa"; model = "\z\addons\dayz_epoch_w\items\cement_bag.p3d"; class ItemActions { class Crafting { text = $STR_EPOCH_ACTION_CONCRETE_BLOCK; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemToolbox","ItemEtool"}; output[] = {{"ItemConcreteBlock",1}}; input[] = {{"ItemStone",6},{"CementBag",1}}; }; }; };
#include <ionir/misc/inst_builder.h> #include <ionir/misc/bootstrap.h> #include "pch.h" using namespace ionir; TEST(InstBuilderTest, GetSection) { ionshared::Ptr<BasicBlock> section = Bootstrap::basicBlock(); ionshared::Ptr<InstBuilder> builder = section->createBuilder(); EXPECT_EQ(builder->getBasicBlock(), section); } TEST(InstBuilderTest, CreateReturn) { // TODO }
#include <iostream> #include <chrono> unsigned int ackermann(unsigned int m, unsigned int n) { if (m == 0) { return n + 1; } if (n == 0) { return ackermann(m - 1, 1); } return ackermann(m - 1, ackermann(m, n - 1)); } int main() { auto start = std::chrono::high_resolution_clock::now(); unsigned int x, y; std::cout << "choose a number:\n "; std::cin >> x; std::cout << "choose another number:\n "; std::cin >> y; for (unsigned int m = 0; m < x; ++m) { for (unsigned int n = 0; n < y; ++n) { std::cout << "A(" << m << ", " << n << ") = " << ackermann(m, n) << "\n"; } } auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; std::cout << "elapsed time: " << elapsed.count() << " s\n"; }
// Created on: 1995-03-14 // Created by: Jacques GOUSSARD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomAPI_IntSS_HeaderFile #define _GeomAPI_IntSS_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GeomInt_IntSS.hxx> #include <Standard_Integer.hxx> class StdFail_NotDone; class Standard_OutOfRange; class Geom_Surface; class Geom_Curve; //! This class implements methods for //! computing the intersection curves between two surfaces. //! The result is curves from Geom. The "domain" used for //! a surface is the natural parametric domain //! unless the surface is a RectangularTrimmedSurface //! from Geom. class GeomAPI_IntSS { public: DEFINE_STANDARD_ALLOC //! Constructs an empty object. Use the //! function Perform for further initialization algorithm by two surfaces. GeomAPI_IntSS(); //! Computes the intersection curves //! between the two surfaces S1 and S2. Parameter Tol defines the precision //! of curves computation. For most cases the value 1.0e-7 is recommended to use. //! Warning //! Use the function IsDone to verify that the intersections are successfully computed.I GeomAPI_IntSS(const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const Standard_Real Tol); //! Initializes an algorithm with the //! given arguments and computes the intersection curves between the two surfaces S1 and S2. //! Parameter Tol defines the precision of curves computation. For most //! cases the value 1.0e-7 is recommended to use. //! Warning //! Use function IsDone to verify that the intersections are successfully computed. void Perform (const Handle(Geom_Surface)& S1, const Handle(Geom_Surface)& S2, const Standard_Real Tol); //! Returns True if the intersection was successful. Standard_Boolean IsDone() const; //! Returns the number of computed intersection curves. //! Exceptions //! StdFail_NotDone if the computation fails. Standard_Integer NbLines() const; //! Returns the computed intersection curve of index Index. //! Exceptions //! StdFail_NotDone if the computation fails. //! Standard_OutOfRange if Index is out of range [1, NbLines] where NbLines //! is the number of computed intersection curves. const Handle(Geom_Curve)& Line (const Standard_Integer Index) const; protected: private: GeomInt_IntSS myIntersec; }; #include <GeomAPI_IntSS.lxx> #endif // _GeomAPI_IntSS_HeaderFile
#include <bits/stdc++.h> using namespace std; int main() { int size; cout<<"Enter the size: "; cin>>size; int arr[size]; cout<<"Enter the elements: "; for(int i=0;i<size;i++) { cin>>arr[i]; } int sum = 0; for (int i = 0; i < size; i++) { for (int j = i; j < size; j += 2) { for (int k = i; k <= j; k++) { sum += arr[k]; } } } cout<<"Sum is : "<<sum; return 0; }
#include <fstream> #include <iostream> #include <string> #include <vector> #include "../moves/movesGen.cpp" using namespace std; /* Input data consumer functions * * Includes functions for reading in and creating the * board object that we will be reading from. Crucial * that it does this in a way that is inline with the * expectations of the rest of the functions. */ Board boardGen() { //the girl /* Returns a Board object * This board is expected to be comprised of a * one-dimensional array of tiles (board.tiles) * * About representing a 2D board in 1D. * Board should have getter/setter functions * for its tiles array that uses a standardized * mathematical operation to "flatten" and "deflatten" * the board. It should be abstracted in such a way * that you can call board.set(0,0) = tile; * * more on that in the board struct. */ ifstream inFile; string x; inFile.open("./board/board.txt"); Board board; board.tiles = vector<Tile>(); if(!inFile){ cout << "File does not exist?" << endl; return *(new Board()); } inFile >> x; //skip the first line(the rack) int countY = 0; while(inFile >> x) { int countX = 0; // This loops through each line of inFile and stores it // in variable x for each iteration. for(string::iterator it = x.begin(); it!=x.end();++it){ if (*it == '-'){ vector<int> coords; coords.push_back(countX); coords.push_back(countY); board.tiles.push_back(*(new Tile(0,0,0, coords))); } if (isalpha(*it)){ vector<int> coords; coords.push_back(countX); coords.push_back(countY); board.tiles.push_back(*(new Tile(*it, weight(*it), 0, coords))); } if(isdigit(*it)){ vector<int> coords; coords.push_back(countX); coords.push_back(countY); board.tiles.push_back(*(new Tile(0, 0, *it-48, coords))); } countX++; } countY++; } inFile.close(); return board; } vector<Tile> rackGen() { //the girl ifstream inFile; string x; vector<Tile> tiles; inFile.open("./board/board.txt"); if(!inFile){ cout << "File does not exist?" << endl; return tiles; } inFile >> x; //Store the rack line in variable x; // for each char it in x for(string::iterator it = x.begin(); it!=x.end();++it){ vector<int> coords; coords.push_back(-1); tiles.push_back(*(new Tile(*it, weight(*it), 0, coords))); // initializes tile with no bonus and default coord of -1 } inFile.close(); return tiles; }
#include<bits/stdc++.h> using namespace std; class PartitionSet { public: bool Partition(const vector<int> &no) { int sum = 0; for(int i = 0; i < no.size(); i++){ sum += no[i]; } if(sum % 2 != 0) { return false; } return this->PartitionRecursive(no, sum / 2, 0); } private: bool PartitionRecursive(const vector<int> &no, int sum, int currentIndex) { if (sum == 0) { return true; } if (no.empty() || currentIndex >= no.size()) { return false; } if (no[currentIndex] <= sum) { if (PartitionRecursive(no, sum - no[currentIndex], currentIndex + 1)) { return true; } } return PartitionRecursive(no, sum, currentIndex + 1); } };
/* Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest. Examples: Input: arr[] = {10, 5, 3, 4, 3, 5, 6} Output: 5 [5 is the first element that repeats] 10 5 3 4 3 5 6 Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10} Output: 6 [6 is the first element that repeats] 6 10 5 4 9 120 4 6 10 */ #include<bits/stdc++.h> using namespace std; int firstRepeating(int arr[], int n) { int i; unordered_set<int> s; for(i=0; i<n/2; i++) { if(s.find(arr[i])!=s.end()) return i; s.insert(arr[i]); if(s.find(arr[n-(i+1)])!=s.end()) return n-(i+1); // s.insert(arr[n-(i+1)]); } return -1; } int main() { int n, i; cin>>n; int arr[n]; for(i=0; i<n; i++) cin>>arr[i]; // for(i=0; i<n; i++) // cout<<arr[i]<<" "; // cout<<endl; cout<<arr[firstRepeating(arr, n)]; cout<<endl; return 0; }
#include<iostream> #include<iomanip> using namespace std; int find(int a[], int n, int x) { int i = 0; for (; i < n; i++) { if (a[i] == x) return i; } cout << "Not Found"; return -1; } void PrintArr(int a[], int n) { if (n == 1) exit(0); else { int i = 0; for (; i < n - 1; i++) { cout << setw(4) << a[i]; } } } void del(int a[], int n, int i) { for (; i < n; i++) { a[i] = a[i + 1]; } a[n] = NULL; PrintArr(a, n); } int main() { int n, i; int arr[10]; cin >> n; for (i = 0; i < n; i++) { cin >> arr[i]; } int x, delnumber; cin >> x; delnumber = find(arr, n, x); if (delnumber == -1) return 0; else del(arr, n, delnumber); return 0; }
#include <mpi.h> #include <cstdlib> #include <iostream> int main(int argc, char* argv[]){ MPI_Init(&argc, &argv); float message; int n, i, rank; MPI_Status status; MPI_Comm_size(MPI_COMM_WORLD, &n); MPI_Comm_rank(MPI_COMM_WORLD, &rank); float rankf = rank; rankf += 0.001; if (rank == 4) { std::cout << "Hello from main process " << rank << "\n"; for (i=1; i<n; i++){ MPI_Recv(&message, 1, MPI_FLOAT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); std::cout << "Hello from process " << message << std::endl; } } else { MPI_Send(&rankf,1,MPI_FLOAT,4,0,MPI_COMM_WORLD); } MPI_Finalize(); return 0; }
#include "gtest/gtest.h" #include "fixtures.hpp" using namespace wali::xfa; #define NUM_ELEMENTS(array) (sizeof(array)/sizeof((array)[0])) // WARNING: the order of the rows and columns in this table must be // consistent with the order of 'words' and 'nwas' below. static bool expected_answers[][13] = { /* eps a aa aaa aaaa a^5 a^6 a^7 a^8 b bb ab ba */ /* trivial {} */ { false, false, false, false, false, false, false, false, false, false, false, false, false }, /* accept empty */ { true, false, false, false, false, false, false, false, false, false, false, false, false }, /* no trans {} */ { false, false, false, false, false, false, false, false, false, false, false, false, false }, /* impossible data*/ { false, false, false, false, false, false, false, false, false, false, false, false, false }, /* simple {a} */ { false, true, false, false, false, false, false, false, false, false, false, false, false }, /* simple cycle */ { false, true, true, true, true, true, true, true, true, false, false, false, false }, /* even cycle */ { false, false, true, false, true, false, true, false, true, false, false, false, false }, /* simple {ab} */ { false, false, false, false, false, false, false, false, false, false, false, true, false }, /* impossible seq */ { false, false, false, false, false, false, false, false, false, false, false, false, false }, /* simple {a, b} */ { false, true, false, false, false, false, false, false, false, true, false, false, false }, /* only {a} poss. */ { false, true, false, false, false, false, false, false, false, false, false, false, false }, /* immpossible eps*/ { false, false, false, false, false, false, false, false, false, false, false, false, false }, /* simple eps */ { true, false, false, false, false, false, false, false, false, false, false, false, false } }; namespace wali { namespace xfa { TEST(wali$xfa$Xfa$isAcceptedWithNonzeroWeight, Battery) { XfaContext context; Relations relations(context.voc, "left"); sem_elem_t zero = relations.false_; Xfa const xfas[] = { TrivialEmptyXfa(zero).xfa, AcceptEmptyStringOnly(zero).xfa, EmptyByMissingTransition(zero).xfa, EmptyByImpossibleDataTransition(zero, relations).xfa, SingleSimpleTrans(zero, relations).xfa, BoringCycle(zero, relations).xfa, DataRestrictedCycle(zero, relations).xfa, SimpleAB(zero, relations).xfa, ImpossibleSequence(zero, relations).xfa, AOrB(zero, relations).xfa, AlternativePathImpossible(zero, relations).xfa, EmptyByImpossibleDataTransitionEpsilon(zero, relations).xfa, SingleSimpleTransEpsilon(zero, relations).xfa }; Xfa::Word const words[] = { Words().epsilon, Words().a, Words().aa, Words().aaa, Words().aaaa, Words().a5, Words().a6, Words().a7, Words().a8, Words().b, Words().bb, Words().ab, Words().ba }; const unsigned num_xfas = NUM_ELEMENTS(xfas); ASSERT_EQ(num_xfas, NUM_ELEMENTS(expected_answers)); const unsigned num_words = NUM_ELEMENTS(words); ASSERT_EQ(num_words, NUM_ELEMENTS(expected_answers[0])); for (unsigned word = 0 ; word < num_words ; ++word) { for (unsigned xfa = 0 ; xfa < num_xfas ; ++xfa) { std::stringstream ss; ss << "Current XFA number " << xfa << " and word number " << word; SCOPED_TRACE(ss.str()); if (expected_answers[xfa][word]) { EXPECT_TRUE(xfas[xfa].isAcceptedWithNonzeroWeight(words[word])); } else { EXPECT_FALSE(xfas[xfa].isAcceptedWithNonzeroWeight(words[word])); } } } } } }
// // Created by 钟奇龙 on 2019-05-16. // #include <iostream> #include <vector> using namespace std; int maxSum(vector<int> arr){ if(arr.size() == 0) return 0; int curSum = 0; int maxSum = 0; for(int i=0; i<arr.size(); ++i){ curSum += arr[i]; maxSum = max(maxSum,curSum); if(curSum < 0){ curSum = 0; } } return maxSum; } int main(){ vector<int> arr = {1,-2,3,5,-2,6,-1}; cout<<maxSum(arr)<<endl; return 0; }
#pragma once /** * @file * @copyright (C) 2020 Anton Frolov johnjocoo@gmail.com */ #include <stdint.h> #define _DURATION_BASE_T_MAX UINT32_MAX typedef uint32_t DurationBaseT; class Duration { public: // can not be used from ISR static Duration timeFromEpoch(); static Duration epoch(); static Duration invalid(); static Duration fromMillis(DurationBaseT millis); static Duration fromSeconds(DurationBaseT seconds, DurationBaseT millis = 0); static Duration fromMinutes(DurationBaseT minutes, DurationBaseT seconds = 0, DurationBaseT millis = 0); Duration(const Duration& other); Duration& operator=(const Duration& other); ~Duration(); bool isInvalid() const; DurationBaseT millisTotal() const; DurationBaseT secondsTotal() const; DurationBaseT minutesTotal() const; DurationBaseT millisInSecond() const; DurationBaseT secondsInMinute() const; DurationBaseT toOSTicks() const; private: explicit Duration(DurationBaseT millis); DurationBaseT m_millis; }; // class Duration bool operator==(const Duration& val1, const Duration& val2) { return val1.m_millis == val2.m_millis; } bool operator!=(const Duration& val1, const Duration& val2) { return val1.m_millis != val2.m_millis; } bool operator>(const Duration& val1, const Duration& val2) { return val1.m_millis > val2.m_millis; } bool operator<(const Duration& val1, const Duration& val2) { return val1.m_millis < val2.m_millis; } bool operator>=(const Duration& val1, const Duration& val2) { return val1.m_millis >= val2.m_millis; } bool operator<=(const Duration& val1, const Duration& val2) { return val1.m_millis <= val2.m_millis; } Duration operator+(const Duration& val1, const Duration& val2) { return Duration{val1.m_millis + val2.m_millis}; } Duration operator-(const Duration& val1, const Duration& val2) { return Duration{val1.m_millis - val2.m_millis}; } Duration& operator+=(Duration& val1, const Duration& val2) { val1.m_millis += val2.m_millis; return val1; } Duration& operator-=(Duration& val1, const Duration& val2) { val1.m_millis -= val2.m_millis; return val1; } Duration operator*(const Duration& val1, unsigned int val2) { return Duration{val1.m_millis * val2}; } Duration operator*(const Duration& val1, float val2) { return Duration{static_cast<DurationBaseT>(val1.m_millis * val2)}; } Duration& operator*=(Duration& val1, unsigned int val2) { val1.m_millis *= val2; return val1; } Duration& operator*=(Duration& val1, float val2) { val1.m_millis = static_cast<DurationBaseT>(val1.m_millis * val2); return val1; } float operator/(const Duration& val1, const Duration& val2) { return val1.m_millis / (float)val2.m_millis; } Duration operator/(const Duration& val1, float val2) { return Duration{static_cast<DurationBaseT>(val1.m_millis / val2)}; } Duration& operator/=(Duration& val1, float val2) { val1.m_millis = static_cast<DurationBaseT>(val1.m_millis / val2); return val1; } Duration operator%(const Duration& val1, const Duration& val2) { return Duration{val1.m_millis % val2.m_millis}; } Duration& operator%=(Duration& val1, const Duration& val2) { val1.m_millis = val1.m_millis % val2.m_millis; return val1; } Duration Duration::epoch() { return Duration{0}; } Duration Duration::invalid() { return Duration{_DURATION_BASE_T_MAX}; } Duration Duration::fromMillis(DurationBaseT millis) { return Duration{millis}; } Duration Duration::fromSeconds(DurationBaseT seconds, DurationBaseT millis) { return Duration{seconds*1000 + millis}; } Duration Duration::fromMinutes(DurationBaseT minutes, DurationBaseT seconds, DurationBaseT millis) { return Duration{minutes*60000 + seconds*1000 + millis}; } Duration::Duration(const Duration& other) : m_millis{other.m_millis} { } Duration& Duration::operator=(const Duration& other) { m_millis = other.m_millis; return *this; } Duration::~Duration() = default; bool Duration::isInvalid() const { return m_millis == _DURATION_BASE_T_MAX; } DurationBaseT Duration::millisTotal() const { return m_millis; } DurationBaseT Duration::secondsTotal() const { return m_millis / 1000; } DurationBaseT Duration::minutesTotal() const { return m_millis / 60000; } DurationBaseT Duration::millisInSecond() const { return m_millis % 1000; } DurationBaseT Duration::secondsInMinute() const { return secondsTotal() % 60; } Duration::Duration(DurationBaseT millis) : m_millis{millis} { }
/* This file is part of SMonitor. Copyright 2015~2016 by: rayx email rayx.cn@gmail.com SMonitor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SMonitor 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "CMisc.h" #include "CClientLog.h" #include <QStringList> #include <QFontDatabase> #include <QRegExp> #include <QFile> #include <QDir> #include <QSettings> #include <QTextCodec> #include <QCryptographicHash> #include <QFileInfo> #include <QFileIconProvider> #include <QDebug> #include "common.h" #include "ZHead.h" #include <windows.h> #include <WinBase.h> #include <MMSystem.h> #include <IPHlpApi.h> #include <TlHelp32.h> #include <QStandardPaths> #pragma comment(lib, "Iphlpapi.lib") //32位操作系统,(系统64位,程序64位) 应用程序信息路径 #define WIN32_APPLOCATE ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall") //64位操作系统,程序32位 应用程序信息路径 #define WIN64_APPLOCATE ("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall") //定义获取系统位数函数指针 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process = NULL; bool CheckSysWow() { //获取系统位数 BOOL bIsSysWow32 = TRUE; fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); if(NULL != fnIsWow64Process) { fnIsWow64Process(GetCurrentProcess(), &bIsSysWow32); bIsSysWow32 = !bIsSysWow32; } return TRUE == bIsSysWow32; } QString CheckCurOsVer() { QString strOSVersionName = ""; SYSTEM_INFO info; //用SYSTEM_INFO结构判断64位AMD处理器 GetSystemInfo(&info); //调用GetSystemInfo函数填充结构 OSVERSIONINFOEX os; os.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(GetVersionEx((OSVERSIONINFO *)&os)) { //下面根据版本信息判断操作系统名称 switch(os.dwMajorVersion) { //判断主版本号 case 4: switch(os.dwMinorVersion){ //判断次版本号 case 0: if(os.dwPlatformId == VER_PLATFORM_WIN32_NT) strOSVersionName = "Microsoft Windows NT 4.0"; //1996年7月发布 else if(os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) strOSVersionName = "Microsoft Windows 95"; break; case 10: strOSVersionName = "Microsoft Windows 98"; break; case 90: strOSVersionName = "Microsoft Windows Me"; break; } break; case 5: switch(os.dwMinorVersion){ //再比较dwMinorVersion的值 case 0: strOSVersionName = "Microsoft Windows 2000"; //1999年12月发布 break; case 1: strOSVersionName = "Microsoft Windows XP"; //2001年8月发布 break; case 2: if(os.wProductType == VER_NT_WORKSTATION && info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) strOSVersionName = "Microsoft Windows XP Professional x64 Edition"; else if(GetSystemMetrics(SM_SERVERR2) == 0) strOSVersionName = "Microsoft Windows Server 2003"; //2003年3月发布 else if(GetSystemMetrics(SM_SERVERR2) != 0) strOSVersionName = "Microsoft Windows Server 2003 R2"; break; } break; case 6: switch(os.dwMinorVersion){ case 0: if(os.wProductType == VER_NT_WORKSTATION) strOSVersionName = "Microsoft Windows Vista"; else strOSVersionName = "Microsoft Windows Server 2008"; //服务器版本 break; case 1: if(os.wProductType == VER_NT_WORKSTATION) strOSVersionName = "Microsoft Windows 7"; else strOSVersionName = "Microsoft Windows Server 2008 R2"; break; } break; default: strOSVersionName = "UNKNOWN"; } if(os.dwMajorVersion > 6 || os.dwMajorVersion == 6 && os.dwMinorVersion > 1) { QSysInfo::WinVersion osVersion = QSysInfo::windowsVersion(); switch(osVersion) { case QSysInfo::WV_WINDOWS8: strOSVersionName = "Microsoft Windows 8"; break; case QSysInfo::WV_WINDOWS8_1: strOSVersionName = "Microsoft Windows 8.1"; break; default: strOSVersionName = "HIGH VERSION"; break; } } } return strOSVersionName; } //判断系统版本是否兼容 bool CMisc::IsOSSuit(QString strOS) { //驱动字符串格式错误,正确格式为 "名称##系统##位数" QStringList osDriverNames = strOS.split("##"); if(osDriverNames.count() != 3) { ClientLogger->AddLog(QString::fromLocal8Bit("驱动名称 [%1] 格式错误,请修改驱动名称为:名称##系统##系统位数, 如:驱动1##WIN8.1##WIN32").arg(strOS)); return false; } //获取系统版本 QString strSysVer = GetOSInfo().replace("Microsoft Windows ", "WIN").toUpper(); QString strSysBits = m_bIsSys32 ? "WIN32" : "WIN64"; if(strSysVer == "UNKNOWN" || strSysVer.isEmpty()) { ClientLogger->AddLog(QString::fromLocal8Bit("本地系统版本号未知 [%1] 驱动无法安装").arg(strOS)); return false; } QString osVersion = osDriverNames.at(1).toUpper().replace("WINDOWS", "WIN");//得到驱动名称中的系统名称 QString osSysBits = osDriverNames.at(2).toUpper().replace("WINDOWS", "WIN");//得到驱动名称中的位数 if((osVersion == "WINALL" || strSysVer.contains(osVersion)) && (strSysBits == osSysBits || osSysBits == "WINALL")) { ClientLogger->AddLog(QString::fromLocal8Bit("当前系统 [%1] 兼容驱动 [%2] ,自动执行驱动安装操作").arg(strSysVer + strSysBits).arg(strOS)); return true; } else { ClientLogger->AddLog(QString::fromLocal8Bit("当前系统 [%1] 不兼容驱动 [%2] ,请联系管理员").arg(strSysVer + strSysBits).arg(strOS)); return false; } } bool CMisc::m_bIsSys32 = CheckSysWow(); QStringList CMisc::m_UnSafeList; QString CMisc::m_strOsVer = CheckCurOsVer(); QFont CMisc::FontAwesome(int pointSize /* = 10 */) { int fontId = QFontDatabase::addApplicationFont(":/Resources/fontawesome-webfont.ttf"); QString family = QFontDatabase::applicationFontFamilies(fontId).at(0); return QFont(family, pointSize); } bool CMisc::GetLocalHostAddr(QString& IP, QString& MAC) { PIP_ADAPTER_INFO pAdapterInfo; DWORD AdapterInfoSize = 0; TCHAR szMac[32] = {0}; DWORD Err; Err = ::GetAdaptersInfo(NULL, &AdapterInfoSize); if((Err != 0) && (Err != ERROR_BUFFER_OVERFLOW)) { return false; } // 分配网卡信息内存 pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, AdapterInfoSize); if(pAdapterInfo == NULL) { return false; } if(::GetAdaptersInfo(pAdapterInfo, &AdapterInfoSize) != 0) { GlobalFree(pAdapterInfo); return false; } PIP_ADAPTER_INFO pAdapter = NULL; pAdapter = pAdapterInfo; while(pAdapter) { /*if(pAdapter->Type == MIB_IF_TYPE_ETHERNET) { sprintf_s(szMac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", pAdapter->Address[0], pAdapter->Address[1], pAdapter->Address[2], pAdapter->Address[3], pAdapter->Address[4], pAdapter->Address[5]); MAC = szMac; IP = pAdapter->IpAddressList.IpAddress.String; break; qDebug() << "IP: " << IP; }*/ sprintf_s(szMac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", pAdapter->Address[0], pAdapter->Address[1], pAdapter->Address[2], pAdapter->Address[3], pAdapter->Address[4], pAdapter->Address[5]); MAC = szMac; IP = pAdapter->IpAddressList.IpAddress.String; if(IP != "0.0.0.0" && IP != "127.0.0.1") break; pAdapter = pAdapter->Next; } ::GlobalFree(pAdapterInfo); return true; } QStringList CMisc::GetLogicalDriveStringList() { QStringList lDriverString; char szBuffer[MAX_PATH] = {"\0"}; int nLength = GetLogicalDriveStrings(MAX_PATH - 1, szBuffer); if (0 == nLength){ return QStringList(); } for(char *pDrive = szBuffer; *pDrive; pDrive += strlen(szBuffer) + 1) { if(DRIVE_FIXED == GetDriveType(pDrive)){ lDriverString << QString(pDrive).replace("\\", "/"); } } return lDriverString; } //获取文件的MD5码 bool CMisc::getFileMD5(const QString &strFile, QString &strMD5) { strMD5 = ""; QFile file(strFile); if (!file.open(QFile::ReadOnly)) { return false; } QByteArray md5Data = QCryptographicHash::hash(file.readAll(), QCryptographicHash::Md5); strMD5.append(md5Data.toHex()); strMD5 = strMD5.toLower(); file.close(); return true; } QString CMisc::getFileTemporary(const QString& strFile) { QString strMD5 = ""; QByteArray byteArray(strFile.toStdString().c_str()); QByteArray md5Data = QCryptographicHash::hash(byteArray, QCryptographicHash::Md5); strMD5.append(md5Data.toHex()); return strMD5; } //--------------------------------------------------------------------------------------------------- //描述:将一个压缩文件解压到某个目录下 // //参数:lpSrcFile - [in]待解压的文件名(全路径名称或相对路径),文件后缀只能为".zip"或".rar" // lpDesDir - [in]压缩文件中所有文件解压后的目标目录 // //返回值:如果压缩文件中所有的文件都解压成功,函数返回TRUE,否则返回FALSE. long CMisc::DecompressFiles(const QString& lpSrcFile, const QString& lpDesDir) { if(lpSrcFile.isEmpty() || lpDesDir.isEmpty()) return -1; //判断源文件后缀名是否为".zip"或".rar" QString strSrcFile = lpSrcFile; QFileInfo desFileinfo(lpSrcFile); qDebug() << desFileinfo.suffix(); if(desFileinfo.suffix() != "zip" && desFileinfo.suffix() != "rar") return -1; QString strDesDir = lpDesDir; if(0 != strDesDir.right(1).compare("\\")) strDesDir += QString("\\"); STARTUPINFO si; PROCESS_INFORMATION pi; QString strParam = QString(""); if("zip" == desFileinfo.suffix()) {//ZIP strParam = QString("7za.exe x -y \"%1\" -o\"%2\"").arg(lpSrcFile).arg(strDesDir); } else {//RAR strParam = QString("rar.exe x -y \"%1\" \"%2\"").arg(lpSrcFile).arg(strDesDir); } ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if(! CreateProcess(NULL, // No module name (use command line). (LPSTR)(LPCSTR)strParam.toLocal8Bit().constData(), // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. CREATE_NO_WINDOW, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi) // Pointer to PROCESS_INFORMATION structure. ) { DWORD dwLastError = GetLastError(); ClientLogger->AddLog(QString::fromLocal8Bit("[%1] CreateProcess启动失败,错误码[%2]").arg((LPSTR)(LPCSTR)strParam.toLocal8Bit().constData()).arg(dwLastError)); return -1; } WaitForSingleObject(pi.hProcess, INFINITE); bool bRet = false; DWORD dwExitCode = 0; if(GetExitCodeProcess(pi.hProcess, &dwExitCode)) { if(dwExitCode == STILL_ACTIVE) { ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 解压超时").arg(strParam)); TerminateProcess(pi.hProcess, 0); } else { switch(dwExitCode) { case 0: bRet = true; break; case 1: bRet = true; ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 解压成功,有部分文件被占用").arg(strParam)); break; default: ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 解压失败,错误码[%2]").arg(strParam).arg(dwExitCode)); dwExitCode = -5; break; } } } else {//获取退出码失败,以防万一,强制关闭进程 ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 获取解压返回值失败").arg(strParam)); TerminateProcess(pi.hProcess, 0); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return dwExitCode; } //通过zlib将一个文件解压至某个目录下 long CMisc::ZDecompressFiles(const QString& lpSrcFile, const QString& lpDesDir) { if(lpSrcFile.isEmpty() || lpDesDir.isEmpty()) return false; //判断源文件后缀名是否为".zip"或".rar" QString strSrcFile = lpSrcFile; QFileInfo desFileinfo(lpSrcFile); qDebug() << desFileinfo.suffix(); if(desFileinfo.suffix() != "zip" && desFileinfo.suffix() != "rar") return false; QString strDesDir = QFileInfo(lpDesDir).absoluteFilePath(); char chSrcPath[MAX_PATH] = {0}; char chDestPath[MAX_PATH] = {0}; memcpy(chSrcPath, lpSrcFile.toLocal8Bit().constData(), lpSrcFile.toLocal8Bit().size()); memcpy(chDestPath, strDesDir.toLocal8Bit().constData(), strDesDir.toLocal8Bit().size()); DWORD dwRet = UnZipToDirectory(chSrcPath, chDestPath); if(0 != dwRet) { DWORD dwSysRet = GetLastError(); if(dwSysRet == 5) { dwRet = 5; } ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 解压失败,错误码[%2] 系统错误码[%3]").arg(lpSrcFile).arg(dwRet).arg(dwSysRet)); } return dwRet; } //在指定目录查找应用程序的所有可执行文件 bool CMisc::FindExe(const QString& strDirName, QStringList &strFileArray) { if(strDirName.isEmpty()) return false; WIN32_FIND_DATA fd; HANDLE hSearch = NULL; bool bFinished = false; bool bReturn = true; ZeroMemory(&fd, sizeof(WIN32_FIND_DATA)); QString strDir = strDirName; if(! strDir.isEmpty() && strDir.right(1) != "\\") { strDir += "\\"; } QString strSearch = strDir + "*.*"; hSearch = FindFirstFile(strSearch.toLocal8Bit().constData(), &fd); if(INVALID_HANDLE_VALUE == hSearch) { return false; } while(! bFinished) { // "."表示当前目录 // ".."表示上一级目录 if((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..")) {//是一个子目录 strSearch = strDir + QString::fromLocal8Bit(fd.cFileName); //在子目录下继续查找e FindExe(strSearch, strFileArray); } else if(!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..")) {//为一个具体的文件 QString strFFile = QString::fromLocal8Bit(fd.cFileName); if(strFFile.length() > 4 && strFFile.right(4) == ".exe") { strFileArray.push_back(strFFile); } } if(! FindNextFile(hSearch, &fd)) { bFinished = true; } }//while(! bFinished) FindClose(hSearch); return bReturn; } //杀掉所有进程 bool CMisc::KillAllProcessesByTaskKiller(QStringList &strProcessArray) { int nCount = strProcessArray.count(); if(0 == nCount) return true; QString strShellCmd = "TASKKILL /F"; for(int i = 0; i < nCount; i++) { QString strProcessName = strProcessArray.at(i); if("SMonitorClient.exe" != strProcessName ) strShellCmd += " /IM \"" + strProcessName + "\""; } strShellCmd += " /T"; return ExcuteCmd(strShellCmd); } //杀掉自己 bool CMisc::KillSelf() { QString strShellCmd = "TASKKILL /F /IM \"SMonitorClient.exe\" /T"; return ExcuteCmd(strShellCmd); } //执行命令行 bool CMisc::ExcuteCmd(const QString& strApp) { if(strApp.isEmpty()) return false; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if(! CreateProcess(NULL, // No module name (use command line). (LPTSTR)(LPCTSTR)(strApp.toLocal8Bit().constData()), // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. CREATE_NO_WINDOW, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi) // Pointer to PROCESS_INFORMATION structure. ) { return false; } WaitForSingleObject(pi.hProcess, 5000); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return true; } //清空目标目录 bool CMisc::DeleteDirectory(const QString& DirName) { if(DirName.isEmpty()) return true; QDir dir(DirName); QString tmpdir = ""; if(!dir.exists()) { return true; } QFileInfoList fileInfoList = dir.entryInfoList(); foreach(QFileInfo fileInfo, fileInfoList) { if(fileInfo.fileName() == "." || fileInfo.fileName() == "..") continue; if(fileInfo.isDir()) { tmpdir = DirName + ("/") + fileInfo.fileName(); if(!MiscDeleteFile(tmpdir)) /**< 移除子目录 */ { return false; } } else if(fileInfo.isFile()) { QString ss = fileInfo.filePath(); if(!MiscDeleteFile(ss)) /**< 删除临时文件 */ { return false; } } else { ; } } dir.cdUp(); /**< 返回上级目录,因为只有返回上级目录,才可以删除这个目录 */ if(dir.exists(DirName)) { if(!MiscDeleteFile(DirName)) return false; } return true; } //执行外部EXE bool CMisc::ExcuteExe(const QString& strExePath, bool bSlient, long lWaitTime, bool bTerminateProcess/* = true*/) { if(strExePath.isEmpty()) return false; PROCESS_INFORMATION processInfoPC; STARTUPINFO startupInfoPC; startupInfoPC.cb = sizeof(STARTUPINFO); startupInfoPC.wShowWindow = bSlient ? SW_HIDE : SW_SHOWNORMAL; startupInfoPC.lpReserved = NULL; startupInfoPC.lpDesktop = NULL; startupInfoPC.lpTitle = NULL; startupInfoPC.dwFlags = STARTF_USESHOWWINDOW; startupInfoPC.cbReserved2 = 0; startupInfoPC.lpReserved2 = NULL; if(!CreateProcess(NULL, (char*)strExePath.toLocal8Bit().constData(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfoPC, &processInfoPC)) { DWORD dwLastError = GetLastError(); ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 启动失败,错误码[%2]").arg((char*)strExePath.toLocal8Bit().constData()).arg(dwLastError)); return false; } WaitForSingleObject(processInfoPC.hProcess, -1 == lWaitTime ? INFINITE : lWaitTime); if(bTerminateProcess) { DWORD dwExitCode = 0; if(GetExitCodeProcess(processInfoPC.hProcess, &dwExitCode)) { if(dwExitCode == STILL_ACTIVE) { TerminateProcess(processInfoPC.hProcess, 0); } } else {//获取退出码失败,以防万一,强制关闭进程 TerminateProcess(processInfoPC.hProcess, 0); } } return true; } //执行外部EXE bool CMisc::ShellExcuteExe(const QString& strExePath, bool bSlient, long lWaitTime, bool bTerminateProcess/* = true*/) { if(strExePath.isEmpty()) return false; SHELLEXECUTEINFO si = {0}; si.cbSize = sizeof(SHELLEXECUTEINFO); si.fMask = SEE_MASK_NOCLOSEPROCESS; si.hwnd = NULL; si.lpVerb = "runas"; char chFile[256]; memset(chFile, 0, sizeof(chFile)); memcpy(chFile, strExePath.toLocal8Bit().constData(), strExePath.toLocal8Bit().size()); si.lpFile = chFile; si.lpParameters = ""; si.lpDirectory = NULL; si.nShow = bSlient ? SW_HIDE : SW_SHOWNORMAL; si.hInstApp = NULL; if(!ShellExecuteEx(&si)) { DWORD dwLastError = GetLastError(); ClientLogger->AddLog(QString::fromLocal8Bit("[%1] 启动失败,错误码[%2]").arg((char*)strExePath.toLocal8Bit().constData()).arg(dwLastError)); return false; } WaitForSingleObject(si.hProcess, -1 == lWaitTime ? INFINITE : lWaitTime); if(bTerminateProcess) { DWORD dwExitCode = 0; if(GetExitCodeProcess(si.hProcess, &dwExitCode)) { if(dwExitCode == STILL_ACTIVE) { TerminateProcess(si.hProcess, 0); } } else {//获取退出码失败,以防万一,强制关闭进程 TerminateProcess(si.hProcess, 0); } } CloseHandle(si.hProcess); return true; } //获取系统版本号 QString CMisc::GetOSInfo() { return m_strOsVer; } bool CMisc::IsOsVerHigherXP() { SYSTEM_INFO info; //用SYSTEM_INFO结构判断64位AMD处理器 GetSystemInfo(&info); //调用GetSystemInfo函数填充结构 OSVERSIONINFOEX os; os.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(GetVersionEx((OSVERSIONINFO *)&os)) { if(os.dwMajorVersion >= 6) return true; else return false; } return true;//默认win7以上系统 } //判断指定名称的软件本机是否已安装 bool CMisc::IsAppInstall(const QString& strAppName) { //根据注册表获取本机应用程序目录 if(IsSysWin32()) {//32位系统 return _IsAppInstall(WIN32_APPLOCATE, strAppName); } else {//64位系统有可能两个路径都存在 if(_IsAppInstall(WIN32_APPLOCATE, strAppName)) return true; return _IsAppInstall(WIN64_APPLOCATE, strAppName); } return false; } //判断指定名称的软件本机是否已安装 bool CMisc::_IsAppInstall(const char* lpSubKey, const QString& strAppName) { if(NULL == lpSubKey || strAppName.isEmpty()) return false; QString strCompareAppName = strAppName; strCompareAppName = strCompareAppName.toUpper(); bool bRet = false; //打开注册表 HKEY hSubKey; REGSAM openMark; if(0 == strcmp(lpSubKey, WIN32_APPLOCATE) && !IsSysWin32()) openMark = KEY_READ | KEY_WOW64_64KEY; else openMark = KEY_READ ; long lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, openMark, &hSubKey); if(ERROR_SUCCESS == lResult) {//打开成功 DWORD dwIndex = 0; TCHAR szKeyName[256] = {0}; DWORD cbName = 256 * sizeof(TCHAR); //开始枚举注册表项 lResult = RegEnumKeyEx(hSubKey, dwIndex++, szKeyName, &cbName, 0, NULL, NULL, NULL); while (ERROR_SUCCESS == lResult && ERROR_MORE_DATA != lResult) {//找到一个应用程序的注册表项 QString strKey = QString::fromLocal8Bit(szKeyName); if(-1 != strKey.indexOf(strCompareAppName)) { bRet = true; break; } //根据属性displayname判断 HKEY hItem; if(ERROR_SUCCESS == RegOpenKeyEx(hSubKey, szKeyName, 0, openMark, &hItem)) { char chBuf[256] = {0}; DWORD dwSize = sizeof(chBuf); DWORD dwRegType; //得到应用程序名 if(ERROR_SUCCESS == RegQueryValueEx(hItem, "DisplayName", 0, &dwRegType, (LPBYTE)chBuf, &dwSize)) { strKey = QString::fromLocal8Bit(chBuf); if(-1 != strKey.indexOf(strCompareAppName)) { bRet = true; break; } } } //继续枚举注册表项 cbName = 256 * sizeof(TCHAR); lResult = RegEnumKeyEx(hSubKey, dwIndex++, szKeyName, &cbName, 0, NULL, NULL, NULL); } } //关闭注册表 RegCloseKey(hSubKey); return bRet; } //判断系统位数 bool CMisc::IsSysWin32() { return m_bIsSys32; } bool CMisc::IsNeedUpdate(const QString& localVersion, const QString& svrVersion) { if(svrVersion.length() != 8) {//服务器日期格式不正确 return false; } if(localVersion.length() != 8) {//本地日期格式不对 return true; } if(localVersion == svrVersion) return false; //比较年 QString strlocal = localVersion.left(4); QString strSvr = svrVersion.left(4); int nCompareResult = CompareStringNum(strlocal, strSvr); if(nCompareResult < 0) return true; else if(nCompareResult > 0) return false; //比较月 strlocal = localVersion.mid(4, 2); strSvr = svrVersion.mid(4, 2); nCompareResult = CompareStringNum(strlocal, strSvr); if(nCompareResult < 0) return true; else if(nCompareResult > 0) return false; //比较日 strlocal = localVersion.mid(6, 2); strSvr = svrVersion.mid(6, 2); nCompareResult = CompareStringNum(strlocal, strSvr); if(nCompareResult < 0) return true; else if(nCompareResult > 0) return false; return false; } //比较数字型字符串 返回值: 0 相等 -1 小于 1 大于 -2 str1格式错误 2 str2格式错误 int CMisc::CompareStringNum(const QString& str1, const QString& str2) { bool bOk = false; long lNum1 = str1.toLong(&bOk); if(!bOk) return -2; long lNum2 = str2.toLong(&bOk); if(!bOk) return 2; if(lNum1 < lNum2) return -1; else if(lNum1 > lNum2) return 1; else return 0; } //将指定文件投射到桌面快捷方式 bool CMisc::LinkToDesktop(const QString& strFilePath, const QString linkName) { if(!CMisc::IsFileExist(strFilePath)) return false; QString strLinkFile = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); if(!CMisc::IsFileExist(strLinkFile)) return false; strLinkFile += "\\" + linkName + ".lnk"; return QFile::link(strFilePath, strLinkFile); } QString CMisc::Encrypt(const QString& src) { QByteArray byteArray = src.toLatin1(); QByteArray result = qCompress(byteArray); QString strEncryBuffer = result.toBase64(); qDebug() << strEncryBuffer; return strEncryBuffer; } QString CMisc::Decrypt(const QString& src) { QByteArray byteArray = QByteArray::fromBase64(src.toLocal8Bit()); QString result = qUncompress(byteArray); return result; } //通过读取版本号文件获得应用程序版本号 QString CMisc::GetVersionFileVersion(const QString& dir) { QString strVersion = ""; if(CMisc::IsFileExist(dir)) { QString strVersionFile = dir; if(dir.right(1) != "\\" && dir.right(1) != "/") { strVersionFile += "\\"; } strVersionFile += VERSIONFILE; QFile file; file.setFileName(strVersionFile); if(file.open(QIODevice::ReadOnly)) { //设置文件共享打开 file.setPermissions(QFileDevice::ReadOther | QFileDevice::WriteOther | QFileDevice::ExeOther); strVersion = file.readAll().constData(); strVersion = strVersion.trimmed(); file.close(); } } return strVersion; } //获取文件内容 bool CMisc::GetFileContent(const QString& strFilePath, QString &strContent) { QFile file; file.setFileName(strFilePath); if(file.open(QIODevice::ReadOnly)) { //设置文件共享打开 file.setPermissions(QFileDevice::ReadOther | QFileDevice::WriteOther | QFileDevice::ExeOther); strContent = file.readAll().constData(); strContent = strContent.trimmed(); file.close(); return true; } return false; } //通过域名解析出IP地址 QStringList CMisc::GetIpByHostName(const QString& strHostName) { QStringList strIpList; HOSTENT *pIPHost; if((pIPHost = gethostbyname(strHostName.toLocal8Bit().constData())) != NULL) { int i = 0; while(pIPHost->h_addr_list[i]) { char ip[32]; memcpy(&ip, inet_ntoa(*((struct in_addr *)pIPHost->h_addr_list[i])), sizeof(ip)); strIpList.push_back(ip); i++; } } return strIpList; } QStringList CMisc::BrandsNotNeedPasswd() { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); return settings.value("Passwd/BrandNotNeedPasswd", QStringList()).toStringList(); } void CMisc::SetBrandsNotNeedPasswd(const QString& brand) { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); QStringList brands = settings.value("Passwd/BrandNotNeedPasswd").toStringList(); brands.removeAll(brand); brands.append(brand); settings.setValue("Passwd/BrandNotNeedPasswd", brands); } void CMisc::SetBrandsNeedPasswd(const QString& brand) { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); QStringList brands = settings.value("Passwd/BrandNotNeedPasswd").toStringList(); brands.removeAll(brand); settings.setValue("Passwd/BrandNotNeedPasswd", brands); } QString CMisc::GetBrandPasswd(const QString& brand) { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); return settings.value(QString("Passwd/%1").arg(brand), QString()).toString(); } //读取服务器CrossLink状态 QString CMisc::GetCrossLinkRunInstallState() { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); return settings.value("Local/InstallState", QString()).toString(); } //设置服务器存储的本地CrossLink安装状态 void CMisc::SetCrossLinkRunInstallState(const QString& state) { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); settings.setValue("Local/InstallState", state); } void CMisc::SetBrandPasswd(const QString& brand, const QString& passwd) { QSettings settings(HKCU, QSettings::NativeFormat); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); settings.setValue(QString("Passwd/%1").arg(brand), passwd); } bool CMisc::IsFileExist(const char* pszNameFile) { if(NULL == pszNameFile) return false; bool bRes = false; WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFile(pszNameFile, &FindFileData); if(INVALID_HANDLE_VALUE != hFind) { bRes = true; FindClose(hFind); } return bRes; } bool CMisc::IsFileExist(const QString& strNameFile) { return IsFileExist(strNameFile.toLocal8Bit().constData()); } //删除文件/目录 bool CMisc::MiscDeleteFile(const QString& strPath) { if(!CMisc::IsFileExist(strPath)) return true; SHFILEOPSTRUCT fileSH; ZeroMemory((void*)&fileSH, sizeof(SHFILEOPSTRUCT)); TCHAR chShortName[MAX_PATH] = {0}; GetShortPathName(strPath.toLocal8Bit().constData(), chShortName, MAX_PATH); fileSH.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; fileSH.hNameMappings = NULL; fileSH.hwnd = NULL; fileSH.lpszProgressTitle = NULL; fileSH.pFrom = chShortName; fileSH.pTo = NULL; fileSH.wFunc = FO_DELETE; return 0 == SHFileOperation(&fileSH); } //判断目录是否安全 bool CMisc::isSafeDirectory(const QString& strPath) { if(strPath.isEmpty()) return false; QString strCompare = strPath.toLower(); strCompare = strCompare.replace("/", "\\"); int nSize = strCompare.length(); if(strCompare[nSize - 1] == '\\') { strCompare = strCompare.remove(nSize - 1, 1); } if(m_UnSafeList.isEmpty()) { m_UnSafeList << "c:" << "c:\\windows" << "c:\\program files" << "c:\\program files (x86)" << "c:\\windows\\system32" << "c:\\windows\\system" << "d:" << "d:\\windows" << "d:\\program files" << "d:\\program files (x86)" << "d:\\windows\\system32" << "d:\\windows\\system" << "e:" << "e:\\windows" << "e:\\program files" << "e:\\program files (x86)" << "e:\\windows\\system32" << "e:\\windows\\system" << "f:" << "f:\\windows" << "f:\\program files" << "f:\\program files (x86)" << "f:\\windows\\system32" << "f:\\windows\\system" << "g:" << "g:\\windows" << "g:\\program files" << "g:\\program files (x86)" << "g:\\windows\\system32" << "g:\\windows\\system" << "h:" << "g:\\windows" << "h:\\program files" << "h:\\program files (x86)" << "h:\\windows\\system32" << "h:\\windows\\system"; } if(m_UnSafeList.contains(strCompare, Qt::CaseInsensitive)) { return false; } return true; } unsigned long CMisc::GetMiscLastError() { return GetLastError(); } QIcon CMisc::GetFileIcon(const QString& path) { //如果获取错误则返回默认图标 QIcon icon(":/Resources/normal.png"); //QFileInfo info(path); //if(info.isFile()) //{ // QFileIconProvider iconProvider; // //icon = iconProvider.icon(info); // icon = iconProvider.icon(info.absoluteFilePath()); //} if(path.contains("CrosslinkRun", Qt::CaseInsensitive)) { icon = QIcon(":/Resources/crossrun.png"); } return icon; }
#include <algorithm> #include <cassert> #include <deque> #include <iostream> #include <string> #include <vector> using ull = unsigned long long; class BigInterger { public: BigInterger(int n) { while (n) { num.push_front(n % 10); n /= 10; } } BigInterger(const std::deque<int>& num) : num(num) { // Do nothing. } BigInterger operator+(const BigInterger& rhs) { auto lit = num.rbegin(); auto rit = rhs.num.rbegin(); int carry{}; std::deque<int> result; while (lit != num.rend() || rit != rhs.num.rend()) { int value = carry; if (lit != num.rend()) { value += *lit; ++lit; } if (rit != rhs.num.rend()) { value += *rit; ++rit; } carry = value / 10; result.push_front(value % 10); } if (carry) { result.push_front(carry); } return BigInterger(result); } friend std::ostream& operator<<(std::ostream& os, const BigInterger& bi) { for (auto n : bi.num) { std::cout << n; } return os; } private: std::deque<int> num; }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n; std::cin >> n; if (n <= 1) { std::cout << n << '\n'; return 0; } BigInterger pre = 1, now = 1; n -= 1; while (--n) { BigInterger temp = pre; pre = now; now = temp + now; } std::cout << now << '\n'; return 0; }
#include "SearchView.hpp" SearchController * SearchView::makeController(Model *m) { return new SearchController(m, this); } SearchView::SearchView(QWidget *parent) : View(parent) { setAttribute(Qt::WA_DeleteOnClose); setFixedSize(310, 550); auto vl = new QVBoxLayout(this); checkA = new QGroupBox(QStringLiteral("Articoli")); checkA->setCheckable(true); checkA->setChecked(true); vl->addWidget(checkA); connect(checkA, SIGNAL(toggled(bool)), this, SLOT(_checkedA(bool))); auto flA = new QFormLayout(); checkA->setLayout(flA); nome = new QLineEdit(); flA->addRow(QStringLiteral("Nome"), nome); costoMax = new QLineEdit(); flA->addRow(QStringLiteral("Costo massimo"), costoMax); prezzoMax = new QLineEdit(); flA->addRow(QStringLiteral("Prezzo massimo"), prezzoMax); checkCD = new QGroupBox(QStringLiteral("CD")); checkCD->setCheckable(true); checkCD->setChecked(false); vl->addWidget(checkCD); connect(checkCD, SIGNAL(toggled(bool)), this, SLOT(_checkedCD(bool))); auto flCD = new QFormLayout(); checkCD->setLayout(flCD); annoCD = new QLineEdit(); flCD->addRow(QStringLiteral("Anno"), annoCD); artista = new QLineEdit(); flCD->addRow(QStringLiteral("Artista"), artista); compilation = new QCheckBox(); flCD->addRow(QStringLiteral("Compilation"), compilation); checkC = new QGroupBox(QStringLiteral("Computer")); checkC->setCheckable(true); checkC->setChecked(false); vl->addWidget(checkC); connect(checkC, SIGNAL(toggled(bool)), this, SLOT(_checkedC(bool))); auto flC = new QFormLayout(); checkC->setLayout(flC); usatoC = new QCheckBox(); flC->addRow(QStringLiteral("Usato"), usatoC); portatile = new QCheckBox(); flC->addRow(QStringLiteral("Portatile"), portatile); checkS = new QGroupBox(QStringLiteral("Smartphone")); checkS->setCheckable(true); checkS->setChecked(false); vl->addWidget(checkS); connect(checkS, SIGNAL(toggled(bool)), this, SLOT(_checkedS(bool))); auto flS = new QFormLayout(); checkS->setLayout(flS); usatoS = new QCheckBox(); flS->addRow(QStringLiteral("Usato"), usatoS); iphone = new QCheckBox(); flS->addRow(QStringLiteral("iPhone"), iphone); auto b = new QPushButton(QStringLiteral("Cerca")); vl->addWidget(b); connect(b, SIGNAL(clicked()), this, SLOT(searchStart())); auto r = new QPushButton(QStringLiteral("Rimuovi elementi trovati")); vl->addWidget(r); connect(r, SIGNAL(clicked()), this, SLOT(deleteSearched())); } SearchController * SearchView::getController() { return dynamic_cast<SearchController *>(View::getController()); } void SearchView::closeEvent(QCloseEvent *event) { emit closing(); event->accept(); } void SearchView::_checkedA(bool on) { nome->setEnabled(on); costoMax->setEnabled(on); prezzoMax->setEnabled(on); if (on) { checkCD->setChecked(false); checkC->setChecked(false); checkS->setChecked(false); } } void SearchView::_checkedCD(bool on) { annoCD->setEnabled(on); artista->setEnabled(on); compilation->setEnabled(on); if (on) { checkA->setChecked(false); checkC->setChecked(false); checkS->setChecked(false); } } void SearchView::_checkedC(bool on) { usatoC->setEnabled(on); portatile->setEnabled(on); if (on) { checkCD->setChecked(false); checkA->setChecked(false); checkS->setChecked(false); } } void SearchView::_checkedS(bool on) { usatoS->setEnabled(on); iphone->setEnabled(on); if (on) { checkCD->setChecked(false); checkC->setChecked(false); checkA->setChecked(false); } } void SearchView::searchStart() { emit searchStart(checkA->isChecked(), nome->text(), costoMax->text(), prezzoMax->text(), checkCD->isChecked(), annoCD->text(), artista->text(), compilation->isChecked(), checkC->isChecked(), usatoC->isChecked(), portatile->isChecked(), checkS->isChecked(), usatoS->isChecked(), iphone->isChecked(), false); } void SearchView::deleteSearched() { emit searchStart(checkA->isChecked(), nome->text(), costoMax->text(), prezzoMax->text(), checkCD->isChecked(), annoCD->text(), artista->text(), compilation->isChecked(), checkC->isChecked(), usatoC->isChecked(), portatile->isChecked(), checkS->isChecked(), usatoS->isChecked(), iphone->isChecked(), true); }
// # include <iostream> // using namespace std; // int main () { // string name, surname; // double hour, net_payment, gross_payment; // const double payment = 6.75; // const double tax = 0.1; // cout << "Hi, please enter your name: " << endl; // cin >> name; // cout << "Also, please enter your surname: " << endl; // cin >> surname; // cout << "Hello" << " " << name << " " << surname << endl; // cout << "Please enter your working hour: " << endl; // cin >> hour; // net_payment = payment * hour; // gross_payment = net_payment - (net_payment * tax); // cout << "Your Gross payment should be $" << gross_payment << endl; // cout << "Detailed information :" << "working hour: " << hour << ", " << "Net payment: " << net_payment << ", " << "Gross payment: " << gross_payment << endl; // system("pause"); // return 0; // } //======================================================================= // # include "stdfna.h" # include <iostream> # include <string> # include <cmath> using namespace std; int main () { // string stdFirstName, stdSurname; // float stdHours, stdGrossPay, stdTax, stdNetPay; string FirstName, LastName; const float payPerHour = 6.75; int hoursWorked; cout<<"Enter in students first name:"<<endl; cin>>FirstName; cout<<"Enter in students last name: "<<endl; cin>>LastName; cout<<"How many hours did they work? "<<endl; cin>>hoursWorked; float grossPay = payPerHour * hoursWorked; float tax = grossPay / 10; //get 10% of grossPay float netPay = grossPay - tax; // char userAnswer != 'y'; // while (userAnswer != 'n' && userAnswer != 'N') { // cout << "Enter the student's First Name :"; // cin >> fName; // cout << "Enter the student's Last Name :"; // cin >> lName; // while(userAnswer != 'n' && userAnswer != 'N' || userAnswer = 'y' && userAnswer = 'Y') { cout << "Student Paysheet: " << FirstName << " " << LastName << endl; cout << "GrossPay: $" << grossPay << " Tax: $" <<tax<< endl; cout << "NetPay: $" << netPay << endl; // } // cout << "Do You Want to Continue(Y/N)" << endl; // } system("pause"); return 0; }
#pragma once #include <iostream> #include <new> #include <array> #include <string> #include <random> #include <cassert> using namespace std; #define DEFAULT_SIZE 4 #define nBelow0 "n is below 0 in CircularDeque!" static void checkIndexOutOfBounds(int32_t r, int32_t size, string op, string type); static void checkIndexOutOfBounds(int32_t r, int32_t size, string op, string type) { if (r >= size || r < 0) { throw out_of_range( "Tried to " + op + " element at rank " + to_string(r) + " on array of size " + to_string(size) + " in " + type ); } } class ArrayDataStructure { public: virtual uint32_t size() = 0; const int32_t operator[](const int32_t index) { return getElemAt(index); } virtual int32_t getElemAt(int32_t) = 0; virtual void setElemAt(int32_t, int32_t) = 0; virtual void insertElemAt(int32_t, int32_t) = 0; virtual int32_t removeElemAt(int32_t) = 0; virtual void insertLast(int32_t) = 0; virtual int32_t removeLast() = 0; virtual string toString() = 0; virtual string toStringPretty() = 0; };
// vnrsharedmemory.cc // 5/7/2014 jichi #include "vnrsharedmemory/vnrsharedmemory.h" #include <QtCore/QSharedMemory> /** Private class */ class VnrSharedMemoryPrivate { public: enum { LanguageCapacity = 4 }; struct Cell { qint8 status; qint64 hash; //qint32 signature; qint8 role; char language[LanguageCapacity]; qint32 textSize; wchar_t text[1]; private: Cell() {} // disable constructor }; int cellCount; int cellSize; // cell size, instead of total size QSharedMemory *memory; explicit VnrSharedMemoryPrivate(QObject *parent) : cellCount(0), cellSize(0), memory(new QSharedMemory(parent)) {} VnrSharedMemoryPrivate(const QString &key, QObject *parent) : memory(new QSharedMemory(key, parent)) {} int textCapacity() const { return qMax<int>(0, (cellSize - sizeof(Cell)) / 2); } quint8 *data(int i) { return static_cast<quint8 *>(memory->data()) + cellSize * i; } const quint8 *constData(int i) const { return static_cast<const quint8 *>(memory->constData()) + cellSize * i; } Cell *cell(int i) { return reinterpret_cast<Cell *>(data(i)); } const Cell *constCell(int i) const { return reinterpret_cast<const Cell *>(constData(i)); } }; /** Public class */ VnrSharedMemory::VnrSharedMemory(QObject *parent) : Base(parent), d_(new D(this)) {} VnrSharedMemory::VnrSharedMemory(const QString &key, QObject *parent) : Base(parent), d_(new D(key, this)) {} VnrSharedMemory::~VnrSharedMemory() { delete d_; } // Shared Memory QString VnrSharedMemory::key() const { return d_->memory->key(); } void VnrSharedMemory::setKey(const QString &v) { d_->memory->setKey(v); } int VnrSharedMemory::cellCount() const { return d_->cellCount; } int VnrSharedMemory::cellSize() const { return d_->cellSize; } bool VnrSharedMemory::create(int size, int count, bool readOnly) { d_->cellSize = size; d_->cellCount = count; return d_->memory->create(size * count, readOnly ? QSharedMemory::ReadOnly : QSharedMemory::ReadWrite); } bool VnrSharedMemory::attach(bool readOnly) { return d_->memory->attach(readOnly ? QSharedMemory::ReadOnly : QSharedMemory::ReadWrite); } bool VnrSharedMemory::detach() { return d_->memory->detach(); } bool VnrSharedMemory::isAttached() const { return d_->memory->isAttached(); } bool VnrSharedMemory::lock() { return d_->memory->lock(); } bool VnrSharedMemory::unlock() { return d_->memory->unlock(); } QString VnrSharedMemory::errorString() const { return d_->memory->errorString(); } bool VnrSharedMemory::hasError() const { return d_->memory->error() != QSharedMemory::NoError; } int VnrSharedMemory::dataTextCapacity() const { return d_->textCapacity(); } // Contents const char *VnrSharedMemory::constData(int i) const { return reinterpret_cast<const char *>(d_->constData(i)); } qint64 VnrSharedMemory::dataHash(int i) const { if (auto p = d_->constCell(i)) return p->hash; else return 0; } void VnrSharedMemory::setDataHash(int i, qint64 v) { if (auto p = d_->cell(i)) p->hash = v; } qint8 VnrSharedMemory::dataStatus(int i) const { if (auto p = d_->constCell(i)) return p->status; else return 0; } void VnrSharedMemory::setDataStatus(int i, qint8 v) { if (auto p = d_->cell(i)) p->status = v; } //qint32 VnrSharedMemory::dataSignature(int i) const //{ // if (auto p = d_->constCell(i)) // return p->signature; // else // return 0; //} // //void VnrSharedMemory::setDataSignature(qint32 v) //{ // if (auto p = d_->cell(i)) // p->signature = v; //} qint8 VnrSharedMemory::dataRole(int i) const { if (auto p = d_->constCell(i)) return p->role; else return 0; } void VnrSharedMemory::setDataRole(int i, qint8 v) { if (auto p = d_->cell(i)) p->role = v; } QString VnrSharedMemory::dataLanguage(int i) const { if (auto p = d_->constCell(i)) return QString::fromLatin1(p->language); else return QString(); } void VnrSharedMemory::setDataLanguage(int i, const QString &v) { if (auto p = d_->cell(i)) { if (v.isEmpty()) p->language[0] = 0; else if (v.size() < D::LanguageCapacity) { auto data = v.toLatin1(); for (int i = v.size() - 1; i >= 0; i--) // iterate in reverse order p->language[i] = data[i]; } else {// truncate string auto data = v.toLatin1(); p->language[D::LanguageCapacity - 1] = 0; for (int i = D::LanguageCapacity - 2; i >= 0; i--) // iterate in reverse order p->language[i] = data[i]; } } } QString VnrSharedMemory::dataText(int i) const { if (auto p = d_->constCell(i)) if (p->textSize > 0 && p->textSize <= d_->textCapacity()) return QString::fromUtf16(p->text, p->textSize); return QString(); } void VnrSharedMemory::setDataText(int i, const QString &v) { if (auto p = d_->cell(i)) { int limit = d_->textCapacity(); if (v.size() <= limit) { p->textSize = v.size(); //v.toWCharArray(p->text); memcpy(p->text, v.utf16(), v.size()); } else { QString w = v.left(limit); p->textSize = w.size(); //w.toWCharArray(p->text); memcpy(p->text, w.utf16(), w.size()); } } } // EOF
#pragma once namespace aeEngineSDK { /*************************************************************************************************/ /* @struct LOGGER_DATA /* /* @brief This is an empty structure that it is defined in aeLogger.cpp /*************************************************************************************************/ struct LOGGER_DATA; /*************************************************************************************************/ /* @class aeLogger /* /* @brief This is a logger module /*************************************************************************************************/ class AE_UTILITY_EXPORT aeLogger : public Module<aeLogger> { /*************************************************************************************************/ /* Constructors /*************************************************************************************************/ public: aeLogger(String& FileName); virtual ~aeLogger(); private: aeLogger(const aeLogger&); aeLogger& operator=(const aeLogger&); protected: /*************************************************************************************************/ /* @fn virtual void aeLogger::OnStartUp() /* /* @brief Override if you want to module to be notified once it has been constructed on start. /*************************************************************************************************/ void OnStartUp() override; /*************************************************************************************************/ /* @fn virtual void aeLogger::OnShutDown() /* /* @brief Override if you want to module to be notified once it has been constructed on shut /* down. /*************************************************************************************************/ void OnShutDown() override; public: /*************************************************************************************************/ /* @fn void aeLogger::Log(const String& Tag, const String& Msg, const ANSICHAR* FuncName, const ANSICHAR* sourceFile, uint32 lineNum); /* /* @brief Writes into the log file. /* /* @param Tag The tag. /* @param Msg The message. /* @param FuncName Name of the function. /* @param sourceFile Source file. /* @param lineNum The line number. /*************************************************************************************************/ void Log(const String& Tag, const String& Msg, const String& FuncName, const String& SourceFile, const uint32& LineNum); /*************************************************************************************************/ /* @fn void aeLogger::SaveToFile(); /* /* @brief Saves to file. /*************************************************************************************************/ void SaveToFile(); private: LOGGER_DATA* m_pData; //This variable stores all the data necessary to work }; } #define AE_START_LOGGER(FileName) aeEngineSDK::aeLogger::StartUp(String(FileName)); #define AE_CLOSE_LOGGER() aeEngineSDK::aeLogger::ShutDown(); #define AE_FATAL(str) aeEngineSDK::aeLogger::Instance().Log("Fatal", str, __FUNCTION__, __FILE__, __LINE__); #if defined(_DEBUG) #define AE_ERROR(str) aeEngineSDK::aeLogger::Instance().Log("Error", str, __FUNCTION__, __FILE__, __LINE__); #define AE_WARNING(str) aeEngineSDK::aeLogger::Instance().Log("Warning", str, __FUNCTION__, __FILE__, __LINE__); #define AE_INFO(str) aeEngineSDK::aeLogger::Instance().Log("INFO", str, nullptr, nullptr, 0); #define AE_LOG(tag, str) aeEngineSDK::aeLogger::Instance().Log(tag, str, nullptr, nullptr, 0); #define AE_ASSERT(expr) aeEngineSDK::aeLogger::Instance().Log("Assert", aeEngineSDK::ToString((bool)(expr)).c_str(), __FUNCTION__, __FILE__, __LINE__); #else #define AE_ERROR(str) (void)sizeof(str); #define AE_WARNING(str) (void)sizeof(str); #define AE_INFO(str) (void)sizeof(str); #define AE_LOG(tag, str) (void)sizeof(tag); (void)sizeof(str); #define AE_ASSERT(expr) (void)sizeof(expr); #endif
#include <iostream> #include "pass.hpp" int main() { PassRegistry::get_pass_registry()->invoke("hello")(); return 0; }
#ifndef ALARMOO_H #define ALARMOO_H #include "synch.h" class Alarm { public: List *sleepQ; Alarm() { sleepQ = NULL; } ~Alarm() { delete sleepQ; } void GoForSleep(int howLong); void wakeUp(); }; #endif
#ifndef MYNETWORKACCESSMANAGER_H #define MYNETWORKACCESSMANAGER_H #include <QNetworkAccessManager> #include <QUrl> #include <qnetworkreply.h> #include <qauthenticator.h> #include <qnetworkreply.h> #include <qsslerror.h> class NetworkAccessViewer; struct OffileDataStruct { QUrl url; QMap<QByteArray,QByteArray> headers; QByteArray data; OffileDataStruct(){} OffileDataStruct(const QNetworkRequest& req, QByteArray dt) { url = req.url(); QByteArray header; foreach( header, req.rawHeaderList() ) { headers[header] = req.rawHeader( header ); } data = dt; } }; class MyNetworkAccessManager : public QNetworkAccessManager { Q_OBJECT public: MyNetworkAccessManager(QObject *parent); ~MyNetworkAccessManager(); void setOfflineMode(bool state); void rePostRequestsToServer(); protected: QNetworkReply * createRequest ( Operation op, const QNetworkRequest & req, QIODevice * outgoingData = 0 ); private: NetworkAccessViewer *viewer; QMainWindow *mainWindow; QList<OffileDataStruct> offileDataList; bool offlineMode; public slots: void slotError(QNetworkReply::NetworkError); void slotProxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator); void slotSslErrors(QNetworkReply *reply, const QList<QSslError> &errors); void slotOnFinished(QNetworkReply* reply); }; #endif // MYNETWORKACCESSMANAGER_H
/***************************************************************************************************************** * File Name : RootToLeafPathSum.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\trees\page06\RootToLeafPathSum.h * Created on : Dec 23, 2013 :: 1:09:52 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef ROOTTOLEAFPATHSUM_H_ #define ROOTTOLEAFPATHSUM_H_ bool doesSumRootToLeafExists(tNode *ptr,unsigned int counter){ if(ptr == NULL){ return targetSum == 0?true:false; } if(ptr->left == NULL && ptr->right == NULL){ return ptr->value - counter == 0?true:false; } if(counter <= 0){ return false; } return doesSumRootToLeafExists(ptr->left,counter-ptr->value) || doesSumRootToLeafExists(ptr->right,counter - ptr->value); } bool doesSumRootToLeafExistsV2(tNode *ptr,int runningSum,int targetSum){ if(ptr == NULL){ return targetSum == 0?true:false; } if(ptr->left == NULL && ptr->right == NULL){ return ptr->value + runningSum == targetSum?true:false; } return doesSumRootToLeafExistsV2(ptr->left,runningSum+ptr->value,targetSum) || doesSumRootToLeafExistsV2(ptr->right,runningSum+ptr->value,targetSum); } bool doesSumRootToLeafExistsHashmap(tNode *ptr,int targetSum){ if(ptr == NULL){ return targetSum == 0?true:false; } tHashmap *hashmapOfTree = getHashmapFormOfTree(ptr,1); hash_map<unsigned int,tNode *> indexNodeMap = hashmapOfTree->indexNodeMap; hash_map<unsigned int,tNode *>::iterator itToIndexNodeMap; unsigned int currentIndex; int sum; for(itToIndexNodeMap = indexNodeMap.begin();itToIndexNodeMap != indexNodeMap.end();itToIndexNodeMap++){ currentIndex = itToIndexNodeMap->first; if(indexNodeMap.find(2*currentIndex) == indexNodeMap.end() && indexNodeMap.find(2*currentIndex + 1) == indexNodeMap.end()){ sum = indexNodeMap.find(0)->second->value; while(currentIndex > 0){ sum += indexNodeMap.find(currentIndex)->second->value; currentIndex /= 2; } if(sum == targetSum){ return true; } } } return false; } bool doesSumRootToLeafExistsParentPtr(tPNode *ptr,int targetSum){ if(ptr == NULL){ return targetSum == 0?true:false; } if(ptr->left == NULL && ptr->right == NULL){ int sum = 0; tPNode *currentNode = ptr; while(currentNode != NULL){ sum += currentNode->value; currentNode = currentNode->parent; } return sum == targetSum?true:false; } return doesSumRootToLeafExistsParentPtr(ptr->left,targetSum) || doesSumRootToLeafExistsParentPtr(ptr->right,targetSum); } bool doesSumRootToLeafExistsPreOrderIterative(tPNode *ptr,int targetSum){ if(ptr == NULL){ return NULL; } stack<tPNode *> auxSpace; hash_map<uint32_t,int> nodeSumMap; hash_map<uint32_t,int>::iterator itToNodeSumMap; tPNode *currentNode; int currentSum; while(!auxSpace.empty()){ currentNode = auxSpace.top(); if(currentNode->parent == NULL){ nodeSumMap.insert(pair<uint32_t,int>((uint32_t)currentNode,currentNode->value)); }else{ currentSum = nodeSumMap.find((uint32_t)currentNode->parent); nodeSumMap.insert(pair<uint32_t,int>((uint32_t)currentNode,currentSum + currentNode->value)); } auxSpace.pop(); if(currentNode->left == NULL && currentNode->right == NULL){ if(currentSum + currentNode->value == targetSum){ return true; } }else{ if(currentNode->right != NULL){ auxSpace.push(currentNode->right); } if(currentNode->left != NULL){ auxSpace.push(currentNode->left); } } } return false; } #endif /* ROOTTOLEAFPATHSUM_H_ */ /************************************************* End code *******************************************************/
// Sharna Hossain // CSC 111 // Lab 12 | multiplication_table.cpp #include <iostream> #include <iomanip> using namespace std; int main() { int rows, columns, digits = 1; cout << "Enter the number of rows: "; cin >> rows; cout << "Enter the number of columns: "; cin >> columns; int bigNum = rows * columns; while(bigNum != 0){ bigNum /= 10; digits++; } // Column Header cout << setw(digits) << " "; for (int c = 1; c <= columns; c++) { cout << setw(digits) << c; } cout << "\n"; for (int r = 1; r <= rows; r++) { // Row Header cout << setw(digits) << r; for (int c = 1; c <= columns; c++) { cout << setw(digits) << c * r; } cout << "\n"; } return 0; }
/* You are given N, and for a given N x N chessboard, find a way to place N queens such that no queen can attack any other queen on the chess board. A queen can be killed when it lies in the same row, or same column, or the same diagonal of any of the other queens. You have to print all such configurations. Note: Don't print anything if there isn't any valid configuration. Input Format: The first line of input contains an integer, that denotes the value of N. Output Format : In the output, you have to print every board configuration in a new line. Every configuration will have N*N board elements printed row wise and are separated by space. The cells where queens are safe and placed, are denoted by value 1 and remaining all cells are denoted by value 0. Please refer to sample test cases for more clarity. Constraints : 1 <= N <= 10 Time Limit: 1 second Sample Input 1: 4 Sample Output 1 : 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 Explanation: The first and second configuration are shown in the image below. Here, 1 denotes the placement of a queen and 0 denotes an empty cell. Please note that in both the configurations, no pair of queens can kill each other. */ #include<bits/stdc++.h> using namespace std; int board[11][11]; bool isPossible(int n,int row,int col){ //check upper column for(int i=row-1;i>=0;i--){ if(board[i][col]==1){ return false; } } //check upper left diagonal for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){ if(board[i][j]==1){ return false; } } //check upper right diagonal for(int i=row-1,j=col+1;i>=0 && j<n;i--,j++){ if(board[i][j]==1){ return false; } } return true; } void nQueenHelper(int n,int row){ if(row==n){ //we have reached some solution //print the board matrix //return for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<board[i][j]<<" "; } } cout<<endl; return; } //place at all possible positions and move on to smaller problem for(int j=0;j<n;j++){ if(isPossible(n,row,j)){ board[row][j]=1; nQueenHelper(n,row+1); board[row][j]=0; } } return; } void placeNQueens(int n){ memset(board,0,11*11*sizeof(int)); nQueenHelper(n,0); } int main(){ int n; cin>>n; placeNQueens(n); return 0; }
#include<iostream> using namespace std; class Node{ public: int data; Node* left = nullptr; Node* right = nullptr; Node(){ } Node(int data){ this->data = data; } }; Node* root = nullptr; class BST{ public: static void insert(Node* tree, Node* newNode); static void inorder(Node* ptr); }; void BST::insert(Node* tree, Node* newNode) { if(root == nullptr){ root = new Node(newNode->data); root->left = nullptr; root->right = nullptr; cout<<"Root Node is Added"<<endl; return; } if(tree->data == newNode->data){ cout << "Element is already in the tree..." << endl; return; } if(tree->data > newNode->data){ if(tree->left != nullptr){ insert(tree->left, newNode); }else{ tree->left = newNode; tree->left->left = nullptr; tree->left->right = nullptr; cout << "Node is added to the left..." << endl; return; } } if(tree->data < newNode->data){ if(tree->right != nullptr){ insert(tree->right, newNode); }else{ tree->right = newNode; tree->right->left = nullptr; tree->right->right = nullptr; cout << "Node is added to the right..." << endl; return; } } } void BST::inorder(Node *ptr) { if (root == nullptr) { cout<<"The Tree is empty"<<endl; return; } if (ptr != nullptr) { inorder(ptr->left); cout<<ptr->data<<" "; inorder(ptr->right); } } int main(){ int numberOfelements = 0; cout << "How much elements you want to insert in the tree: "; cin >> numberOfelements; for(int i=0; i<numberOfelements; i++){ Node* temp = new Node; cout<<"Enter the number to be inserted : "; cin>>temp->data; BST::insert(root, temp); } BST::inorder(root); return 0; }
// // Created by adam on 23.12.18. // #ifndef AAL_MSTGRAPH_H #define AAL_MSTGRAPH_H #include "../Algorithm/Implementation.h" class MSTgraph { std::vector<std::vector<edgeDef> > MSTonCC; std::vector<unsigned> isolatedVertices; std::vector<edgeDef> MSTonGraph; public: void addVectorToMSTonCC(std::vector<edgeDef> nextMSTonCC); void addToIsolatedVertices(unsigned vertexId); void computeMSTonGraph(); void print() const; unsigned getMSTValue() const; }; #endif //AAL_MSTGRAPH_H
/* * @lc app=leetcode.cn id=986 lang=cpp * * [986] 区间列表的交集 */ // @lc code=start #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) { int a = 0, b = 0; vector<vector<int> > res; while (a < A.size() && b < B.size()) { int a1 = A[a][0], a2 = A[a][1]; int b1 = B[b][0], b2 = B[b][1]; if(b2 >= a1 && a2 >= b1){ res.push_back({max(a1, b1), min(a2, b2)}); } if(b2 < a2){ ++b; }else{ ++a; } } return res; } }; // @lc code=end
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int n, m; cin >> n >> m; vector<vector<int>> v; for(int bit=0; bit<(1 << n); bit++){ vector<int> t; for(int i=0; i<n; i++){ if(bit & (1<<i)) t.push_back(1); else t.push_back(0); } v.push_back(t); } vector<vector<int>> s(m); for(int i=0; i<m; i++){ int k; cin >> k; for(int j=0; j<k; j++){ int sw; cin >> sw; s[i].push_back(sw); } } vector<int> p(m); for(int i=0; i<m; i++) cin >> p[i]; int ans = 0; for(int i=0; i<v.size(); i++){ int cnt = 0; for(int j=0; j<m; j++){ int tmp = 0; for(int l=0; l<s[j].size(); l++){ if(v[i][s[j][l]-1] == 1) tmp++; } if(tmp%2 == p[j]) cnt++; } if(cnt == m) ans++; } cout << ans << endl; }
#include "drawClockFrame.h" #include "cursorSet.h" #include <stdio.h> #include <ctime> #include <conio.h> #include <windows.h> #include "time.h" #include <string> #include "webClock.h" #include <iomanip> #include <iostream> #include "clockMenus.h" void drawClockFrame::drawNewClockFrame(int startRow, int startCol, cursorSet newCursorLoc) { //draws the frame around the clocks newCursorLoc.setNewCursor(startRow, startCol); cout << setfill('*') << setw(30) << ""; cout << setfill(' ') << setw(10) << ""; cout << setfill('*') << setw(30) << ""; cout << setfill(' '); newCursorLoc.setNewCursor(startRow + 1, startCol); cout << "*"; cout << setw(21) << right << "24-HOUR CLOCK" << setw(8) << right << "*"; cout << setw(10) << ""; cout << "*"; cout << setw(21) << right << "12-HOUR CLOCK" << setw(8) << right << "*"; newCursorLoc.setNewCursor(startRow + 2, startCol); cout << "*" << setw(29) << right << "*" << setw(11) << right << "*" << setw(29) << right << "*"; newCursorLoc.setNewCursor(startRow + 3, startCol); cout << setfill('*') << setw(30) << ""; cout << setfill(' ') << setw(10) << ""; cout << setfill('*') << setw(30) << ""; } void drawClockFrame::hideCursorBlink() { //hide the blinking cursor HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO info; info.dwSize = 100; info.bVisible = FALSE; SetConsoleCursorInfo(consoleHandle, &info); } void drawClockFrame::showMainMenu(cursorSet newCursorLoc) { //title and menu on main clock newCursorLoc.setNewCursor(0, 0); cout << "Welcome to WebClock. Press 'q' to quit, press 'i' to change the time." << endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2008-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** @author Haavard Molland <haavardm@opera.com> ** @author Alexei Khlebnikov <alexeik@opera.com> ** */ #ifndef CRYPTO_CERTIFICATE_CHAIN_IMPL_H_ #define CRYPTO_CERTIFICATE_CHAIN_IMPL_H_ #ifdef CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION #include "modules/libcrypto/include/CryptoCertificateChain.h" #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/x509.h" #include "modules/libopeay/openssl/x509v3.h" class CryptoCertificateChain_impl : public CryptoCertificateChain { public: ~CryptoCertificateChain_impl(); static OP_STATUS Make(CryptoCertificateChain *&chain); virtual OP_STATUS AddToChainBase64(const char *certificate_der); virtual OP_STATUS AddToChainBinary(const UINT8 *certificate_der, int length); virtual int GetNumberOfCertificates() const { return m_certificate_list.GetCount(); } virtual const CryptoCertificate* GetCertificate(int chain_index) const { return m_certificate_list.Get(chain_index); } virtual CryptoCertificate* GetCertificate(int chain_index) { return m_certificate_list.Get(chain_index); } virtual CryptoCertificate* RemoveCertificate(int chain_index) { return m_certificate_list.Remove(chain_index); } virtual OP_STATUS VerifyChainSignatures(VerifyStatus& reason, const CryptoCertificateStorage* ca_storage); /** Implementation-specific methods. */ STACK_OF(X509)* GetStackOfX509() const { return m_certificate_chain; } private: CryptoCertificateChain_impl(); OP_STATUS UpdateCertificateList(); OpAutoVector<CryptoCertificate> m_certificate_list; STACK_OF(X509) *m_certificate_chain; X509_STORE_CTX *m_certificate_storage; }; #endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION #endif /* CRYPTO_CERTIFICATE_CHAIN_IMPL_H_ */
#include <iostream> int get_fuel1(int num) { if((num / 3) - 2 > 0) return (num/3)-2; return 0; } int get_fuel2(int num) { int sum = 0; if((num/3) - 2 <= 0) return 0; return sum += (num/3) - 2 + get_fuel2((num/3) - 2); } int main() { int num, sum1 = 0, sum2 = 0; while(std::cin >> num) { sum1 += get_fuel1(num); sum2 += get_fuel2(num); } std::cout << sum1 << std::endl; std::cout << sum2 << std::endl; }
#include "UnitsTest.h" // RsaToolbox #include "Definitions.h" #include "General.h" using namespace RsaToolbox; // Qt #include <QString> UnitsTest::UnitsTest(QObject *parent) : TestClass(parent) { } void UnitsTest::units_data() { QTest::addColumn<Units>("units"); QTest::addColumn<QString>("string"); QTest::newRow("seconds") << Units::Seconds << "s"; QTest::newRow("hertz" ) << Units::Hertz << "Hz"; QTest::newRow("radians") << Units::Radians << "Rad"; QTest::newRow("degrees") << Units::Degrees << "Deg"; QTest::newRow("ohms" ) << Units::Ohms << "Ohm"; QTest::newRow("siemens") << Units::Siemens << "S"; QTest::newRow("watts" ) << Units::Watts << "W"; QTest::newRow("dB" ) << Units::dB << "dB"; QTest::newRow("dBW" ) << Units::dBW << "dBW"; QTest::newRow("dBm" ) << Units::dBm << "dBm"; } void UnitsTest::units() { QFETCH(Units, units); QFETCH(QString, string); QCOMPARE(toString(units), string); } void UnitsTest::prefix_data() { QTest::addColumn<SiPrefix>("prefix"); QTest::addColumn<double>("value"); QTest::addColumn<QString>("string"); QTest::newRow("tera") << SiPrefix::Tera << 1.0E12 << "T"; QTest::newRow("giga") << SiPrefix::Giga << 1.0E9 << "G"; QTest::newRow("mega") << SiPrefix::Mega << 1.0E6 << "M"; QTest::newRow("kilo") << SiPrefix::Kilo << 1.0E3 << "K"; QTest::newRow("none") << SiPrefix::None << 1.0 << "" ; QTest::newRow("milli") << SiPrefix::Milli << 1.0E-3 << "m"; QTest::newRow("micro") << SiPrefix::Micro << 1.0E-6 << "u"; QTest::newRow("nano") << SiPrefix::Nano << 1.0E-9 << "n"; QTest::newRow("pico") << SiPrefix::Pico << 1.0E-12 << "p"; QTest::newRow("femto") << SiPrefix::Femto << 1.0E-15 << "f"; } void UnitsTest::prefix() { QFETCH(SiPrefix, prefix); QFETCH(double, value); QFETCH(QString, string); QCOMPARE(toDouble(prefix), value); QCOMPARE(toString(prefix), string); QCOMPARE(toSiPrefix(string), prefix); } void UnitsTest::formatValue_data() { QTest::addColumn<double>("value"); QTest::addColumn<int>("decimals"); QTest::addColumn<SiPrefix>("prefix"); QTest::addColumn<Units>("units"); QTest::addColumn<QString>("result"); //Columns: test value decimals prefix units result QTest::newRow("10 MHz") << 10.0 << 3 << SiPrefix::Mega << Units::Hertz << "10 MHz"; QTest::newRow("1 GHz") << 1.0 << 3 << SiPrefix::Giga << Units::Hertz << "1 GHz"; QTest::newRow("1.234 dBm") << 1.234 << 3 << SiPrefix::Giga << Units::Watts << "1.234 GW"; } void UnitsTest::formatValue() { QFETCH(double, value); QFETCH(int, decimals); QFETCH(SiPrefix, prefix); QFETCH(Units, units); QFETCH(QString, result); QCOMPARE(RsaToolbox::formatValue(value, decimals, units, prefix), result); }
#include "Synergist.h" #include <iostream> size_t SynergistHealth[] = { 0, 25, 25, 31, 34, 38, 38, 41, 47, 52, 59, 66, 71, 75, 81, 85, 90, 95, 103, 110, 125 }; size_t SynergistAttack[] = { 0, 13, 15, 15, 17, 19, 19, 21, 23, 25, 30, 33, 37, 43, 48, 50, 54, 55, 60, 63, 65 }; size_t ExperienceSNeed[] = { 0, 0, 10, 30, 55, 70, 100, 130, 165, 200, 240, 285, 325, 370, 420, 475, 530, 590, 650, 720 }; float SynergistDefence[] = { 0, 15, 15, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; Synergist::Synergist() { NormalAttackmultiplier = 0.40f; Name = "Synergist"; } Synergist::~Synergist() { } void Synergist::Init(int Level) { SetisPressed(false); SetisSelected(false); //if (Level > 0 && Level < 21) //{ // SetLevel(Level); // SetHealth(SynergistHealth[Level - 1]); // SetMaxHealth(SynergistHealth[Level - 1]); // SetAttack(SynergistAttack[Level - 1]); // SetDefence(SynergistDefence[Level - 1]); //} //if (Level > 20) //{ // float Levelscale = Level - 20; // float finalscale = 1 + (Levelscale * 0.01f); // SetLevel(Level); // SetHealth((SynergistHealth[19] * finalscale)); // SetMaxHealth(SynergistHealth[19] * finalscale); // SetAttack(SynergistAttack[19] * finalscale); // SetDefence(SynergistDefence[19] * finalscale); //} ////SetPosition(Position_Middle); for (int i = 0; i < Level; i++) { LevelUp(true); } } void Synergist::LevelUp(bool init) { if (init) Level++; else { if (ExperiencePoints > ExperienceSNeed[Level + 1]) Level++; else return; } ExperiencePoints = (float)ExperienceSNeed[Level]; SetHealth(SynergistHealth[Level]); SetMaxHealth(SynergistHealth[Level]); SetAttack(SynergistAttack[Level]); SetDefence((size_t)SynergistDefence[Level]); SetDamageMitigation(); if (Level <= 10) { Skill* skill = new Skill(); if (Level == 10) { skill->SetName("Quake"); skill->SetActionCost(60); skill->SetMaxTurnCooldown(6); skill->SetStatusEffect(6, "Stun"); skill->SetRequiredPosition(2, true); skill->SetRequiredPosition(3, true); for (int i = 0; i < 3; i++) { skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); } else if (Level == 5) { skill->SetName("Power Breakdown"); skill->SetActionCost(30); skill->SetMaxTurnCooldown(4); skill->SetStatusEffect(3, "Debuff"); for (int i = 0; i < 3; i++) { skill->SetRequiredPosition(i, true); skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); } else if (Level == 4) { skill->SetName("Unholy Gift"); skill->SetActionCost(35); skill->SetMaxTurnCooldown(1); skill->SetRequiredPosition(2, true); skill->SetRequiredPosition(3, true); for (int i = 0; i < 3; i++) { skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); } else if (Level == 3) { skill->SetName("Dark Hail"); skill->SetActionCost(40); skill->SetMaxTurnCooldown(2); skill->SetStatusEffect(2,"Stun"); for (int i = 0; i < 3; i++) { skill->SetRequiredPosition(i, true); skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); } else if (Level == 1) { skill->SetName("Basic Attack"); skill->SetActionCost(15); for (int i = 0; i < 3; i++) { skill->SetRequiredPosition(i, true); skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); skill = new Skill(); skill->SetName("Life Drain"); skill->SetActionCost(25); skill->SetStatusEffect(2, "Debuff"); for (int i = 0; i < 3; i++) { skill->SetRequiredPosition(i, true); skill->SetSelectableTarget(i, true); } SkillList.push_back(skill); } } for (vector<Skill*>::iterator it = SkillList.begin(); it != SkillList.end(); it++) { Skill* SkillItr = (*it); if (SkillItr->GetName() == "Unholy Gift") SkillItr->SetDamage((int)(Attack * 0.5)); else if (SkillItr->GetName() == "Life Drain") SkillItr->SetDamage((int)(Attack * 0.3)); else if (SkillItr->GetName() == "Dark Hail") SkillItr->SetDamage((int)(Attack*0.3)); else if (SkillItr->GetName() == "Basic Attack") SkillItr->SetDamage((int)(Attack * 0.4)); } } void Synergist::Update(double dt) { }
/** * @file CommandBase.cxx * @author Krzysztof Ciba (Krzysztof.Ciba@NOSPAMagh.edu.pl) * @date 23/11/2006 * @brief Definition of CommandBase class. */ #include "CommandBase.h" void CLUE::CommandBase::parse_recipe() { std::stringstream inout(m_recipe); std::vector<std::string> sentence; std::string word; while ( inout >> word ) sentence.push_back(word); std::vector<std::string>::iterator it; for (it = sentence.begin(); it != sentence.end(); ++it ) { std::string chunk = (*it); if ( chunk[0] == '%' && ( (*it).length() > 3 ) ) { // we got an index // remove (,#,) chars std::replace((*it).begin(), (*it).end(), '(', ' '); std::replace((*it).begin(), (*it).end(), ')', ' '); std::replace((*it).begin(), (*it).end(), '#', ' '); inout.clear(); inout.seekg( std::ios_base::beg ); inout.str( (*it) ); int lo, up; inout >> word >> lo >> up; m_dims.push_back( CLUE::FORTRAN_DIM( lo, up ) ); } } // reverting to get F77 indexes std::reverse(m_dims.begin(), m_dims.end()); m_dim = m_dims.size(); };
#include <string.h> #include "ConvexMesh.h" //ある軸に投影(軸に投影して、どこかの軸で重なっていなければ衝突していない) //p147あたり参照 void GetProjection(float &pmin, float &pmax,const ConvexMesh *convexMesh,const Vector3 &axis){ assert(convexMesh); float t_pmin = FLT_MAX; float t_pmax = -FLT_MAX; for (unsigned int i = 0; i < convexMesh->m_numVertices; i++){ float proj = dot(axis, convexMesh->m_vertices[i]); t_pmin = MIN(t_pmin, proj); t_pmax = MAX(t_pmax, proj); } pmin = t_pmin; pmax = t_pmax; } bool CreateConvexMesh(ConvexMesh *convexMesh, const float *vertices, unsigned int numVertices, const GLuint *indices, unsigned int numIndices, const Vector3 &scale = Vector3(1.0f)) { //不正データのチェック assert(convexMesh); assert(vertices); assert(indices); assert(dot(scale, scale)>0.0f); //最大頂点数を超えたらダメ(TODO:大きい頂点数は?(現在はstackoverflowになる)) if (numVertices > CONVEX_MESH_MAX_VERTICES || numIndices > CONVEX_MESH_MAX_FACETS * 3) { return false; } //メモリ確保 memset(convexMesh, 0, sizeof(ConvexMesh)); // 頂点バッファ作成 for (unsigned int i = 0; i<numVertices; i++) { convexMesh->m_vertices[i][0] = vertices[i * 3]; convexMesh->m_vertices[i][1] = vertices[i * 3 + 1]; convexMesh->m_vertices[i][2] = vertices[i * 3 + 2]; convexMesh->m_vertices[i] = mulPerElem(scale, convexMesh->m_vertices[i]); } convexMesh->m_numVertices = numVertices; // 面バッファ作成 unsigned int nf = 0; for (unsigned int i = 0; i<numIndices / 3; i++) { //インデックスから面の3点を決定 Vector3 p[3] = { convexMesh->m_vertices[indices[i * 3]], convexMesh->m_vertices[indices[i * 3 + 1]], convexMesh->m_vertices[indices[i * 3 + 2]] }; //法線 Vector3 normal = cross(p[1] - p[0], p[2] - p[0]); float areaSqr = lengthSqr(normal); // 面積 if (areaSqr > EPSILON * EPSILON) {// 縮退面は登録しない convexMesh->m_facets[nf].vertId[0] = (unsigned char)indices[i * 3]; convexMesh->m_facets[nf].vertId[1] = (unsigned char)indices[i * 3 + 1]; convexMesh->m_facets[nf].vertId[2] = (unsigned char)indices[i * 3 + 2]; convexMesh->m_facets[nf].normal = normal / sqrtf(areaSqr); nf++; } } convexMesh->m_numFacets = nf; // エッジバッファ作成(辺に対する面と頂点を登録) unsigned char edgeIdTable[CONVEX_MESH_MAX_VERTICES*CONVEX_MESH_MAX_VERTICES / 2]; memset(edgeIdTable, 0xff, sizeof(edgeIdTable)); unsigned int ne = 0; for (unsigned int i = 0; i < convexMesh -> m_numFacets; i++) { Facet &facet = convexMesh->m_facets[i]; for (unsigned int e = 0; e<3; e++) { unsigned int vertId0 = MIN(facet.vertId[e % 3], facet.vertId[(e + 1) % 3]); unsigned int vertId1 = MAX(facet.vertId[e % 3], facet.vertId[(e + 1) % 3]); unsigned int tableId = vertId1*(vertId1 - 1) / 2 + vertId0; if (edgeIdTable[tableId] == 0xff) { // 初回時は登録のみ convexMesh->m_edges[ne].facetId[0] = i; convexMesh->m_edges[ne].facetId[1] = i; convexMesh->m_edges[ne].vertId[0] = (unsigned char)vertId0; convexMesh->m_edges[ne].vertId[1] = (unsigned char)vertId1; convexMesh->m_edges[ne].type = EdgeTypeConvex; // 凸エッジで初期化 facet.edgeId[e] = ne; edgeIdTable[tableId] = ne; ne++; if (ne > CONVEX_MESH_MAX_EDGES) { return false; } } else { // 共有面を見つけたので、エッジの角度を判定 assert(edgeIdTable[tableId] < CONVEX_MESH_MAX_EDGES); Edge &edge = convexMesh->m_edges[edgeIdTable[tableId]]; Facet &facetB = convexMesh->m_facets[edge.facetId[0]]; assert(edge.facetId[0] == edge.facetId[1]); // エッジに含まれないA面の頂点がB面の表か裏かで判断 Vector3 s = convexMesh->m_vertices[facet.vertId[(e + 2) % 3]]; Vector3 q = convexMesh->m_vertices[facetB.vertId[0]]; float d = dot(s - q, facetB.normal); if (d < -EPSILON) { edge.type = EdgeTypeConvex; } else if (d > EPSILON) { // 本来ここに来てはいけない edge.type = EdgeTypeConcave; } else { edge.type = EdgeTypeFlat; } edge.facetId[1] = i; } } } convexMesh->m_numEdges = ne; return true; }
////////////////////////////////////////////////////////////////////////// // Bwindows.h 包含了编写 Windows 程序所必须的头文件, // 一些常用自定义函数的声明、类型、常数、类的定义 // 类包括: // CBApp 类: 管理应用程序全局信息 // CBHashLK:长整数型 key 的哈希表类 // CBHashStrK:字符串型 key 的哈希表类 // CBRecycledArr:带回收站的数组类 // CBRecycledArrInt:整型版带回收站的数组类 // CHeapMemory: 用全局对象维护所有通过 new 分配的内存指针 // // 包含本 h 文件即可使用全局对象指针:pApp(->)获得程序全局信息,但只有 // 同时包含 BForm 的模块(封装 WinMain 函数)后才能获得正确的信息 // // 包含本 h 文件即可使用全局对象:HM (管理以 new 开辟的内存指针) // 调用 HM.AddPtr(p, bArrNew); 添加管理一个以 new 开辟的内存指针 // 调用 HM.Dispose(); 释放目前所管理的所有动态内存(程序结束时也会自动释放) ////////////////////////////////////////////////////////////////////////// #pragma once #define OEMRESOURCE // to use any of the OBM_ constants #include <windows.h> #include <stdlib.h> // 需用 atoi、atof 等函数 #include <memory.h> #include <string.h> #include <tchar.h> #include <math.h> // EventsGenerator 函数返回此值表示要调用默认的窗口程序,否则不再调用默认的窗口程序 #define gc_APICEventsGenDefautRet 0xFEEEEEEE enum EStandardIcon // 系统图标 { IDI_Application = (int)IDI_APPLICATION, IDI_Asterisk = (int)IDI_ASTERISK, IDI_Error = (int)IDI_ERROR, IDI_Exclamation = (int)IDI_EXCLAMATION, IDI_Hand = (int)IDI_HAND, IDI_Information = (int)IDI_INFORMATION, IDI_Question = (int)IDI_QUESTION, IDI_Warning = (int)IDI_WARNING, IDI_Winlogo = (int)IDI_WINLOGO }; #define gc_IDStandCursorIDBase 0x10000 enum EStandardCursor // 系统鼠标指针形状,为对应 API 常量 + gc_IDStandCursorIDBase(目的是为与资源 ID 区分,资源 ID 均小于 gc_IDStandCursorIDBase) { IDC_AppStarting = (int)IDC_APPSTARTING + gc_IDStandCursorIDBase, // Standard arrow and small hourglass IDC_Arrow = (int)IDC_ARROW + gc_IDStandCursorIDBase, // Standard arrow IDC_Cross = (int)IDC_CROSS + gc_IDStandCursorIDBase, // Cross hair IDC_Hand = (int)MAKEINTRESOURCE(32649) + gc_IDStandCursorIDBase, // Windows NT 5.0 and later: Hand IDC_Help = (int)IDC_HELP + gc_IDStandCursorIDBase, // Arrow and question mark IDC_IBeam = (int)IDC_IBEAM + gc_IDStandCursorIDBase, // I-beam IDC_Icon = (int)IDC_ICON + gc_IDStandCursorIDBase, // Obsolete for applications marked version 4.0 or later. IDC_No = (int)IDC_NO + gc_IDStandCursorIDBase, // Slashed circle IDC_Size = (int)IDC_SIZE + gc_IDStandCursorIDBase, // Obsolete for applications marked version 4.0 or later. Use IDC_SIZEALL. IDC_SizeAll = (int)IDC_SIZEALL + gc_IDStandCursorIDBase, // Four-pointed arrow pointing north, south, east, and west IDC_SizeNESW = (int)IDC_SIZENESW + gc_IDStandCursorIDBase, // Double-pointed arrow pointing northeast and southwest IDC_SizeNS = (int)IDC_SIZENS + gc_IDStandCursorIDBase, // Double-pointed arrow pointing north and south IDC_SizeNWSE = (int)IDC_SIZENWSE + gc_IDStandCursorIDBase, // Double-pointed arrow pointing northwest and southeast IDC_SizeWE = (int)IDC_SIZEWE + gc_IDStandCursorIDBase, // Double-pointed arrow pointing west and east IDC_UpArrow = (int)IDC_UPARROW + gc_IDStandCursorIDBase, // Vertical arrow IDC_Wait = (int)IDC_WAIT + gc_IDStandCursorIDBase // Hourglass }; enum EOEMBmp // 系统 OEM 位图 { Obm_Btncorners = OBM_BTNCORNERS, Obm_Btsize = OBM_BTSIZE, Obm_Check = OBM_CHECK, Obm_Checkboxes = OBM_CHECKBOXES, Obm_Close = OBM_CLOSE, Obm_Reduce = OBM_REDUCE, Obm_Combo = OBM_COMBO, Obm_Reduced = OBM_REDUCED, Obm_Dnarrow = OBM_DNARROW, Obm_Restore = OBM_RESTORE, Obm_Dnarrowd = OBM_DNARROWD, Obm_Restored = OBM_RESTORED, Obm_Dnarrowi = OBM_DNARROWI, Obm_Rgarrow = OBM_RGARROW, Obm_Lfarrow = OBM_LFARROW, Obm_Rgarrowd = OBM_RGARROWD, Obm_Lfarrowd = OBM_LFARROWD, Obm_Rgarrowi = OBM_RGARROWI, Obm_Lfarrowi = OBM_LFARROWI, Obm_Size = OBM_SIZE, Obm_Mnarrow = OBM_MNARROW, Obm_Uparrow = OBM_UPARROW, Obm_Uparrowd = OBM_UPARROWD, // Obm_Old_Restore = OBM_OLD_RESTORE, // Bitmap names that begin with OBM_OLD represent bitmaps used by 16-bit versions of Windows earlier than 3.0. // Obm_Old_Rgarrow = OBM_OLD_RGARROW, // Obm_Old_Uparrow = OBM_OLD_UPARROW, // Obm_Old_Zoom = OBM_OLD_ZOOM, // Obm_Old_Close = OBM_OLD_CLOSE, // Obm_Old_Dnarrow = OBM_OLD_DNARROW, // Obm_Old_Lfarrow = OBM_OLD_LFARROW, // Obm_Old_Reduce = OBM_OLD_REDUCE, Obm_Uparrowi = OBM_UPARROWI, Obm_Zoom = OBM_ZOOM, Obm_Zoomd = OBM_ZOOMD }; enum EOEMIcon // 系统 OEM 图标 { Oic_Sample = OIC_SAMPLE, Oic_Hand = OIC_HAND, Oic_Ques = OIC_QUES, Oic_Bang = OIC_BANG, Oic_Note = OIC_NOTE, #if(WINVER >= 0x0400) Oic_Winlogo = OIC_WINLOGO, Oic_Warning = OIC_WARNING, Oic_Error = OIC_ERROR, Oic_Information = OIC_INFORMATION, #endif /* WINVER >= 0x0400 */ }; enum EOEMCursor // 系统 OEM 光标 { Ocr_Normal = OCR_NORMAL, Ocr_Ibeam = OCR_IBEAM, Ocr_Wait = OCR_WAIT, Ocr_Cross = OCR_CROSS, Ocr_Up = OCR_UP, Ocr_Size = OCR_SIZE, /* OBSOLETE: use OCR_SIZEALL */ Ocr_Icon = OCR_ICON, /* OBSOLETE: use OCR_NORMAL */ Ocr_Sizenwse = OCR_SIZENWSE, Ocr_Sizenesw = OCR_SIZENESW, Ocr_Sizewe = OCR_SIZEWE, Ocr_Sizens = OCR_SIZENS, Ocr_Sizeall = OCR_SIZEALL, Ocr_Icocur = OCR_ICOCUR, /* OBSOLETE: use OIC_WINLOGO */ Ocr_No = OCR_NO, #if(WINVER >= 0x0500) Ocr_Hand = OCR_HAND, #endif /* WINVER >= 0x0500 */ #if(WINVER >= 0x0400) Ocr_Appstarting = OCR_APPSTARTING, #endif /* WINVER >= 0x0400 */ }; enum EColorType // 系统颜色 { COLOR_ActiveBorder = COLOR_ACTIVEBORDER, COLOR_ActiveCaption = COLOR_ACTIVECAPTION, COLOR_AppWorkspace = COLOR_APPWORKSPACE, COLOR_BackGround = COLOR_BACKGROUND, COLOR_BtnFace = COLOR_BTNFACE, COLOR_BtnShadow = COLOR_BTNSHADOW, COLOR_BtnText = COLOR_BTNTEXT, COLOR_CaptionText = COLOR_CAPTIONTEXT, COLOR_GrayText = COLOR_GRAYTEXT, COLOR_Highlight = COLOR_HIGHLIGHT, COLOR_HighlightText = COLOR_HIGHLIGHTTEXT, COLOR_InactiveBorder = COLOR_INACTIVEBORDER, COLOR_InactiveCaption = COLOR_INACTIVECAPTION, COLOR_Menu = COLOR_MENU, COLOR_MenuText = COLOR_MENUTEXT, COLOR_ScrollBar = COLOR_SCROLLBAR, COLOR_Window = COLOR_WINDOW, COLOR_WindowFrame = COLOR_WINDOWFRAME, COLOR_WindowText = COLOR_WINDOWTEXT }; enum EShowWindowCmd // 窗口显示状态 { SW_ForceMinimize = SW_FORCEMINIMIZE, // Windows NT 5.0 and later: Minimizes a window, even if the thread that owns the window is hung. This flag should only be used when minimizing windows from a different thread. SW_Hide = SW_HIDE, // Hides the window and activates another window. SW_Mazimize = SW_MAXIMIZE, // Maximizes the specified window. SW_Minimize = SW_MINIMIZE, // Minimizes the specified window and activates the next top-level window in the Z order. SW_Restore = SW_RESTORE, // Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window. SW_Show = SW_SHOW, // Activates the window and displays it in its current size and position. SW_ShowDefault = SW_SHOWDEFAULT, // Sets the show state based on the SW_ flag specified in theSTARTUPINFO structure passed to theCreateProcess function by the program that started the application. SW_ShowMaximized = SW_SHOWMAXIMIZED, // Activates the window and displays it as a maximized window. SW_ShowMinimized = SW_SHOWMINIMIZED, // Activates the window and displays it as a minimized window. SW_ShowMinNoactive = SW_SHOWMINNOACTIVE, // Displays the window as a minimized window. The active window remains active. SW_ShowNA = SW_SHOWNA, // Displays the window in its current state. The active window remains active. SW_ShowNoActivate = SW_SHOWNOACTIVATE, // Displays a window in its most recent size and position. The active window remains active. SW_ShowNormal = SW_SHOWNORMAL // Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. }; enum EMsgBoxBtn // 用于消息框的按钮类型 { mb_OK = MB_OK, mb_OkCancel = MB_OKCANCEL, mb_AbortRetryIgnore = MB_ABORTRETRYIGNORE, mb_YesNoCancel = MB_YESNOCANCEL, mb_YesNo = MB_YESNO, mb_RetryCancel = MB_RETRYCANCEL }; enum EMsgBoxIcon // 用于消息框的图标 { mb_IconNone = 0, mb_IconError = MB_ICONHAND, mb_IconQuestion = MB_ICONQUESTION, mb_IconExclamation = MB_ICONEXCLAMATION, mb_IconInformation = MB_ICONASTERISK #if(WINVER >= 0x0400) ,mb_UserIcon = MB_USERICON #endif /* WINVER >= 0x0400 */ }; enum EMsgBeep { mb_SoundOK = MB_OK, // SystemDefault mb_SoundError = MB_ICONHAND, mb_SoundQuestion = MB_ICONQUESTION, mb_SoundExclamation = MB_ICONEXCLAMATION, mb_SoundAsterisk = MB_ICONASTERISK, mb_SoundSpeaker = 0xFFFFFFFF // Standard beep using the computer speaker }; enum EDlgBoxDefBtn // 用于消息框,指定默认按钮 { mb_DefButton1 = MB_DEFBUTTON1, mb_DefButton2 = MB_DEFBUTTON2, mb_DefButton3 = MB_DEFBUTTON3 #if(WINVER >= 0x0400) ,mb_DefButton4 = MB_DEFBUTTON4 #endif /* WINVER >= 0x0400 */ }; enum EDlgBoxCmdID //用于消息框,指定用户按下的按钮 { NoValue = 0, idAbort = IDABORT, // Abort button was selected. idCancel = IDCANCEL, // Cancel button was selected. idIgnore = IDIGNORE, // Ignore button was selected. idNo = IDNO, // No button was selected. idOk = IDOK, // OK button was selected. idRetry = IDRETRY, // Retry button was selected. idYes = IDYES // Yes button was selected. }; enum ESysMenu // 系统菜单枚举类型 { eSysMenu_Close = SC_CLOSE, eSysMenu_Minimize = SC_MINIMIZE, eSysMenu_Maxmize = SC_MAXIMIZE, eSysMenu_Move = SC_MOVE, eSysMenu_Size = SC_SIZE, eSysMenu_Restore = SC_RESTORE }; ////////////////////////////////////////////////////////////////////////// // 常用自定义函数 // ////////////////////////////////////////////////////////////////////////// // 弹出消息框 // 如 title 为 NULL,就自动使用应用程序名作为 title EDlgBoxCmdID MsgBox(LPCTSTR szPrompt, LPCTSTR szTitle = NULL, EMsgBoxBtn buttons = mb_OK, EMsgBoxIcon icon = mb_IconNone, EDlgBoxDefBtn defBtn = mb_DefButton1, bool bSystemModal = false, bool bHelpButton = false, bool bRightJustified = false, bool bRightToLeftReading = false); BOOL MsgBeep(EMsgBeep soundStyle = mb_SoundSpeaker); // 将一个整数转换为八进制的字符串,字符串空间自动管理 LPTSTR Oct(long number); // 将一个整数转换为十六进制的字符串,字符串空间自动管理 LPTSTR Hex(long number); // 获得当前路径字符串,字符串空间自动管理 LPTSTR CurDir(); // 获取一个自定义资源的字节数据(空间由本模块自动开辟、自动管理) // rSize 不为0时,将从此参数指向的空间返回资源的字节数 unsigned char * LoadResData(UINT idRes, UINT typeRes, unsigned long * rSize=0); unsigned char * LoadResData(UINT idRes, LPCTSTR typeRes, unsigned long * rSize=0 ); unsigned char * LoadResData(LPCTSTR idRes, UINT typeRes, unsigned long * rSize=0 ); unsigned char * LoadResData(LPCTSTR idRes, LPCTSTR typeRes, unsigned long * rSize=0); ////////////////////////////////////////////////////////////////////////// // 时间 函数 ////////////////////////////////////////////////////////////////////////// // 返回当前系统日期、时间的一个字符串 // 若 lpDblTime 不为0,还将当前系统日期、时间转换为 double // (为1601-1-1以来经历的毫秒数)存入它指向的 double 型变量中 // 若 lpTime 不为0,还将当前系统日期、时间存储到它指向的结构中 LPTSTR Now( double *lpDblTime=0, SYSTEMTIME *lpTime=0); // 设置当前系统日期、时间 BOOL NowSet( SYSTEMTIME stNow ); // 将一个日期、时间转换为 double 返回(为1601-1-1以来经历的毫秒数) double DateTimeDbl( SYSTEMTIME stDatetime ); // 计算两个日期、时间的时间间隔时所用的间隔类型 enum eDataTimeDiffStyle { edtYearDiff = 1, edtMonthDiff, edtDayDiff, edtHourDiff, edtMinuteDiff, edtSecondDiff, edtMilliseconds }; // 计算两个日期、时间的时间间隔 // style 为指定时间间隔的单位 double DateDiff(eDataTimeDiffStyle style, SYSTEMTIME stDatetime1, SYSTEMTIME stDatetime2); ////////////////////////////////////////////////////////////////////////// // 自定义字符串 函数 ////////////////////////////////////////////////////////////////////////// // 以 printf 方式制作一个字符串(字符串空间由本模块自动开辟、自动管理) LPTSTR cdecl StrPrintf( LPCTSTR szFormat, ... ); // 取字符串的前 length 个字符组成新字符串,返回新字符串的首地址 // 新字符串空间由本模块自动开辟、自动管理 LPTSTR Left(LPCTSTR szStringSrc, int length); // 取字符串的后 length 个字符组成新字符串,返回新字符串的首地址 // 新字符串空间由本模块自动开辟、自动管理 LPTSTR Right(LPCTSTR szStringSrc, int length); // 取字符串的从第 startPos 个字符起,长 length 个字符组成新字符串 // (第一个字符位置为1),返回新字符串的首地址 // 新字符串空间由本模块自动开辟、自动管理 LPTSTR Mid(LPCTSTR szStringSrc, int startPos, int length); // 删除字符串的前导、尾部和所有空格,返回删除后的新字符串, // 新字符串空间由本模块自动开辟、自动管理 // bDelOtherSpace=true时删除所有空格在内的 isspace 返回真的 // 所有字符;bDelOtherSpace=false 时只删除空格 LPTSTR LTrim(LPCTSTR szStringSrc, bool bDelOtherSpace=false); LPTSTR RTrim(LPCTSTR szStringSrc, bool bDelOtherSpace=false); LPTSTR Trim(LPCTSTR szStringSrc, bool bDelOtherSpace=false); // 将字符串中的字母全部转换为大写(UCase)、小写(LCase) // 返回转换后的新字符串(新字符串空间自动管理) LPTSTR LCase(LPCTSTR szStringSrc); LPTSTR UCase(LPCTSTR szStringSrc); enum eBStrCompareMethod // 字符串比较方式 { bcmBinaryCompare = 0, // 二进制比较(区分大小写) bcmTextCompare = 1 // 文本比较(不区分大小写) }; // 在 szSrc 中,从第 start 个字符开始(第一个字符位置为1), // 查找字符串 szFind 的第一次出现的位置(第一个字符位置为1), // 找到返回值>0,没找到返回0 // 说明:本函数未调用任何库函数(strlen也未调用),提高了运行效率 int InStr(int start, LPCTSTR szSrc, LPCTSTR szFind, eBStrCompareMethod compare=bcmBinaryCompare); // 在 szSrc 中,从第一个字符开始,查找字符串 szFind 的 // 第一次出现的位置(第一个字符位置为1), // 返回位置号(第一个字符位置为1)。找到返回值>0,没找到返回0 int InStr(LPCTSTR szSrc, LPCTSTR szFind, eBStrCompareMethod compare=bcmBinaryCompare); // 在 szSrc 中,从第 start 个字符开始(第一个字符位置为1)到末尾的部分, // 查找字符串 szFind 的倒数第一次出现的位置(第一个字符位置为1), // 找到返回值>0,没找到返回0 // 说明:本函数未调用任何库函数(strlen也未调用),提高了运行效率 int InStrRev(LPCTSTR szSrc, LPCTSTR szFind, int start=1, eBStrCompareMethod compare=bcmTextCompare); // 按分隔字符串 delimiters ,分割一个字符串,生成若干子字符串 // 各 子字符串 的地址由 ptrStrings[] 数组返回,函数返回子字符串的个数 // ptrStrings[] 数组下标从1开始,最大到函数返回值 // limit 限制返回子字符串的最大个数,为 -1 时不限制,将返回所有字符串 // 子字符串内存及 ptrStrings[] 数组内存都由本模块自动分配、自动管理 int Split(LPCTSTR stringSrc, TCHAR ** &ptrStrings, LPCTSTR delimiters=0, int limit=-1, eBStrCompareMethod compare=bcmBinaryCompare); // 以 delimiter 连接多个字符串,返回连接好的字符串 // 多个字符串的地址由数组 stringSrcArray[] 给出,将连接 // 数组中从下标 arrayIndexStart 到 arrayIndexEnd 的字符串 // delimiter 为 0 时,默认以 "\0" 连接字符串;否则以字符串 delimiter 连接 // bTailDoubleNull 若为 true,则在结果字符串的最后再加一个'\0'(即最后有两个'\0') // 结果字符串的内存由本模块自动分配、自动管理 LPTSTR Join(TCHAR * stringSrcArray[], const int arrayIndexEnd, LPCTSTR delimiter=0, const int arrayIndexStart=1, const bool bTailDoubleNull=false); // 替换字符串 LPTSTR Replace(LPCTSTR szStringSrc, // 要被替换的字符串 LPCTSTR szFind, // 要被替换掉的子字符串 LPCTSTR szReplaceWith, // 要替换为的内容 int start=1, // 在 szStringSrc 中子字符串搜索的开始位置 int countLimit=-1, // 子字符串进行替换的次数。–1 表明进行所有可能的替换 eBStrCompareMethod compare=bcmBinaryCompare // 判别子字符串时所用的比较方式 ); // 连接字符串,生成连接后的长字符串 // 返回连接好的字符串的首地址,自动维护动态空间 // 每次调用可最多连接9个字符串 LPTSTR StrAppend(LPCTSTR str1=0, LPCTSTR str2=0, LPCTSTR str3=0, LPCTSTR str4=0, LPCTSTR str5=0, LPCTSTR str6=0, LPCTSTR str7=0, LPCTSTR str8=0, LPCTSTR str9=0 ); // 将 ANSI 或 UTF8 字符串转换为 Unicode,返回结果字符串首地址 // 参数 bToUTF8orANSI 为 false 时转换 ANSI,为 true 时转换 UTF8 // 结果字符串的内存由本模块自动分配、自动管理 LPWSTR StrConvUnicode(const char * szAnsi, bool bFromUTF8orANSI=false ); // LPWSTR 就是 unsigned short int * // 将 Unicode 字符串转换为 ANSI 或 UTF8,返回结果字符串首地址 // 参数 bToUTF8orANSI 为 false 时转换为 ANSI,为 true 时转换为 UTF8 // 结果字符串的内存由本模块自动分配、自动管理 char * StrConvFromUnicode(LPCWSTR szUnicode, bool bToUTF8orANSI=false ); // 将字符串转换为 double 型数值 double Val( LPCWSTR stringVal ); // Unicode 字符串 double Val( LPCSTR stringVal ); // ANSI 字符串 // 将各种类型数据转换为字符串 // 返回字符串首地址,字符串空间由本函数自动开辟和管理 LPTSTR Str(char number); LPTSTR Str(unsigned short int number); // TCHAR LPTSTR Str(int number); LPTSTR Str(unsigned int number); LPTSTR Str(unsigned long number); LPTSTR Str(float number); LPTSTR Str(double number); LPTSTR Str(long double number); ////////////////////////////////////////////////////////////////////////// // 自定义 动态数组 函数 ////////////////////////////////////////////////////////////////////////// // 重定义 一个 REDIMTYPE 类型(如int型、int *型即指针数组)的数组的大小,新定义空间自动清零 // arr:为数组指针(可为 int *型变量,或void **型变量,后者为数组指针),本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound template <typename REDIMTYPE> int Redim( REDIMTYPE * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false ) // template 函数定义要在头文件中 { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { REDIMTYPE * ptrNew = new REDIMTYPE[toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(REDIMTYPE)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 REDIMTYPE 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(REDIMTYPE)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0) { // 不开辟空间,删除原有空间 if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } // 删除动态数组的空间,并设置指针 arr 为 0 template <typename REDIMTYPE> void Erase( REDIMTYPE * &arr) { if(arr!=0) delete [] arr; arr=0; } ////////////////////////////////////////////////////////////////////// // CBApp 类: 管理应用程序全局信息 // ////////////////////////////////////////////////////////////////////// class CBApp // 应用程序全局信息对象 { public: // 构造函数 CBApp(HINSTANCE hInst, HINSTANCE hPrevInst, char * lpCmdLine, int nShowCmd); // 常成员(只能获得值,不能修改;是在构造函数的初始化表中修改的) const HINSTANCE hInstance; // WinMain 函数传递过来的 hInstance const int CmdShow; // WinMain 函数传递过来的 nShowCmd // 获得应用程序当前运行的路径(最后含 \) LPTSTR Path(); // 获得命令行参数字符串(包含exe文件名路径,字符串空间由 Windows 维护) LPTSTR Command() const; // 获得屏幕宽度、高度 int ScreenWidth() const; int ScreenHeight() const; private: TCHAR m_path[2048]; // 应用程序当前运行的路径字符串缓冲区 }; // 全局对象变量 pApp(是指针)的声明,所指向的对象用于获得本程序的全局程序信息, // 如 hInstance 等。真正的变量定义在 BWindows.cpp 中,这里用 // extern 声明此变量,则所有包含本 h 文件的模块都可使用此全局变量 extern CBApp *pApp; // =============================================================== // CBHashLK:长整数型 key 的哈希表类 // 支持每个元素中有一个 long 型的数据和一个 long 型的附加数据 // // 可能抛出的异常: // throw (unsigned char)7; // 超出内存 // throw (unsigned char)5; // 无效的过程调用或参数:键值错误,如试图添加已存在的同样键值的新元素,访问键不存在的元素 // throw (unsigned char)9; // 下标越界:无法分配新数据空间 // // ---- 可以使用 Index 的方式遍历所有哈希表元素 ---- // for (i = 1; i<=hash.Count; i++) // cout<<hash.KeyFromIdx(i) // // for (i = 1; i<=hash.Count; i++) // cout<<hash.ItemFromIdx(i) // // 注意 Index 并不与数据对应,随着增删和重排,数据的 Index 都可能会变化 // 但在同一时刻,Index 相同的一套数据(Key,Data,DataLong,DataString)是同一套 // =============================================================== class CBHashLK { private: typedef long KeyType; // key 的类型 typedef long DataType; // 数据的类型 typedef long DataLongType; // 附加数据的类型 typedef long DataLong2Type; // 附加数据的类型 typedef struct _MemType { KeyType Key; DataType Data; DataLongType DataLong; DataLong2Type DataLong2; double DataDouble; LPTSTR DataStr; LPTSTR DataStr2; bool Used; int Index; // mArrTable[] 数组的 mArrTable[index] 元素,是保存本 MemType 数据 // 所在的 mem[] 中的下标(index>0)或在 mem2[] 中的下标(index<0) // mArrTableCount == memUsedCount + memUsedCount2 时且 index !=0 时 有效 // 在 RefreshArrTable 中设置此成员 } MemType; static const int mcIniMemSize; // 初始 mem[] 的大小 static const int mcMaxItemCount; // 最多元素个数(可扩大此值到 long 表示的范围之内) static const float mcExpandMaxPort; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 static const int mcExpandCountThres; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 static const int mcExpandCountThresMax; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandBigPer; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandMem2Per; // 每次扩大 mem2[] 的大小 static const int mcSeqMax; // 顺序检索最大值 private: MemType * mem; // 动态数组指针,但数组不使用 [0] 的元素 int memCount, memUsedCount; // 动态数组最大下标,mem[] 数组下标为 [0] ~ [memCount]。哈希表已用元素个数 MemType * mem2; // 空间冲突的元素的保存空间,顺序使用 int memCount2, memUsedCount2; // mem2[] 数组下标为 [0] ~ [memCount2],其中 [0] 不用,已使用空间为 [1] ~ [memUsedCount2] int mTravIdxCurr; // 用 NextXXX 方法遍历的当前 index,正值表示 mem[] 中的下标,负值表示 mem2[] 中的下标 // 支持通过给定下标 Index 访问一个哈希表数据,mArrTable 指向动态数组, // 数组元素保存:所有哈希表数据依遍历顺序所在的 mem[] 中的下标(>0) // 或 mem2[] 中的下标。 // 遍历一次,将所有哈希表数据 mem[] 或 mem2[] 的下标存于此数组, // 以后不需重复遍历,直接通过给定下标 Index 访问一个哈希表数据。 // mArrTableCount != memUsedCount + memUsedCount2 为标志, // 如 !=,标志要重新刷新遍历。注意重新遍历后,元素顺序可能会重排。 // 各哈希表数据的 Index 并不是一直不变的 int * mArrTable; int mArrTableCount; public: CBHashLK(int memSize=0); // memSize=0 则开辟初始 mcIniMemSize 个空间,否则开辟 memSize 个空间,memSize 应比实际数据个数大一些 ~CBHashLK(); void AlloMem(int memSize); // 事先可用此函数定义足够大的空间,以减少以后自动扩大空间的次数,提高效率 bool Add(DataType data, KeyType key=0, DataLongType dataLong=0, DataLong2Type dataLong2=0, LPCTSTR dataStr=0, LPCTSTR dataStr2=0, double dataDouble=0.0, bool raiseErrorIfNotHas=true); // 添加元素 bool Remove(KeyType key, bool raiseErrorIfNotHas=true); // 删除元素 // 根据 key 获得元素、附加数据 DataType Item(KeyType key, bool raiseErrorIfNotHas=true); DataLongType ItemLong(KeyType key, bool raiseErrorIfNotHas=true); DataLong2Type ItemLong2(KeyType key, bool raiseErrorIfNotHas=true); double ItemDouble(KeyType key, bool raiseErrorIfNotHas=true); LPTSTR ItemStr(KeyType key, bool raiseErrorIfNotHas=true); LPTSTR ItemStr2(KeyType key, bool raiseErrorIfNotHas=true); // 根据 key 设置元素、附加数据 bool ItemSet(KeyType key, DataType vNewValue, bool raiseErrorIfNotHas=true); bool ItemLongSet(KeyType key, DataLongType vNewValue, bool raiseErrorIfNotHas=true); bool ItemLong2Set(KeyType key, DataLong2Type vNewValue, bool raiseErrorIfNotHas=true); bool ItemDoubleSet(KeyType key, double vNewValue, bool raiseErrorIfNotHas=true); bool ItemStrSet(KeyType key, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); bool ItemStr2Set(KeyType key, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); // 根据 index 获得元素、附加数据 DataType ItemFromIndex(int index, bool raiseErrorIfNotHas=true); DataLongType ItemLongFromIndex(int index, bool raiseErrorIfNotHas=true); DataLong2Type ItemLong2FromIndex(int index, bool raiseErrorIfNotHas=true); double ItemDoubleFromIndex(int index, bool raiseErrorIfNotHas=true); LPTSTR ItemStrFromIndex(int index, bool raiseErrorIfNotHas=true); LPTSTR ItemStr2FromIndex(int index, bool raiseErrorIfNotHas=true); // 根据 index 设置元素、附加数据(但不能设置 Key,Key为只读) bool ItemFromIndexSet(int index, DataType vNewValue, bool raiseErrorIfNotHas=true); bool ItemLongFromIndexSet(int index, DataLongType vNewValue, bool raiseErrorIfNotHas=true); bool ItemLong2FromIndexSet(int index, DataLong2Type vNewValue, bool raiseErrorIfNotHas=true); bool ItemDoubleFromIndexSet(int index, double vNewValue, bool raiseErrorIfNotHas=true); bool ItemStrFromIndexSet(int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); bool ItemStr2FromIndexSet(int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); KeyType IndexToKey(int index, bool raiseErrorIfNotHas=true); int KeyToIndex(KeyType key, bool raiseErrorIfNotHas=true); bool IsKeyExist(KeyType key); // 判断某个 key 的元素是否存在 void Clear(void); // 清除所有元素,重定义 mcIniMemSize 个存储空间 void StartTraversal(); // 开始一个遍历过程 DataType NextItem(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素,直到 bRetNotValid 返回 true DataLongType NextItemLong(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素的附加数据,直到 bRetNotValid 返回 true DataLong2Type NextItemLong2(bool &bRetNotValid); double NextItemDouble(bool &bRetNotValid); LPTSTR NextItemStr(bool &bRetNotValid); LPTSTR NextItemStr2(bool &bRetNotValid); KeyType NextKey(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素的 key,直到 bRetNotValid 返回 true int Count(void); // 返回共有元素个数 private: int AlloMemIndex(KeyType key, bool CanExpandMem=true ); // 根据 Key 分配一个 mem[] 中的未用存储空间,返回 mem[] 数组下标 int FindMemIndex(KeyType key) const; // 根据 Key 查找 mem[] 中元素,返回 mem[] 数组下标 int FindSeqIdx(KeyType key, int fromIndex, int toIndex); // 找 mem[] 中键为 key 的元素下标,仅查找空间下标为从 fromIndex 开始、到 toIndex 结束的空间 void ReLocaMem(int preMemCountTo); // 重新分配 mem[], mem2[] 的各元素的地址,mem2[] 的某些元素可能被重新移动到 mem[] void ExpandMem(void); // 重定义 mem[] 数组大小,扩大 mem[] 的空间 int TraversalGetNextIdx(void); // 用 NextXXX 方法遍历时,返回下一个(Next)的 mem[]下标(返回值>0),或 mem2[] 的下标(返回值<0),或已遍历结束(返回值=0) int AlloSeqIdx(int fromIndex, int toIndex); // 找 mem[] 中一个没使用的空间,仅查找空间下标为从 fromIndex 开始、到 toIndex 结束的空间 bool RefreshArrTable(); // 遍历哈希表,将数据下标存入 mArrTable[],设置 mArrTableCount 为数据个数(返回成功或失败) int RedimArrMemType(MemType * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false); // 重定义 一个 MemType 类型的数组(如可以是 lMem[] 或 lMem2[])的大小,新定义空间自动清零 int GetMemIndexFromKey(KeyType key, bool raiseErrorIfNotHas=true); // 从 Key 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 int GetMemIndexFromIndex(int index, bool raiseErrorIfNotHas=true); // 从 index 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 void SaveItemString(TCHAR ** ptrSaveTo, LPCTSTR ptrNewString); // 用 new 开辟新字符串空间,把 key 指向的字符串拷贝到新空间;ptrSaveTo 是一个保存字符串地址的指针变量的地址,其指向的指针变量将保存“用 new 开辟的新字符串空间的地址”,即让 “*ptrSaveTo = 新空间地址” }; // =============================================================== // CBHashStrK:字符串型 key 的哈希表类 // 支持每个元素中有一个 long 型的数据和一个 long 型的附加数据 // // 可能抛出的异常: // throw (unsigned char)7; // 超出内存 // throw (unsigned char)5; // 无效的过程调用或参数:键值错误,如试图添加已存在的同样键值的新元素,访问键不存在的元素 // throw (unsigned char)9; // 下标越界:无法分配新数据空间 // // ---- 可以使用 Index 的方式遍历所有哈希表元素 ---- // for (i = 1; i<=hash.Count; i++) // cout<<hash.KeyFromIdx(i) // // for (i = 1; i<=hash.Count; i++) // cout<<hash.ItemFromIdx(i) // // 注意 Index 并不与数据对应,随着增删和重排,数据的 Index 都可能会变化 // 但在同一时刻,Index 相同的一套数据(Key,Data,DataLong,DataString)是同一套 // =============================================================== class CBHashStrK { private: typedef struct _MemType { LPTSTR Key; // 指向本类管理的用 new 开辟的一块内存区,每个 mem[] 在被删除时,先 delete [] .key int Data; long DataLong; long DataLong2; double DataDouble; LPTSTR DataStr; LPTSTR DataStr2; bool Used; int Index; // mArrTable[] 数组的 mArrTable[index] 元素,是保存本 MemType 数据 // 所在的 mem[] 中的下标(index>0)或在 mem2[] 中的下标(index<0) // mArrTableCount == memUsedCount + memUsedCount2 时且 index !=0 时 有效 // 在 RefreshArrTable 中设置此成员 } MemType; static const int mcIniMemSize; // 初始 mem[] 的大小 static const int mcMaxItemCount; // 最多元素个数(可扩大此值到 long 表示的范围之内) static const float mcExpandMaxPort; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 static const int mcExpandCountThres; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 static const int mcExpandCountThresMax; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandBigPer; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandMem2Per; // 每次扩大 mem2[] 的大小 static const int mcSeqMax; // 顺序检索最大值 private: MemType * mem; // 动态数组指针,但数组不使用 [0] 的元素 int memCount, memUsedCount; // 动态数组最大下标,mem[] 数组下标为 [0] ~ [memCount]。哈希表已用元素个数 MemType * mem2; // 空间冲突的元素的保存空间,顺序使用 int memCount2, memUsedCount2; // mem2[] 数组下标为 [0] ~ [memCount2],其中 [0] 不用,已使用空间为 [1] ~ [memUsedCount2] int mTravIdxCurr; // 用 NextXXX 方法遍历的当前 index,正值表示 mem[] 中的下标,负值表示 mem2[] 中的下标 // 支持通过给定下标 Index 访问一个哈希表数据,mArrTable 指向动态数组, // 数组元素保存:所有哈希表数据依遍历顺序所在的 mem[] 中的下标(>0) // 或 mem2[] 中的下标。 // 遍历一次,将所有哈希表数据 mem[] 或 mem2[] 的下标存于此数组, // 以后不需重复遍历,直接通过给定下标 Index 访问一个哈希表数据。 // mArrTableCount != memUsedCount + memUsedCount2 为标志, // 如 !=,标志要重新刷新遍历。注意重新遍历后,元素顺序可能会重排。 // 各哈希表数据的 Index 并不是一直不变的 int * mArrTable; int mArrTableCount; public: bool KeyCaseSensitive; // 是否 key 要区分大小写(默认不分大小写) public: CBHashStrK(int memSize=0); // memSize=0 则开辟初始 mcIniMemSize 个空间,否则开辟 memSize 个空间,memSize 应比实际数据个数大一些 ~CBHashStrK(); void AlloMem(int memSize); // 事先可用此函数定义足够大的空间,以减少以后自动扩大空间的次数,提高效率 bool Add(int data, LPCTSTR key=0, long dataLong=0, long dataLong2=0, LPCTSTR dataStr=NULL, LPCTSTR dataStr2=NULL, double dataDouble=0.0, bool raiseErrorIfNotHas=true); // 添加元素 bool Remove(LPCTSTR key, bool raiseErrorIfNotHas=true); // 删除元素 // 根据 key 获得元素、附加数据 int Item(LPCTSTR key, bool raiseErrorIfNotHas=true); long ItemLong(LPCTSTR key, bool raiseErrorIfNotHas=true); long ItemLong2(LPCTSTR key, bool raiseErrorIfNotHas=true); double ItemDouble(LPCTSTR key, bool raiseErrorIfNotHas=true); LPTSTR ItemStr(LPCTSTR key, bool raiseErrorIfNotHas=true); LPTSTR ItemStr2(LPCTSTR key, bool raiseErrorIfNotHas=true); // 根据 key 设置元素、附加数据 bool ItemSet(LPCTSTR key, int vNewValue, bool raiseErrorIfNotHas=true); bool ItemLongSet(LPCTSTR key, long vNewValue, bool raiseErrorIfNotHas=true); bool ItemLong2Set(LPCTSTR key, long vNewValue, bool raiseErrorIfNotHas=true); bool ItemDoubleSet(LPCTSTR key, double vNewValue, bool raiseErrorIfNotHas=true); bool ItemStrSet(LPCTSTR key, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); bool ItemStr2Set(LPCTSTR key, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); // 根据 index 获得元素、附加数据 int ItemFromIndex(int index, bool raiseErrorIfNotHas=true); long ItemLongFromIndex(int index, bool raiseErrorIfNotHas=true); long ItemLong2FromIndex(int index, bool raiseErrorIfNotHas=true); double ItemDoubleFromIndex(int index, bool raiseErrorIfNotHas=true); LPTSTR ItemStrFromIndex(int index, bool raiseErrorIfNotHas=true); LPTSTR ItemStr2FromIndex(int index, bool raiseErrorIfNotHas=true); // 根据 index 设置元素、附加数据(但不能设置 Key,Key为只读) bool ItemFromIndexSet(int index, int vNewValue, bool raiseErrorIfNotHas=true); bool ItemLongFromIndexSet(int index, long vNewValue, bool raiseErrorIfNotHas=true); bool ItemLong2FromIndexSet(int index, long vNewValue, bool raiseErrorIfNotHas=true); bool ItemDoubleFromIndexSet(int index, double vNewValue, bool raiseErrorIfNotHas=true); bool ItemStrFromIndexSet(int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); bool ItemStr2FromIndexSet(int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas=true); LPTSTR IndexToKey(int index, bool raiseErrorIfNotHas=true); int KeyToIndex(LPCTSTR key, bool raiseErrorIfNotHas=true); bool IsKeyExist(LPCTSTR key); // 判断某个 key 的元素是否存在 void Clear(void); // 清除所有元素,重定义 mcIniMemSize 个存储空间 void StartTraversal(); // 开始一个遍历过程 int NextItem(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素,直到 bRetNotValid 返回 true long NextItemLong(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素的附加数据,直到 bRetNotValid 返回 true long NextItemLong2(bool &bRetNotValid); double NextItemDouble(bool &bRetNotValid); LPTSTR NextItemStr(bool &bRetNotValid); LPTSTR NextItemStr2(bool &bRetNotValid); LPTSTR NextKey(bool &bRetNotValid); // 遍历过程开始后,不断调用此函数,获得每个元素的 key,直到 bRetNotValid 返回 true int Count(void); // 返回共有元素个数 private: int AlloMemIndex(LPCTSTR Key, bool CanExpandMem=true ); // 根据 Key 分配一个 mem[] 中的未用存储空间,返回 mem[] 数组下标 int FindSeqIdx(LPCTSTR key, int fromIndex, int toIndex); // 找 mem[] 中键为 key 的元素下标,仅查找空间下标为从 fromIndex 开始、到 toIndex 结束的空间 void ReLocaMem(int preMemCountTo); // 重新分配 mem[], mem2[] 的各元素的地址,mem2[] 的某些元素可能被重新移动到 mem[] void ExpandMem(void); // 重定义 mem[] 数组大小,扩大 mem[] 的空间 int TraversalGetNextIdx(void); // 用 NextXXX 方法遍历时,返回下一个(Next)的 mem[]下标(返回值>0),或 mem2[] 的下标(返回值<0),或已遍历结束(返回值=0) int AlloSeqIdx(int fromIndex, int toIndex); // 找 mem[] 中一个没使用的空间,仅查找空间下标为从 fromIndex 开始、到 toIndex 结束的空间 bool RefreshArrTable(); // 遍历哈希表,将数据下标存入 mArrTable[],设置 mArrTableCount 为数据个数(返回成功或失败) int RedimArrMemType(MemType * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false); // 重定义 一个 MemType 类型的数组(如可以是 lMem[] 或 lMem2[])的大小,新定义空间自动清零 int GetMemIndexFromKey(LPCTSTR key, bool raiseErrorIfNotHas=true); // 从 Key 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 int GetMemIndexFromIndex(int index, bool raiseErrorIfNotHas=true); // 从 index 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 long KeyStringToLong(LPCTSTR key); // 将一个 字符串类型的 key 转换为一个长整数 void SaveItemString(TCHAR ** ptrSaveTo, LPCTSTR ptrNewString); // 用 new 开辟新字符串空间,把 key 指向的字符串拷贝到新空间;ptrSaveTo 是一个保存字符串地址的指针变量的地址,其指向的指针变量将保存“用 new 开辟的新字符串空间的地址”,即让 “*ptrSaveTo = 新空间地址” bool CompareKey(LPCTSTR key1, LPCTSTR key2); // 根据 KeyCaseSensitive 属性,比较两 key 的字符串是否相等:相等返回True,不等返回False }; ////////////////////////////////////////////////////////////////////// // CBRecycledArr:带回收站的数组类 // // 可组织一批数据,数据类型可同时为: // 一个字符串、两个整数、一个单精度数、一个双精度数 // 可随意 Add、Remove,自动维护 index 为 1~Count 范围,以便通过数组 // 的方式访问各元素;也支持通过遍历的方法访问各元素 ////////////////////////////////////////////////////////////////////// // 可能 throw 的错误: // throw (unsigned char)5; // 无效的过程调用或参数 class CBRecycledArr { private: typedef struct _MemType { LPTSTR DataString; // 字符串数据 int DataInt; // 附加整型数据1 int DataInt2; // 附加整型数据2 float DataFloat; // 附加单精度数据 double DataDouble; // 附加双精度数据 bool Used; } MemType; static const int mcIniMemSize; // 初始 mem[] 的大小 static const int mcMaxItemCount; // 最多元素个数(可扩大此值到 long 表示的范围之内) static const float mcExpandMaxPort; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 static const int mcExpandCountThres; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 static const int mcExpandCountThresMax; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandBigPer; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcRecyExpandPer; // 扩大 recycles[] 空间时,每次扩大的大小 private: MemType * mem; // 动态数组指针,但数组不使用 [0] 的元素 int memCount, memUsedCount; // 动态数组最大下标,mem[] 数组下标为 [0] ~ [memCount]。已用[0] ~ [memUsedCount](其中可能有删除的元素,删除的元素下标在 recycles 中保存) int * recycles; // 指向一个整型数组,数组各元素保存 mem[] 中已删除的元素的下标;该数组被维护从小到大排序 // recycles[] 数组下标为 [0] ~ [recyclesCount],其中 [0] 不用;用 [1] - [recyUsedCount],其余为可用空余空间 int recyCount, recyUsedCount; // recycles[] 数组元素下标最大值 int mTravIdxCurr; // 用 NextXXX 方法遍历的当前 index public: CBRecycledArr(int initSize = 0); // initSize = 0 时,初始开辟 mcIniMemSize 大小的空间,否则开辟 initSize 大小的空间 ~CBRecycledArr(); int Add(LPCTSTR dataString = 0, int dataInt = 0, int dataInt2 = 0, float dataFloat = 0.0, double dataDouble = 0.0); // 添加新数据,返回新数据被保存到的 mem[] 中的下标(>0),出错返回0 bool Remove(int index); // 删除一个数据,index 为要删除数据的下标;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count LPTSTR Item(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个字符串数据;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count;字符串的内存空间由本类自动管理,主调程序不必干预;如主调程序修改了返回指针的指向内容,则本类对象内部内容也同时发生变化 int ItemInt(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个整型附加数据;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count int ItemInt2(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个整型附加数据2;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count float ItemFloat(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个 float 型附加数据;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count double ItemDouble(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个 double 型附加数据;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count int Count(); // 返回当前拥有的数据个数 void Clear(); // 删除所有数据 void StartTraversal(); // 开始一次遍历 LPTSTR NextItem( bool &bRetNotValid ); // 遍历的下一个数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int NextDataInt( bool &bRetNotValid ); // 遍历的下一个附加整型数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int NextDataInt2( bool &bRetNotValid ); // 遍历的下一个附加整型数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) float NextDataFloat( bool &bRetNotValid ); // 遍历的下一个附加 float 型数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) double NextDataDouble( bool &bRetNotValid ); // 遍历的下一个附加整 double 数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) private: void ExpandMem(void); int RedimArrMemType(MemType * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false); // 重定义 一个 MemType 类型的数组(如可以是 mem[])的大小,新定义空间自动清零 int RedimArrInt( int * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false ); // 重定义 一个 int 类型的数组(如可以是 recycles)的大小,新定义空间自动清零 int FindPosInSortedRecycle(int itemToFind); // 用二分查找法在数组 recycles 中查找元素 itemToFind 的位置 int UserIndexToMemIndex(int index); // 根据用户 index,获得在 mem[] 中的下标;删除数据后,后续数据的用户 index 会自动调整;使用户 index 总为 1~Count }; ////////////////////////////////////////////////////////////////////// // CBRecycledArrInt:整型版带回收站的数组类 // // 可组织一批数据,数据类型可同时为: // 两个整数、一个单精度数、一个双精度数 // 可随意 Add、Remove,自动维护 index 为 1~Count 范围,以便通过数组 // 的方式访问各元素;也支持通过遍历的方法访问各元素 ////////////////////////////////////////////////////////////////////// // 可能 throw 的错误: // throw (unsigned char)5; // 无效的过程调用或参数 class CBRecycledArrInt { private: typedef int DataType; // 数据的类型 typedef int DataIntType; // 附加整型数据的类型 typedef float DataFloatType; // 附加单精度数据的类型 typedef double DataDoubleType; // 附加双精度数据的类型 typedef struct _MemType { DataType Data; DataIntType DataInt; DataFloatType DataFloat; DataDoubleType DataDouble; bool Used; } MemType; static const int mcIniMemSize; // 初始 mem[] 的大小 static const int mcMaxItemCount; // 最多元素个数(可扩大此值到 long 表示的范围之内) static const float mcExpandMaxPort; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 static const int mcExpandCountThres; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 static const int mcExpandCountThresMax; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcExpandBigPer; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer static const int mcRecyExpandPer; // 扩大 recycles[] 空间时,每次扩大的大小 private: MemType * mem; // 动态数组指针,但数组不使用 [0] 的元素 int memCount, memUsedCount; // 动态数组最大下标,mem[] 数组下标为 [0] ~ [memCount]。已用[0] ~ [memUsedCount](其中可能有删除的元素,删除的元素下标在 recycles 中保存) int * recycles; // 指向一个整型数组,数组各元素保存 mem[] 中已删除的元素的下标 // recycles[] 数组下标为 [0] ~ [recyclesCount],其中 [0] 不用;用 [1] - [recyUsedCount],其余为可用空余空间 int recyCount, recyUsedCount; // recycles[] 数组元素下标最大值 int mTravIdxCurr; // 用 NextXXX 方法遍历的当前 index public: CBRecycledArrInt(int initSize = 0); // initSize = 0 时,初始开辟 mcIniMemSize 大小的空间,否则开辟 initSize 大小的空间 ~CBRecycledArrInt(); int Add(DataType data, DataIntType dataInt = 0, DataFloatType dataFloat = 0.0, DataDoubleType dataDouble = 0.0); // 添加新数据,返回新数据被保存到的 mem[] 中的下标(>0),出错返回0 bool Remove(int index); // 删除一个数据,index 为要删除数据的下标。 DataType Item(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个数据 DataIntType ItemInt(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个整型附加数据 DataFloatType ItemFloat(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个 float 型附加数据 DataDoubleType ItemDouble(int index, bool bRaiseErrIfNotHas=false); // 根据下标 index,返回一个 double 型附加数据 int Count(); // 返回当前拥有的数据个数 void Clear(); // 删除所有数据 void StartTraversal(); // 开始一次遍历 DataType NextItem( bool &bRetNotValid ); // 遍历的下一个数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) DataIntType NextDataInt( bool &bRetNotValid ); // 遍历的下一个附加整型数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) DataFloatType NextDataFloat( bool &bRetNotValid ); // 遍历的下一个附加 float 型数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) DataDoubleType NextDataDouble( bool &bRetNotValid ); // 遍历的下一个附加整 double 数据,若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) private: void ExpandMem(void); int RedimArrMemType(MemType * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false); // 重定义 一个 MemType 类型的数组(如可以是 mem[])的大小,新定义空间自动清零 int RedimArrInt( int * &arr, int toUBound=-1, int uboundCurrent=-1, bool preserve=false ); // 重定义 一个 int 类型的数组(如可以是 recycles)的大小,新定义空间自动清零 }; ////////////////////////////////////////////////////////////////////// // CHeapMemory: 用全局对象维护所有通过 new 分配的内存指针,在本类对象 // 析构时会自动 delete 此这些内存 // ////////////////////////////////////////////////////////////////////// class CBHeapMemory { public: CBHeapMemory(int initSize=0); virtual ~CBHeapMemory(); // 添加一个要由本对象管理的、已用new分配的空间的地址, // 成功返回本对象所管理的地址个数(含新增的这一个) // 若 bArrayNew=true,将在 delete 时有[];否则 delete 时没有[] int AddPtr(void *ptrNew, bool bArrayNew=true); // 用 new 分配 size 个字节的空间,并自动清0 // 返回此空间的地址(出错返回0),并由本对象自动记录此空间的地址 void * Alloc(int size); // 释放 ptr 所指向的一段内存空间 // ptr 必须是由本对象所管理的空间,否则本函数不会释放 void Free(void *ptr); // 返回 ptr 所指向的一段内存空间是否正由本对象管理 bool IsPtrManaged(void *ptr); // 返回 本对象正管理的空间个数 int CountPtrs(); // 返回 本对象正管理的一个空间的地址 // index 应为 1~CountPtrs() 之间 // 由参数 ptrbArrayNew 返回该空间 delete 时是否应有[] void * PtrEach(int index, bool * ptrbArrayNew=0); // 清零一块内存空间。实际是调用 memset (本类已 include <memory.h>) , // 为使主调程序不必再 include memory.h,本类也提供了这个功能接口 void ZeroMem(void * ptr, unsigned int length); // 内存拷贝。实际是调用 memcpy (本类已 include <memory.h>) , // 为使主调程序不必再 include memory.h,本类也提供了这个功能接口) void CopyMem(void * dest, void * source, unsigned int length); // 强制释放本对象所记录的所有地址指向的空间 // 本对象析构时也会自动调用本函数 void Dispose(); private: // 保存由本对象管理的、所有用 new 动态分配的空间地址 // key=地址;data=地址; // dataLong!=0 时,delete 时会有[];dataLong=0,delete 时无[] CBHashLK memHash; }; // 全局对象变量 HM 的声明,管理程序中所有以 new 开辟的内存指针,该对象 // 析构时可自动 delete 这些内存。真正的变量定义在 BWindows.cpp 中,这里 // 用 extern 声明此变量,则所有包含本 h 文件的模块都可使用此全局变量 extern CBHeapMemory HM;
#include "../Display.hpp" using namespace Drivers; uint8_t Display::buffor[Display::Width*Display::Hight/8] = { 0 }; void Display::sendByte(uint8_t type, uint8_t data) { Port::setFalse( bitValue(PinCE) ); if(type == SendType::Data) Port::setTrue( bitValue(PinDC) ); if(type == SendType::Command) Port::setFalse( bitValue(PinDC) ); SPDR = data; while(!(SPSR & (1<<SPIF))); // wait for data send Port::setTrue( bitValue(PinCE) ); } void Display::init(void) { Port::setFalse( bitValue(PinRST) ); Ddr::setTrue( bitValue(PinRST) | bitValue(PinCLK) | bitValue(PinDIN) | bitValue(PinDC) | bitValue(PinCE) ); SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); // spi configuration _delay_ms(15); // time for display to receive RST(true) and else Port::setTrue( bitValue(PinRST) | bitValue(PinCE) ); sendByte(SendType::Command, 0x21); // Function set - extended instruction set sendByte(SendType::Command, 0x13); // Bias - 1:48 sendByte(SendType::Command, 0x06); // Temperature Control sendByte(SendType::Command, 0xa5); // Set Vop sendByte(SendType::Command, 0x20); // Function set - basic instruction set, horizontal addressing sendByte(SendType::Command, 0x0C); // Display control - normal mode } void Display::display(void) { sendByte(SendType::Command, 0x40); sendByte(SendType::Command, 0x80); for (uint16_t i = 0 ; i < (Width * Hight / 8) ; i++) sendByte(SendType::Data, buffor[i]); } void Display::clear(bool color) { for (uint16_t i = 0 ; i < (Width * Hight / 8) ; i++) buffor[i] = color ? 0xFF : 0x00; } bool Display::getPoint(uint8_t x, uint8_t y) { return ((buffor[(y/8)*84+x] >> y%8) & 0b000000001) == 0b00000001; } void Display::drawPoint(uint8_t x, uint8_t y, bool color) { if(color) buffor[(y/8)*84+x] |= 1 << y%8; else buffor[(y/8)*84+x] &= ~(1 << y%8); } void Display::drawRectangle(uint8_t x, uint8_t y,uint8_t w,uint8_t h, bool color) { for(uint8_t lx = x; lx != x+w; lx++) { for(uint8_t ly = y; ly != y+h; ly++) { drawPoint(lx,ly,color); } } } void Display::drawBitmap(uint8_t x, uint8_t y,uint8_t w,uint8_t h, const uint8_t image[], bool invert) { for(uint8_t ly = 0; ly < h; ly++) { for(uint8_t lx = 0; lx < w; lx++) { uint8_t img = pgm_read_byte(&image[(ly/8)*w+lx]); if(invert) img = ~img; drawPoint(lx+x,ly+y, (img >> (ly%8)) & 0b000000001 ); } } } const uint8_t Display::DefaultFont[] PROGMEM = { #include "../../Assets/Font(char6x8).bitmap" }; const uint8_t Display::LeftArrow[] PROGMEM = { #include "../../Assets/IconLeftArrow(6x8).bitmap" }; const uint8_t Display::RightArrow[] PROGMEM = { #include "../../Assets/IconRightArrow(6x8).bitmap" }; void Display::drawText(uint8_t x, uint8_t y,char* str, bool invert,const uint8_t font[],uint8_t letterX,uint8_t letterY) { for(uint8_t i = 0; str[i] != '\0';i++) { uint8_t offset = str[i] - '0'; if(str[i] >= 'A') offset = str[i] - 'A' + 11; if(str[i] == 32) offset = 37; for(uint8_t ly = 0; ly < letterY; ly++) { for(uint8_t lx = 0; lx < letterX; lx++) { uint8_t img = pgm_read_byte(&font[(lx+offset*letterX)]); if(invert) img = ~img; drawPoint(i*letterX+lx+x,ly+y, (img >> (ly%8)) & 0b000000001 ); } } } } void Display::drawBorder() { Display::drawRectangle(0,0,Display::Width,1,Display::Color::Black); Display::drawRectangle(0,47,Display::Width,1,Display::Color::Black); Display::drawRectangle(0,0,1,48,Display::Color::Black); Display::drawRectangle(83,0,1,48,Display::Color::Black); }
#ifndef _LASER_BEAM_H #define _LASER_BEAM_H #include "WeaponInfo.h" class LaserBeam : public CWeaponInfo { public: LaserBeam(GenericEntity::OBJECT_TYPE _bulletType); virtual ~LaserBeam(); // Initialise this instance to default values void Init(void); //render weapon void Render(); // Discharge this weapon void Discharge(Vector3 position, Vector3 target); // Get mesh Mesh* GetMesh(); private: //increment pos spawning of projectile float m_fIncrement; // Number of bullet to create and pattern void generateBullet(Vector3 position, Vector3 target, const int numBullet = 1, const float angle = 0.f); }; #endif
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <screen.h> #include <QPixmap> #include <QScreen> #include <QFileDialog> #include <QMessageBox> #include <QString> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QPixmap editPixmap; private: Ui::MainWindow *ui; Screen * screen; public slots: void on_screenbtn_clicked(); void on_drawImg(QPixmap *p); void on_btn_save_clicked(); }; #endif // MAINWINDOW_H
// // Token.cpp // Tarea4Ejercicio3 // // Created by Daniel on 16/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Token.h" Token::Token(){ remitente = 0; destino = 0; mnsj = nullptr; } int Token::verificar(int i){ if(i == remitente){ if(mnsj == nullptr){ std::cout<<"Su mensaje fue recibido"<<std::endl; remitente = 0; ocupado = false; } return 2; } else if (i == destino){ destino = 0; return 1; } else{ return 0; } } void Token::setMensaje(Mensaje* m){ mnsj = m; destino = m->dirDestino; remitente = m->dirOrigen; ocupado = true; } Mensaje* Token::entregarMensaje(){ Mensaje * nuevo = new Mensaje(mnsj->dirOrigen, mnsj->dirDestino, mnsj->mnsj); mnsj = nullptr; return nuevo; }
/* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or other ATmega32U4 based boards. created 9 May 2011 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/SerialEvent */ #include <Servo.h> const int SERVO0=9; const int SERVO1=10; const int SERVO2=11; Servo myservo0; Servo myservo1; Servo myservo2; int angle[3] = {90,90,90}; int newAngle = 0; int index = 0; int tempIndex = 0; char ch; const int maxChar = 3; char angleVal[maxChar]; String inputString = ""; // a String to hold incoming data bool stringComplete = false; // whether the string is complete void setup() { // initialize serial: Serial.begin(38400); // reserve 200 bytes for the inputString: inputString.reserve(200); // Define digital PWM pins for each servo myservo0.attach(SERVO0); myservo1.attach(SERVO1); myservo2.attach(SERVO2); // Initialize all servos to 90 degrees myservo0.write(angle[0]); myservo1.write(angle[1]); myservo2.write(angle[2]); } void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // control servos using sequence stored in input string while( inputString.charAt(index) != '\n' ){ Serial.print("Beginning of loop "); Serial.println(inputString.charAt(index)); ch = inputString.charAt(index); ++index; if( inputString.charAt(index) == ':' ){ Serial.println(inputString.charAt(index)); index++; Serial.print("tempIndex: "); Serial.println(tempIndex); tempIndex = 0; while(isDigit(inputString.charAt(index)) ){//&& (tempIndex < maxChar)){ Serial.println("inside angle loop"); angleVal[tempIndex] = inputString.charAt(index); tempIndex++; index++; } Serial.print("index after angle loop: "); Serial.println(index); Serial.print("The angle value: "); Serial.println(atoi(angleVal)); Serial.print("The servo: "); Serial.println(ch); // call writeServo function here newAngle = atoi(angleVal); //void writeServo( char servo, int newAngle, int angle[]) { writeServo( ch, newAngle, angle); index++; //tempIndex =0; } else { break; } //memset(angle[0], 0, maxChar); for (int i =0; i<=maxChar;i++){ angleVal[i] = 'B'; } //index++; Serial.print("the index at end of loop: "); Serial.println(index); Serial.print("char at index end of loop: "); Serial.println(inputString.charAt(index)); } Serial.println("made it out"); Serial.println(inputString.charAt(index)); // clear the strings inputString = "";//"2:80,0:0,1:0,2:145,1:30,0:150,2:90,1:90,"; index = 0; stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag so the main loop can // do something about it: if (inChar == '\n') { stringComplete = true; } } } void writeServo( char servo, int newAngle, int angle[]) { int i = servo - '0'; //convert char to int Serial.print("the servo number is "); Serial.println(i); if(newAngle >= 0 && newAngle <= 180){ if(newAngle < angle[i]) { for(; angle[i] >= newAngle; angle[i] -= 1) { delay(5); if (servo == '0'){ myservo0.write(angle[i]); } else if (servo == '1'){ myservo1.write(angle[i]); //Serial.println(angle[i]); } else { myservo2.write(angle[i]); } } } else for(; angle[i] <= newAngle; angle[i] += 1){ delay(5); if (servo == '0'){ myservo0.write(angle[i]); } else if (servo == '1'){ //Serial.println(newAngle); //Serial.println(angle[i]); myservo1.write(angle[i]); } else { myservo2.write(angle[i]); } } angle[i] = newAngle; } }
#ifndef CSTATUSWIDGET_H #define CSTATUSWIDGET_H #include <QWidget> #include "ui_CStatusWidget.h" class CStatusWidget : public QWidget, public Ui::CStatusWidget { Q_OBJECT public: CStatusWidget(QWidget *parent = 0); ~CStatusWidget(); private Q_SLOTS: void changePasswd(); void checkLength(); void distributeMessage(); private: void clearInput(); void StorageLastMessage(const QDateTime& time, const QString& msg); void LoadLastMessage(); private: int m_nMsgMaxLength; //推送消息最大字数 }; #endif // CSTATUSWIDGET_H
#include <stdio.h> #include <math.h> #include <glut.h> #include "Controller.h" #define PI 3.14159265358979323846 Controller::Controller(void) { for (int i = 0; i < 256; i++) _key[i] = false; _shiftDown = false; _fpsMode = false; _viewportWidth= 0; _viewportHeight = 0; _mouseLeftDown = false; _mouseRightDown = false; _rotationSpeed = PI / 180 * 0.2; _translationSpeed = 0.05; } Controller::~Controller(void) { } void Controller::keyboard(unsigned char key, int x, int y) { if (key == 27) // Escape key exit(0); if(key == ' ') { _fpsMode = !_fpsMode; if(_fpsMode) { glutSetCursor(GLUT_CURSOR_NONE); glutWarpPointer(_viewportWidth/2, _viewportHeight/2); } else { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); } } if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) { _shiftDown = true; } else { _shiftDown = false; } _key[key] = true; } void Controller::keyUp(unsigned char key, int x, int y) { _key[key] = false; } void Controller::timerMove(int value, Camera &cam, Maze &maze) { if(_fpsMode) { if(_key['w'] || _key['W']) { cam.Move(_translationSpeed, maze); } if(_key['s'] || _key['S']) { cam.Move(-_translationSpeed, maze); } if(_key['a'] || _key['A']) { cam.Strafe(_translationSpeed, maze); } if(_key['d'] || _key['D']) { cam.Strafe(-_translationSpeed, maze); } if(_mouseLeftDown) { cam.Fly(_translationSpeed); } if(_mouseRightDown) { cam.Fly(-_translationSpeed); } } } // Mouse Functions void Controller::mouse(int button, int state, int x, int y) { if(state == GLUT_DOWN) { if(button == GLUT_LEFT_BUTTON) { _mouseLeftDown = true; } else if(button == GLUT_RIGHT_BUTTON) { _mouseRightDown = true; } } else if(state == GLUT_UP) { if(button == GLUT_LEFT_BUTTON) { _mouseLeftDown = false; } else if(button == GLUT_RIGHT_BUTTON) { _mouseRightDown = false; } } } void Controller::mouseMotion(int x, int y, Camera &cam, Maze &maze) { // This variable is hack to stop glutWarpPointer from triggering an event callback to Mouse(...) // This avoids it being called recursively and hanging up the event loop static bool just_warped = false; if(just_warped) { just_warped = false; return; } if(_fpsMode) { int dx = x - _viewportWidth/2; int dy = y - _viewportHeight/2; if(dx) { cam.RotateYaw(_rotationSpeed * dx); } if(dy) { cam.RotatePitch(-_rotationSpeed * dy); } glutWarpPointer(_viewportWidth/2, _viewportHeight/2); just_warped = true; } } int Controller::getViewportWidth() { return _viewportWidth; } void Controller::setViewportWidth(int width) { _viewportWidth = width; } int Controller::getViewportHeight() { return _viewportHeight; } void Controller::setViewportHeight(int height) { _viewportHeight = height; }
#include<WinSock2.h> #include<stdio.h> // #pragma comment(lib,"ws2_32.lib") // #define Ser_PORT 5050 // #define DATA_BUFFER 1024 void main(){ WSADATA wsaData; SOCKET sClient; // int iLen; // int iSend; int iRecv; // printf("请输入你想发送给服务器的一串小写英文字符(不要超过1024个字符): "); char send_buf[DATA_BUFFER]; scanf("%s",send_buf); // char recv_buf[DATA_BUFFER]; // struct sockaddr_in ser; // if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0){ printf("Failed to load Winsock.\n"); system("pause"); return; } sClient = socket(AF_INET,SOCK_DGRAM,0); if(sClient==INVALID_SOCKET){ printf("socket()Failed:%d\n",WSAGetLastError()); system("pause"); return; } // ser.sin_family=AF_INET; ser.sin_port = htons(Ser_PORT); ser.sin_addr.s_addr = inet_addr("172.20.10.5"); iLen=sizeof(ser); // iSend = sendto(sClient,send_buf,strlen(send_buf)+1,0,(struct sockaddr*)&ser,iLen); if(iSend==SOCKET_ERROR){ printf("sendto()Failed:%d\n",WSAGetLastError()); system("pause"); return; }else{ if(iSend==0){ system("pause"); return; }else{ printf("\n-----------------------------------\n"); printf(" 调用sendto()函数给服务器发送的信息是: %s\n",send_buf); printf(" 调用sendto()函数给服务器发送的信息长度是: %d字节\n",iSend); printf(" sendto() succeeded.(调用sendto()函数发送信息成功)\n\n"); } } // memset(recv_buf,'\0',sizeof(recv_buf)); // iRecv = recvfrom(sClient,recv_buf,sizeof(recv_buf),0,(struct sockaddr*)&ser,&iLen); if(iRecv==SOCKET_ERROR){ printf("recvfrom()Failed.:%d\n",WSAGetLastError()); system("pause"); return; }else if(iRecv==0){ system("pause"); return; }else{ // printf(" 调用recvfrom()函数从服务器接收到的信息是:%s\n",recv_buf); printf("-----------------------------------\n"); } closesocket(sClient); WSACleanup(); system("pause"); }
// Linked List Implementation C++ // Node Class represents a node in a Linked List #include <iostream> using namespace std; class Node { public: int value; Node* next; }; class LinkedList { private: Node* root; // Root Node i.e beginning of Linked List public: LinkedList() { root = NULL; } // O(1) insertion. Insert in beginning of Linked List void insertNode(int value) { if (root == NULL) { root = new Node(); root->value = value; root->next = NULL; } else { Node* curr = new Node(); curr->value = value; curr->next = root; root = curr; } } // O(n) search. Iterate through list to find value bool search(int value) { Node* curr = root; while (curr != NULL) { if (curr->value == value) { return true; } curr = curr->next; } return false; } // O(1) Deletion i.e Deletes first node void deletion() { Node* curr = root; curr = curr->next; root = curr; } // O(n) Deletion i.e Delete Specific Node void deleteSpecific(int value) { Node* curr = root; bool deleted = false; // Case where value is first node if (curr->value == value) { curr = curr->next; root = curr; return; } while (curr != NULL && deleted == false) { // deal with case where last node is deleted if ((curr->next->next == NULL) && (curr->next->value == value)) { curr->next = NULL; deleted = true; } // deal with normal case else if (curr->next->value == value) { curr->next = curr->next->next; deleted = true; } else { curr = curr->next; } } } // Basic Print Function Iterates through list. O(n) time complexity void printList() { Node* curr = root; cout << "Printed List\n"; while (curr != NULL) { cout << curr->value << " "; curr = curr->next; } } }; int main() { LinkedList myLinkedList; myLinkedList.insertNode(5); myLinkedList.insertNode(10); myLinkedList.insertNode(7); myLinkedList.insertNode(13); myLinkedList.insertNode(20); myLinkedList.insertNode(8); bool result = myLinkedList.search(10); result ? cout << "Found\n" : cout << "Not Found\n"; myLinkedList.printList(); cout << endl; myLinkedList.deleteSpecific(5); cout << endl; myLinkedList.printList(); cout << endl; myLinkedList.deleteSpecific(8); cout << endl; myLinkedList.printList(); cout << endl; myLinkedList.deleteSpecific(13); cout << endl; myLinkedList.printList(); return 0; }
/* Include the controller definition */ #include <argos3/core/utility/math/rng.h> #include <services/debug_log.h> #include "lootbot_closest_light.h" CLootBotClosest::CLootBotClosest() : steeringActuator(nullptr), charging(false), startedCharging(false), dead(false), pcRNG(nullptr), nextLightPosition(nullptr) {} void CLootBotClosest::Init(TConfigurationNode &node) { getSensorsAndActuators(); pcRNG = CRandom::CreateRNG("argos"); try { readParams(node); } catch (CARGoSException &ex) { THROW_ARGOSEXCEPTION_NESTED("Error parsing the controller parameters.", ex); } refreshRandomTarget(); battery = pcRNG->Uniform(CRange<int>(batteryParams.randomWalkThreshold, batteryParams.capacity)); } void CLootBotClosest::ControlStep() { hasRead[PROXIMITY_SENSOR] = false; hasRead[GROUND_SENSOR] = false; hasRead[POSITIONING_SENSOR] = false; hasRead[LIGHT_SENSOR] = false; startedCharging = false; timestamp++; auto positionOfBot = getPositioningReading(); auto proxReading = getProximityReading(); balServices.fotWalls->addWalls(proxReading, positionOfBot, timestamp, GetId()); balServices.fotBotsFc->addBots(proxReading, positionOfBot, timestamp, GetId(), balServices.fotWalls); if (balServices.fotBotsOa != nullptr) balServices.fotBotsOa->addBots(proxReading, positionOfBot, timestamp, GetId(), balServices.fotWalls); if (!dead) { if (nextLightPosition != nullptr) { if (needsLightUpdate()) { setNextLight(readLight()); } aimToLight(); } else { aimToRandomTarget(randomTimer <= 0); randomTimer--; } updateBattery(); } else { aimToLight(); } } bool CLootBotClosest::needsLightUpdate() { if (!hasUpdated && lightCloserThan(furtherThreshold)) { return true; } return lightCloserThan(4 * targetThreshold); } bool CLootBotClosest::lightCloserThan(double threshold) { return nextLightPosition != nullptr && (*nextLightPosition - get2DPosition()).Length() <= threshold; } bool CLootBotClosest::moveToRandomTargetSinceChargingWasCancelled() { if (charging) { RLOG << "charging aborted" << endl; charging = false; Real cap = batteryParams.randomWalkThreshold + (batteryParams.capacity - batteryParams.randomWalkThreshold) / 2.0; if (battery > cap) { RLOG << "giving up" << endl; setNextLight(nullptr); return true; } RLOG << "retry" << endl; } return false; } void CLootBotClosest::doCharging() { if (!charging) { charging = true; startedCharging = true; } battery += chargePerStep; int goal = batteryParams.capacity // - (0.1 * batteryParams.capacity * balServices.fotBotsFc->noOfBotsNearby(get2DPosition(), GetId(), timestamp)) ; if (battery >= goal) { RLOG << "finished charging" << endl; setNextLight(nullptr); charging = false; aimToRandomTarget(true); } else { stop(); } } void CLootBotClosest::aimToRandomTarget(bool refreshTarget) { if (refreshTarget) { refreshRandomTarget(); } if (balServices.fotWalls->isAimingAtWall(getPositioningReading(), randomDirection)) { BOTLOG << "aiming at wall" << endl; refreshRandomTarget(randomDirection + CRadians::PI_OVER_TWO, randomDirection + 3 * CRadians::PI_OVER_TWO); } // if (battery / (double) batteryParams.capacity > 0.95) { // vector<CColor> colors; // for (int i = 0; i < 4; i++) { // auto color = colorForReading(getGroundReading()[i].Value); // colors.push_back(color); // } // if (moveByColor(colors)) { // return; // } // } // if (battery / (double) batteryParams.capacity > 0.9) { // moveWheelsStraight(1); // return; // } CVector2 randomTarget = get2DPosition() + CVector2(10, randomDirection); setWheelSpeedsFromVector(vectorToPosition(randomTarget)); } void CLootBotClosest::updateBattery() { battery--; if (battery == 0) { stop(); RLOG << "Battery died" << endl; dead = true; } if (battery == batteryParams.randomWalkThreshold) { setNextLight(readLight()); } } CVector2 CLootBotClosest::readLight() { auto position = getPositioningReading(); auto lightReads = getLightReading(); auto result = balServices.forLights->calculateRelevantLight(lightReads, position, nextLightPosition, GetId(), balServices.fotBotsFc, timestamp); if (result.getId() == -1) { return (nextLightPosition != nullptr) ? *nextLightPosition : CVector2(); } else { return result.get2DPosition(); } } void CLootBotClosest::aimToLight() { if (lightCloserThan(furtherThreshold)) { auto groundReads = getGroundReading(); vector<CColor> colors; for (int i = 0; i < 4; i++) { auto color = colorForReading(groundReads[i].Value); colors.push_back(color); if (color == CColor::GRAY80) { // bot is atLight and should be charging doCharging(); return; } } if (dead) { return; } if (moveToRandomTargetSinceChargingWasCancelled()) { aimToRandomTarget(true); return; } if (!moveByColor(colors)) { goToLight(); } } else if (!dead) { goToLight(); } } bool CLootBotClosest::moveByColor(const vector<CColor> &colors) { CColor *readColor = majorColor(colors); if (readColor == nullptr) { // bot is on different colors; continue straight moveWheelsStraight(1); return true; } if (*readColor == CColor::WHITE) { return false; } // bot is in colored area setWheelSpeedsFromVector(directionByColor(readColor), true); return true; } void CLootBotClosest::goToLight() { if (nextLightPosition == nullptr) { stop(); RLOG << "Could not get light" << endl; } else { // bot is far away from the light setWheelSpeedsFromVector(vectorToPosition(*nextLightPosition)); } } CColor * CLootBotClosest::majorColor(vector<CColor> colors) const { for (int i = 1; i < colors.size(); i++) { if (colors[i] != colors[0]) { return nullptr; } } return &colors[0]; } CColor CLootBotClosest::colorForReading(Real reading) const { CColor readColor; if (reading > 0.9) { readColor = CColor::WHITE; } else if (reading > 0.75) { readColor = CColor::GRAY80; } else if (reading > 0.55) { readColor = CColor::GRAY60; } else if (reading > 0.35) { readColor = CColor::GRAY40; } else if (reading > 0.1) { readColor = CColor::GRAY20; } else { readColor = CColor::BLACK; } return readColor; } CVector2 CLootBotClosest::vectorToPosition(CVector2 target) { auto tProx = getPositioningReading(); CQuaternion inv = tProx.Orientation.Inverse(); CVector3 toTarget = CVector3(target.GetX(), target.GetY(), 0) - tProx.Position; CVector3 toTargetBotSpace = toTarget.Rotate(inv); CVector2 toTargetBotSpace2D = CVector2(toTargetBotSpace.GetX(), toTargetBotSpace.GetY()); if (isnan(toTargetBotSpace2D.GetX()) || isnan(toTargetBotSpace2D.GetY())) { RLOGERR << "could not convert target " << target << endl; RLOGERR << "orientation " << tProx.Orientation << endl; RLOGERR << "position " << tProx.Position << endl; return {}; } return toTargetBotSpace2D; } CVector2 CLootBotClosest::directionByColor(CColor *color) { CVector2 direction; if (*color == CColor::GRAY20) { direction = { 0,-1 }; } else if (*color == CColor::GRAY40) { direction = { -1,0 }; } else if (*color == CColor::GRAY60) { direction = { 0,1 }; } else if(*color == CColor::BLACK) { direction = { 1,0 }; } CVector2 aimTo = get2DPosition() + direction; return vectorToPosition(aimTo); } void CLootBotClosest::setWheelSpeedsFromVector(CVector2 heading, bool stopAtObstacle) { if (heading == CVector2::ZERO) { stop(); return; } bool isClose = lightCloserThan(10* targetThreshold); auto botService = (balServices.fotBotsOa != nullptr) ? balServices.fotBotsOa : balServices.fotBotsFc; if (isnan(heading.GetX()) || isnan(heading.GetY())) { RLOGERR << "heading is nan" << endl; stop(); return; } auto direction = balServices.fotWalls->getClosestFreeAngle(heading, getPositioningReading(), timestamp, nextLightPosition != nullptr, GetId(), botService); // if (Abs(NormalizedDifference(direction.first, heading.Angle())) > CRadians(0.05)) { // BOTLOG << "original angle: " << heading.Angle() << ", going to: " << direction.first << endl; // } // CRadians *angle = stopAtObstacle || isClose ? new CRadians(headingAngle) : readingsService->getClosestFreeAngle(headingAngle, getPositioningReading(), timestamp); if (direction.second == 0.0) { RLOG << "cannot move" << endl; stop(); return; } wheelTurningParams.turningMechanism = calculateTurningMechanism(direction.first); switch (wheelTurningParams.turningMechanism) { case SWheelTurningParams::NO_TURN: { moveWheelsStraight(direction.second); break; } case SWheelTurningParams::HARD_TURN: turn(direction.first); break; } } void CLootBotClosest::moveWheelsStraight(double speedMultiplier) const { steeringActuator->SetLinearVelocity(speedMultiplier * wheelTurningParams.maxSpeed, speedMultiplier * wheelTurningParams.maxSpeed); } void CLootBotClosest::stop() const { steeringActuator->SetLinearVelocity(0, 0); } void CLootBotClosest::turn(CRadians headingAngle) { Real leftWheelSpeed, rightWheelSpeed; /* Opposite wheel speeds */ rightWheelSpeed = headingAngle.GetValue() * wheelTurningParams.maxSpeed; leftWheelSpeed = -rightWheelSpeed; steeringActuator->SetLinearVelocity(leftWheelSpeed, rightWheelSpeed); } void CLootBotClosest::refreshRandomTarget(CRadians min, CRadians max) { randomDirection = CRadians(pcRNG->Uniform(CRange<Real>(min.GetValue(), max.GetValue()))); UInt32 diff = batteryParams.capacity - batteryParams.randomWalkThreshold; randomTimer = pcRNG->Uniform(CRange<UInt32>(0, diff)); } void CLootBotClosest::readParams(TConfigurationNode &node) { wheelTurningParams.init(GetNode(node, "wheel_turning")); batteryParams.init(GetNode(node, "battery")); arenaParams.init(GetNode(node, "arena")); } void CLootBotClosest::getSensorsAndActuators() { steeringActuator = GetActuator<CCI_DifferentialSteeringActuator>("differential_steering"); positioningSensor = GetSensor<CCI_PositioningSensor>(POSITIONING_SENSOR); groundSensor = GetSensor<CCI_LootBotMotorGroundSensor>(GROUND_SENSOR); proximitySensor = GetSensor<CCI_LootBotProximitySensor>(PROXIMITY_SENSOR); lightSensor = GetSensor<CCI_LootBotLightSensor>(LIGHT_SENSOR); } CLootBotClosest::SWheelTurningParams::ETurningMechanism CLootBotClosest::calculateTurningMechanism( const CRadians &angle) { if (Abs(angle) <= wheelTurningParams.noTurnAngleThreshold) { return SWheelTurningParams::NO_TURN; } else { return SWheelTurningParams::HARD_TURN; } } void CLootBotClosest::SWheelTurningParams::init(TConfigurationNode &t_node) { try { turningMechanism = NO_TURN; CDegrees cAngle; GetNodeAttribute(t_node, "hard_turn_angle_threshold", cAngle); hardTurnOnAngleThreshold = ToRadians(cAngle); GetNodeAttribute(t_node, "no_turn_angle_threshold", cAngle); noTurnAngleThreshold = ToRadians(cAngle); GetNodeAttribute(t_node, "max_speed", maxSpeed); } catch (CARGoSException &ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing controller wheel turning parameters.", ex); } } void CLootBotClosest::SBatteryParams::init(TConfigurationNode &t_tree) { try { GetNodeAttribute(t_tree, "random_walk_threshold", randomWalkThreshold); GetNodeAttribute(t_tree, "capacity", capacity); } catch (CARGoSException &ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing controller wheel battery parameters.", ex); } } void CLootBotClosest::SArenaParams::init(TConfigurationNode &t_tree) { try { GetNodeAttribute(t_tree, "xLength", xLength); GetNodeAttribute(t_tree, "yLength", yLength); } catch (CARGoSException &ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing controller arena battery parameters.", ex); } } /* * This statement notifies ARGoS of the existence of the controller. * It binds the class passed as first argument to the string passed as second argument. * The string is then usable in the XML configuration file to refer to this controller. * When ARGoS reads that string in the XML file, it knows which controller class to instantiate. * See also the XML configuration files for an example of how this is used. */ REGISTER_CONTROLLER(CLootBotClosest, "lootbot_closest_light_controller")
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; long long a[100100]; bool fig(long long t,int n,long long k) { long long ans = 0; for (int i = 1;i <= n; i++) if (a[i] > t) ans += (a[i] - t - 1)/(k-1) + 1; //cout << t << " " << ans << endl; if (ans <= t) return true; return false; } int main() { int n;long long k; scanf("%d",&n); long long l = 1,r = 0; for (int i = 1;i <= n; i++) { scanf("%I64d",&a[i]); r = max(r,a[i]); } scanf("%I64d",&k); if (k == 1) { l = r; } while (l < r) { //cout << l << " " << r << endl; int mid = l + ((r - l) >> 1); if (fig(mid,n,k)) r = mid; else l = mid + 1; } printf("%I64d\n",l); return 0; }
/** Copyright (c) 2015 Eric Bruneton All rights reserved. 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 the copyright holder 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. */ #include "atmosphere/comparisons.h" #include <algorithm> #include <cstdint> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include "minpng/minpng.h" #include "physics/cie.h" #include "util/progress_bar.h" namespace { using dimensional::vec3; const char* kOutputDir = "output/figures/"; const int kScaleColorMap[162] = { 109, 90, 203, 126, 124, 217, 138, 148, 226, 148, 169, 232, 157, 187, 238, 165, 203, 242, 173, 218, 246, 179, 231, 250, 186, 244, 253, 0, 102, 181, 0, 131, 201, 0, 151, 213, 0, 167, 223, 0, 180, 230, 0, 192, 237, 0, 203, 242, 0, 213, 247, 0, 222, 251, 72, 185, 171, 90, 201, 189, 105, 213, 203, 119, 222, 215, 132, 231, 225, 143, 238, 234, 154, 244, 242, 165, 250, 249, 174, 255, 255, 136, 196, 145, 151, 209, 158, 162, 219, 168, 172, 227, 176, 180, 234, 183, 187, 241, 189, 193, 246, 195, 199, 251, 200, 204, 255, 204, 196, 167, 125, 209, 185, 143, 219, 199, 159, 227, 211, 173, 234, 222, 186, 240, 231, 198, 246, 240, 209, 251, 248, 220, 255, 255, 230, 212, 112, 84, 222, 134, 105, 229, 154, 123, 235, 172, 139, 240, 190, 154, 245, 207, 168, 249, 224, 181, 252, 240, 193, 255, 255, 204 }; const int kErrorColorMap[123] = { 8, 54, 106, 15, 67, 123, 23, 82, 144, 29, 95, 162, 36, 106, 174, +46, 119, 181, 54, 129, 186, 63, 142, 192, 76, 153, 198, 95, 165, 205, 117, 178, 212, 135, 190, 218, 155, 201, 224, 169, 209, 229, 184, 216, 233, 202, 225, 238, 213, 231, 241, 224, 236, 243, 233, 240, 244, 242, 245, 246, 248, 243, 240, 249, 237, 229, 251, 229, 216, 252, 222, 205, 252, 213, 191, 249, 198, 172, 247, 185, 156, 245, 170, 137, 240, 156, 123, 233, 139, 110, 225, 120, 96, 218, 104, 83, 208, 85, 72, 200, 68, 64, 191, 51, 56, 182, 31, 46, 168, 21, 41, 147, 14, 38, 129, 8, 35, 112, 3, 32, 103, 0, 31 }; void GetScaleColor(double x, int* red, int* green, int* blue) { int n = floor(log(x) / log(10.0)); int i = floor(x / pow(10.0, n)) - 1; int color_index = 3 * (i + 9 * n); if (color_index < 0) { *red = 255; *green = 0; *blue = 0; } else if (color_index > 159) { *red = 255; *green = 255; *blue = 0; } else { *red = kScaleColorMap[color_index]; *green = kScaleColorMap[color_index + 1]; *blue = kScaleColorMap[color_index + 2]; } } void GetErrorColor(double x, int* red, int* green, int* blue) { int n = floor(x * 10.0) + 20; int color_index = 3 * std::max(0, std::min(40, n)); *red = kErrorColorMap[color_index]; *green = kErrorColorMap[color_index + 1]; *blue = kErrorColorMap[color_index + 2]; } uint32_t Blend(uint32_t background, uint32_t foreground) { int red1 = (background >> 16) & 0xFF; int green1 = (background >> 8) & 0xFF; int blue1 = background & 0xFF; int red2 = (foreground >> 16) & 0xFF; int green2 = (foreground >> 8) & 0xFF; int blue2 = foreground & 0xFF; double blend = (foreground >> 24) / 255.0; int red = red1 * (1.0 - blend) + red2 * blend; int green = green1 * (1.0 - blend) + green2 * blend; int blue = blue1 * (1.0 - blend) + blue2 * blend; return (0xFF << 24) | (red << 16) | (green << 8) | blue; } void DrawCross(Angle sun_zenith, Angle sun_azimuth, int size, uint32_t color, int width, int height, uint32_t* pixels) { Number radius = sun_zenith / (pi / 2.0); Number x = radius * sin(sun_azimuth); Number y = radius * cos(sun_azimuth); int i = static_cast<int>((x * (width / 2.0) + width / 2.0 - 0.5)()); int j = static_cast<int>((y * (height / 2.0) + height / 2.0 - 0.5)()); for (int x = -size; x <= size; ++x) { pixels[i + x + j * width] = Blend(pixels[i + x + j * width], color); } for (int x = -size; x <= size; ++x) { if (x != 0) { pixels[i + (j + x) * width] = Blend(pixels[i + (j + x) * width], color); } } } void DrawCrosses(Angle sun_zenith, Angle sun_azimuth, int width, int height, uint32_t* pixels) { DrawCross(sun_zenith, sun_azimuth, 5, 0xFFFF0000, width, height, pixels); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { Angle view_zenith; Angle view_azimuth; HemisphericalFunction<Number>::GetSampleDirection( i, j, &view_zenith, &view_azimuth); DrawCross( view_zenith, view_azimuth, 0, 0x40000000, width, height, pixels); } } } vec3 ToneMapping(Color rgb) { constexpr Luminance c = 5.0 * MaxLuminousEfficacy * watt_per_square_meter_per_sr; return vec3( 1.0 - exp(-rgb.x / c), 1.0 - exp(-rgb.y / c), 1.0 - exp(-rgb.z / c)); } Number GetColorErrorSquare(Color a, Color b) { vec3 ta = ToneMapping(a); vec3 tb = ToneMapping(b); return dot(ta - tb, ta - tb); } void WritePngArgb(const std::string& name, void* pixels, int width, int height) { write_png(name.c_str(), pixels, width, height); } } // anonymous namespace Comparisons::Comparisons(const std::string& name, const Atmosphere& atmosphere, const MeasuredAtmospheres& reference, Wavelength min_wavelength, Wavelength max_wavelength) : name_(name), atmosphere_(atmosphere), reference_(reference), min_wavelength_(min_wavelength), max_wavelength_(max_wavelength) {} void Comparisons::RenderSkyImage(const std::string& name, Angle sun_zenith, Angle sun_azimuth, bool white_balance) const { const int width = 1024; const int height = 576; const Angle kHorizontalFov = 90.0 * deg; const Angle kVerticalFov = 2.0 * atan(tan(kHorizontalFov / 2.0) * height / width); const vec3 left(1.0, 0.0, 0.0); const vec3 top(0.0, -sin(kVerticalFov / 2.0), cos(kVerticalFov / 2.0)); const vec3 center = vec3(0.0, cos(kVerticalFov / 2.0), sin(kVerticalFov / 2.0)) * (width / (2.0 * tan(kHorizontalFov / 2.0))); const Angle kSunApex = 0.5357 * deg; const SolidAngle kSunSolidAngle = 2.0 * PI * (1.0 - cos(kSunApex * 0.5)) * sr; Number normalization_factor = 36.0 * watt_per_square_meter / Integral(atmosphere_.GetSkyIrradiance(0.0 * m, sun_zenith)); std::unique_ptr<vec3[]> data(new vec3[width * height]); ProgressBar progress_bar(width * height); RunJobs([&](int j) { for (int i = 0; i < width; ++i) { vec3 view_dir = normalize(center + left * Number(i - width / 2) + top * Number(height - 1 - j - height / 2)); Angle view_zenith = acos(view_dir.z); Angle view_azimuth = atan2(view_dir.x, view_dir.y); RadianceSpectrum radiance = atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); Number cos_angle = cos(view_zenith) * cos(sun_zenith) + sin(view_zenith) * sin(sun_zenith) * cos(view_azimuth - sun_azimuth); if (acos(cos_angle) < kSunApex * 0.5) { radiance = atmosphere_.GetSunIrradiance(0.0 * m, sun_zenith) * (1.0 / kSunSolidAngle); } Color rgb = GetOriginalColor(radiance * normalization_factor); if (white_balance) { rgb = WhiteBalanceNaive(rgb); } data[i + j * width] = ToneMapping(rgb) * 255.0; progress_bar.Increment(1); } }, height); std::unique_ptr<uint32_t[]> pixels(new uint32_t[width * height]); std::unique_ptr<vec3[]> dither(new vec3[width * height]); for (int i = 0; i < width * height; ++i) { dither[i] = vec3(0.0, 0.0, 0.0); } for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { vec3 color = data[i + j * width] + dither[i + j * width]; int red = round(color.x()); int green = round(color.y()); int blue = round(color.z()); pixels[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; // See https://en.wikipedia.org/wiki/Floyd–Steinberg_dithering. vec3 error = color - vec3(red, green, blue); if (i + 1 < width) { dither[(i + 1) + j * width] += error * (7 / 16.0); } if (j + 1 < height) { if (i - 1 >= 0) { dither[(i - 1) + (j + 1) * width] += error * (3 / 16.0); } dither[i + (j + 1) * width] += error * (5 / 16.0); if (i + 1 < width) { dither[(i + 1) + (j + 1) * width] += error * (1 / 16.0); } } } } std::string filename = GetOutputDir() + "sky_image_" + name + "_" + name_ + ".png"; WritePngArgb(filename, pixels.get(), width, height); } void Comparisons::PlotSunIlluminanceAttenuation() const { const DimensionlessSpectrum& y_bar = cie_y_bar_function(); Irradiance extra_terrestrial_illuminance = Integral(SolarSpectrum() * y_bar); std::ofstream file(GetOutputDir() + "sun_illuminance_attenuation_" + name_ + ".txt"); for (int i = 0; i <= 90; ++i) { Angle sun_zenith = i * deg; Irradiance ground_illuminance = Integral(atmosphere_.GetSunIrradiance(0.0 * m, sun_zenith) * y_bar); file << sun_zenith.to(deg) << " " << (ground_illuminance / extra_terrestrial_illuminance)() << std::endl; } file.close(); } void Comparisons::PlotRadiance(const std::string& name, Angle sun_zenith, Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const { RadianceSpectrum radiance = atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); std::stringstream filename; filename << GetOutputDir() << "radiance_" << name << "_" << view_zenith.to(deg) << "_" << view_azimuth.to(deg) << "_" << name_ << ".txt"; std::ofstream file(filename.str()); for (unsigned int i = 0; i < radiance.size(); ++i) { file << radiance.GetSample(i).to(nm) << " " << radiance[i].to(watt_per_square_meter_per_sr_per_nm) << std::endl; } file.close(); } void Comparisons::RenderLuminanceAndImage(const std::string& name, Angle sun_zenith, Angle sun_azimuth) const { const Luminance zenith_luminance = GetLuminance(atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, 0.0 * deg, 0.0 * deg)); const int width = 256; const int height = 256; std::unique_ptr<uint32_t[]> pixels1(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels2(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels3(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels4(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels5(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels6(new uint32_t[width * height]); std::unique_ptr<uint32_t[]> pixels7(new uint32_t[width * height]); double square_error_sum = 0.0; int count = 0; RunJobs([&](unsigned int j) { for (int i = 0; i < width; ++i) { Number x = (i + 0.5 - width / 2.0) / (width / 2.0); Number y = (height / 2.0 - 0.5 - j) / (height / 2.0); Number radius = sqrt(x * x + y * y); if (radius >= 1.0) { pixels1[i + j * width] = 0; pixels2[i + j * width] = 0; pixels3[i + j * width] = 0; pixels4[i + j * width] = 0xFF << 24; pixels5[i + j * width] = 0xFF << 24; pixels6[i + j * width] = 0xFF << 24; pixels7[i + j * width] = 0xFF << 24; continue; } Angle view_zenith = radius * pi / 2.0; Angle view_azimuth = atan2(x, -y); RadianceSpectrum radiance = atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); const Luminance view_dir_luminance = GetLuminance(radiance); Number relative_luminance = view_dir_luminance / zenith_luminance; int red, green, blue; GetScaleColor( view_dir_luminance.to(cd_per_square_meter), &red, &green, &blue); pixels1[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; GetScaleColor(relative_luminance() * 100.0, &red, &green, &blue); pixels2[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; Color rgb = GetSrgbColor(radiance); Color rgb_original = GetOriginalColor(radiance); Color rgb_approx_spectral = GetSrgbColorFrom3SpectrumSamples(radiance); const Luminance rgb_max = std::max(rgb.x, std::max(rgb.y, rgb.z)); red = 255.0 * (rgb.x / rgb_max)(); green = 255.0 * (rgb.y / rgb_max)(); blue = 255.0 * (rgb.z / rgb_max)(); pixels3[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; vec3 c = ToneMapping(rgb); red = 255.0 * c.x(); green = 255.0 * c.y(); blue = 255.0 * c.z(); pixels4[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; c = ToneMapping(rgb_original); int r = 255.0 * c.x(); int g = 255.0 * c.y(); int b = 255.0 * c.z(); pixels5[i + j * width] = (0xFF << 24) | (r << 16) | (g << 8) | b; c = ToneMapping(rgb_approx_spectral); r = 255.0 * c.x(); g = 255.0 * c.y(); b = 255.0 * c.z(); pixels6[i + j * width] = (0xFF << 24) | (r << 16) | (g << 8) | b; square_error_sum += (r - red) * (r - red) + (g - green) * (g - green) + (b - blue) * (b - blue); count += 1; r = std::abs(r - red) * 10; g = std::abs(g - green) * 10; b = std::abs(b - blue) * 10; pixels7[i + j * width] = (0xFF << 24) | (r << 16) | (g << 8) | b; } }, height); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels1.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels2.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels3.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels4.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels5.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels6.get()); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels7.get()); std::string filename1 = GetOutputDir() + "absolute_luminance_" + name + "_" + name_ + ".png"; WritePngArgb(filename1, pixels1.get(), width, height); std::string filename2 = GetOutputDir() + "relative_luminance_" + name + "_" + name_ + ".png"; WritePngArgb(filename2, pixels2.get(), width, height); std::string filename3 = GetOutputDir() + "chromaticity_" + name + "_" + name_ + ".png"; WritePngArgb(filename3, pixels3.get(), width, height); std::string filename4 = GetOutputDir() + "image_full_spectral_" + name + "_" + name_ + ".png"; WritePngArgb(filename4, pixels4.get(), width, height); std::string filename5 = GetOutputDir() + "image_original_" + name + "_" + name_ + ".png"; WritePngArgb(filename5, pixels5.get(), width, height); std::string filename6 = GetOutputDir() + "image_approx_spectral_" + name + "_" + name_ + ".png"; WritePngArgb(filename6, pixels6.get(), width, height); std::string filename7 = GetOutputDir() + "image_approx_diff_" + name + "_" + name_ + ".png"; WritePngArgb(filename7, pixels7.get(), width, height); double mean_square_error = sqrt(square_error_sum / count); double psnr = 10.0 * log(255 * 255 / mean_square_error) / log(10.0); std::ofstream psnr_stream( GetOutputDir() + "image_approx_psnr_" + name + "_" + name_ + ".txt"); psnr_stream << round(psnr * 10.0) / 10.0 << std::endl; psnr_stream.close(); } void Comparisons::PlotLuminanceProfile(const std::string& name, Angle sun_zenith, Angle sun_azimuth) const { std::string filename = GetOutputDir() + "luminance_profile_" + name + "_" + name_ + ".txt"; std::ofstream file(filename); if (&atmosphere_ == &reference_) { for (int i = 0; i < 9; ++i) { Angle view_zenith; Angle view_azimuth; HemisphericalFunction<Number>::GetSampleDirection( 8 - i, i, &view_zenith, &view_azimuth); Luminance measured = GetLuminance(reference_.GetSkyRadianceMeasurement( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth)); file << (i < 4 ? -view_zenith.to(deg) : view_zenith.to(deg)) << " " << measured.to(cd_per_square_meter) << std::endl; } } else { for (int i = 2; i <= 62; ++i) { Angle view_zenith = std::abs(i - 32) / 32.0 * pi / 2.0; Angle view_azimuth = i < 32 ? -45 * deg : 135 * deg; Luminance model = GetLuminance(atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth)); file << (i < 32 ? -view_zenith.to(deg) : view_zenith.to(deg)) << " " << model.to(cd_per_square_meter) << std::endl; } } file.close(); } SpectralRadiance Comparisons::PlotRelativeError(const std::string& name, Angle sun_zenith, Angle sun_azimuth, SpectralRadiance* rmse_with_approximate_spectrum) const { // Relative error for the measured directions, and interpolated in between. HemisphericalFunction<Number> relative_error; Number rgb_rmse; Number original_rgb_rmse; Number approximate_rgb_rmse; SpectralRadiance rmse = ComputeRelativeErrorAndRmse(sun_zenith, sun_azimuth, &relative_error, rmse_with_approximate_spectrum, &rgb_rmse, &original_rgb_rmse, &approximate_rgb_rmse); std::ofstream file(GetOutputDir() + "error_" + name + "_" + name_ + ".txt"); double rounded_rmse = round(rmse.to(1e-4 * watt_per_square_meter_per_sr_per_nm)) / 10.0; file << rounded_rmse << std::endl; file.close(); file.open(GetOutputDir() + "error_rgb_" + name + "_" + name_ + ".txt"); rounded_rmse = round(rgb_rmse() * 10000.0) / 10.0; file << rounded_rmse << std::endl; file.close(); file.open( GetOutputDir() + "error_original_rgb_" + name + "_" + name_ + ".txt"); rounded_rmse = round(original_rgb_rmse() * 10000.0) / 10.0; file << rounded_rmse << std::endl; file.close(); file.open(GetOutputDir() + "error_approximate_rgb_" + name + "_" + name_ + ".txt"); rounded_rmse = round(approximate_rgb_rmse() * 10000.0) / 10.0; file << rounded_rmse << std::endl; file.close(); const int width = 256; const int height = 256; std::unique_ptr<uint32_t[]> pixels(new uint32_t[width * height]); for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { Number x = (i + 0.5 - width / 2.0) / (width / 2.0); Number y = (height / 2.0 - 0.5 - j) / (height / 2.0); Number radius = sqrt(x * x + y * y); if (radius >= 1.0) { pixels[i + j * width] = 0; continue; } Angle view_zenith = radius * pi / 2.0; Angle view_azimuth = atan2(x, -y); double error = relative_error(view_zenith, view_azimuth)(); int red, green, blue; GetErrorColor(error, &red, &green, &blue); pixels[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; } } DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels.get()); std::string filename = GetOutputDir() + "relative_error_" + name + "_" + name_ + ".png"; WritePngArgb(filename, pixels.get(), width, height); return rmse; } void Comparisons::PlotRelativeError(const std::string& name, const Atmosphere& reference, Angle sun_zenith, Angle sun_azimuth) const { const int width = 256; const int height = 256; std::unique_ptr<uint32_t[]> pixels(new uint32_t[width * height]); int count = 0; auto error_square_sum = 0.0 * watt_per_square_meter_per_sr_per_nm * watt_per_square_meter_per_sr_per_nm; RunJobs([&](unsigned int j) { for (int i = 0; i < width; ++i) { Number x = (i + 0.5 - width / 2.0) / (width / 2.0); Number y = (height / 2.0 - 0.5 - j) / (height / 2.0); Number radius = sqrt(x * x + y * y); if (radius >= 1.0) { pixels[i + j * width] = 0; continue; } Angle view_zenith = radius * pi / 2.0; Angle view_azimuth = atan2(x, -y); RadianceSpectrum model_spectrum = atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); RadianceSpectrum reference_spectrum = reference.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); Radiance model = Integral(model_spectrum, min_wavelength_, max_wavelength_); Radiance ref = Integral(reference_spectrum, min_wavelength_, max_wavelength_); Number relative_error = (model - ref) / ref; for (unsigned int k = 0; k < model_spectrum.size(); ++k) { if (model_spectrum.GetSample(k) >= min_wavelength_ && model_spectrum.GetSample(k) <= max_wavelength_) { count += 1; error_square_sum += (model_spectrum[k] - reference_spectrum[k]) * (model_spectrum[k] - reference_spectrum[k]); } } int red, green, blue; GetErrorColor(relative_error(), &red, &green, &blue); pixels[i + j * width] = (0xFF << 24) | (red << 16) | (green << 8) | blue; } }, height); DrawCrosses(sun_zenith, sun_azimuth, width, height, pixels.get()); std::string filename = GetOutputDir() + "relative_error_" + name + "_" + name_ + ".png"; WritePngArgb(filename, pixels.get(), width, height); SpectralRadiance rmse = sqrt(error_square_sum / count); double rounded_rmse = round(rmse.to(1e-4 * watt_per_square_meter_per_sr_per_nm)) / 10.0; std::ofstream file(GetOutputDir() + "error_" + name + "_" + name_ + ".txt"); file << rounded_rmse << std::endl; file.close(); } SpectralRadiance Comparisons::ComputeTotalRmse( const std::vector<Angle>& sun_zenith, const std::vector<Angle>& sun_azimuth) const { auto error_square_sum = 0.0 * watt_per_square_meter_per_sr_per_nm * watt_per_square_meter_per_sr_per_nm; for (unsigned int i = 0; i < sun_zenith.size(); ++i) { HemisphericalFunction<Number> relative_error; SpectralRadiance rmse_with_approximate_spectrum; Number rgb_rmse; Number original_rgb_rmse; Number approximate_rgb_rmse; SpectralRadiance rmse = ComputeRelativeErrorAndRmse(sun_zenith[i], sun_azimuth[i], &relative_error, &rmse_with_approximate_spectrum, &rgb_rmse, &original_rgb_rmse, &approximate_rgb_rmse); error_square_sum += rmse * rmse; } return sqrt(error_square_sum / sun_zenith.size()); } Luminance Comparisons::ComputeZenithLuminance(Angle sun_zenith) const { return GetLuminance( atmosphere_.GetSkyRadiance(0.0 * m, sun_zenith, 0.0 * deg, 0.0 * deg)); } void Comparisons::ComputeIrradiance(Angle sun_zenith, Irradiance* sun, Irradiance* sky) const { Number cosine = cos(sun_zenith); *sky = Integral(atmosphere_.GetSkyIrradiance(0.0 * m, sun_zenith), min_wavelength_, max_wavelength_); *sun = Integral(atmosphere_.GetSunIrradiance(0.0 * m, sun_zenith) * cosine, min_wavelength_, max_wavelength_); } void Comparisons::PlotDayZenithLuminance( const std::vector<Angle>& sun_zenith, const std::vector<Luminance>& zenith_luminance) const { std::ofstream file( GetOutputDir() + "day_zenith_luminance_" + name_ + ".txt"); for (unsigned int i = 0; i < sun_zenith.size(); ++i) { file << i << " " << zenith_luminance[i].to(cd_per_square_meter) << std::endl; } file.close(); } void Comparisons::PlotDayIrradiance( const std::vector<Angle>& sun_zenith, const std::vector<Irradiance>& sun, const std::vector<Irradiance>& sky) const { std::ofstream file(GetOutputDir() + "day_irradiance_" + name_ + ".txt"); for (unsigned int i = 0; i < sun_zenith.size(); ++i) { file << i << " " << (sun[i] + sky[i]).to(watt_per_square_meter) << " " << sky[i].to(watt_per_square_meter) << std::endl; } file.close(); } const std::string Comparisons::GetOutputDir() { return kOutputDir; } std::string Comparisons::SaveGroundAlbedo() { std::ofstream albedo(GetOutputDir() + "ground_albedo.txt"); const DimensionlessSpectrum& ground_albedo = GroundAlbedo(); for (unsigned int i = 0; i < ground_albedo.size(); ++i) { albedo << ground_albedo.GetSample(i).to(nm) << " " << ground_albedo[i]() << std::endl; } return "reset\n" "set terminal postscript eps size 8.5cm,5.0cm\n" "set output \"" + GetOutputDir() + "ground_albedo.eps\"\n" "set xlabel \"Wavelength (nm)\"\n" "set ylabel \"Albedo\"\n" "set xtics nomirror\n" "set ytics nomirror\n" "set grid noxtics ytics\n" "unset key\n" "plot [360:720][0:] \"" + GetOutputDir() + "ground_albedo.txt\" with lines\n"; } std::string Comparisons::SaveErrorCaption() { std::ofstream palette(GetOutputDir() + "error_palette.txt"); for (int i = 0; i < 41; ++i) { palette << kErrorColorMap[3 * i] << " " << kErrorColorMap[3 * i + 1] << " " << kErrorColorMap[3 * i + 2] << std::endl; } palette.close(); std::ofstream caption(GetOutputDir() + "error_caption.txt"); for (int j = 0; j < 2; ++j) { for (int i = 0; i < 41; ++i) { caption << i << " "; } caption << std::endl; } caption.close(); return "reset\n" "set terminal postscript eps size 15cm,1.2cm enhanced\n" "set output \"" + GetOutputDir() + "error_caption.eps\"\n" "set xtics border out nomirror\n" "set xtics (\"-200\" -0.5, \"-150\" 4.5, \"-100\" 9.5, " "\"-50\" 14.5, \"0\" 19.5, \"50\" 24.5, \"100\" 29.5, \"150\" 34.5, " "\"200\" 39.5)\n" "unset ytics\n" "set palette model RGB " "file \"" + GetOutputDir() + "error_palette.txt\" " "using ($1/255):($2/255):($3/255)\n" "unset key\n" "unset title\n" "unset colorbox\n" "plot \"" + GetOutputDir() + "error_caption.txt\" matrix with image"; } std::string Comparisons::SaveScaleCaption() { std::ofstream palette(GetOutputDir() + "scale_palette.txt"); for (int i = -12; i < 6 * 64 + 12; ++i) { int red, green, blue; GetScaleColor(pow(10.0, i / 64.0), &red, &green, &blue); palette << red << " " << green << " " << blue << std::endl; } palette.close(); std::ofstream caption(GetOutputDir() + "scale_caption.txt"); for (int j = 0; j < 2; ++j) { for (int i = 0; i < 6 * 64 + 24; ++i) { caption << i << " "; } caption << std::endl; } caption.close(); return "reset\n" "set terminal postscript eps size 15cm,1.2cm enhanced\n" "set output \"" + GetOutputDir() + "scale_caption.eps\"\n" "set xtics (\"1\" 13, \"10\" 77, \"10^2\" 140, \"10^3\" 204, " "\"10^4\" 268, \"10^5\" 331, \"10^6\" 395)\n" "set xtics border out nomirror\n" "unset ytics\n" "set palette model RGB " "file \"" + GetOutputDir() + "scale_palette.txt\" " "using ($1/255):($2/255):($3/255)\n" "unset key\n" "unset title\n" "unset colorbox\n" "plot \"" + GetOutputDir() + "scale_caption.txt\" matrix with image"; } Color Comparisons::GetOriginalColor(const RadianceSpectrum& radiance) const { if (atmosphere_.GetOriginalNumberOfWavelengths() == 3) { return GetSrgbColorNaive(radiance); } else if (atmosphere_.GetOriginalNumberOfWavelengths() == DimensionlessSpectrum::SIZE) { return GetSrgbColor(radiance); } else { return GetSrgbColor(radiance, min_wavelength_, max_wavelength_, atmosphere_.GetOriginalNumberOfWavelengths()); } } SpectralRadiance Comparisons::ComputeRelativeErrorAndRmse(Angle sun_zenith, Angle sun_azimuth, HemisphericalFunction<Number>* relative_error, SpectralRadiance* rmse_with_approximate_spectrum, Number* rgb_rmse, Number* original_rgb_rmse, Number* approximate_rgb_rmse) const { int count = 0; auto error_square_sum = 0.0 * watt_per_square_meter_per_sr_per_nm * watt_per_square_meter_per_sr_per_nm; auto error_square_sum_with_approximate_spectrum = error_square_sum; Number rgb_error_square_sum = 0.0; auto original_rgb_error_square_sum = rgb_error_square_sum; auto approximate_rgb_error_square_sum = rgb_error_square_sum; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { Angle view_zenith; Angle view_azimuth; HemisphericalFunction<Number>::GetSampleDirection( i, j, &view_zenith, &view_azimuth); RadianceSpectrum model_spectrum = atmosphere_.GetSkyRadiance( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); RadianceSpectrum model_approximate_spectrum = GetApproximateSpectrumFrom3SpectrumSamples(model_spectrum); RadianceSpectrum measured_spectrum = reference_.GetSkyRadianceMeasurement( 0.0 * m, sun_zenith, sun_azimuth, view_zenith, view_azimuth); Radiance model = Integral(model_spectrum, min_wavelength_, max_wavelength_); Radiance measured = Integral(measured_spectrum, min_wavelength_, max_wavelength_); for (unsigned int k = 0; k < model_spectrum.size(); ++k) { if (model_spectrum.GetSample(k) >= min_wavelength_ && model_spectrum.GetSample(k) <= max_wavelength_) { count += 1; error_square_sum += (model_spectrum[k] - measured_spectrum[k]) * (model_spectrum[k] - measured_spectrum[k]); error_square_sum_with_approximate_spectrum += (model_approximate_spectrum[k] - measured_spectrum[k]) * (model_approximate_spectrum[k] - measured_spectrum[k]); } } Color model_rgb = GetSrgbColor(model_spectrum); Color model_original_rgb = GetOriginalColor(model_spectrum); Color model_approximate_rgb = GetSrgbColorFrom3SpectrumSamples(model_spectrum); Color measured_rgb = GetSrgbColor(measured_spectrum); rgb_error_square_sum += GetColorErrorSquare(model_rgb, measured_rgb); original_rgb_error_square_sum += GetColorErrorSquare(model_original_rgb, measured_rgb); approximate_rgb_error_square_sum += GetColorErrorSquare(model_approximate_rgb, measured_rgb); relative_error->Set(i, j, (model - measured) / measured); } } *rmse_with_approximate_spectrum = sqrt(error_square_sum_with_approximate_spectrum / count); *rgb_rmse = sqrt(rgb_error_square_sum / count); *original_rgb_rmse = sqrt(original_rgb_error_square_sum / count); *approximate_rgb_rmse = sqrt(approximate_rgb_error_square_sum / count); return sqrt(error_square_sum / count); }