text
stringlengths
8
6.88M
#include "forgetpass.h" #include "ui_forgetpass.h" forgetpass::forgetpass(QWidget *parent) : QWidget(parent), ui(new Ui::forgetpass) { ui->setupUi(this); } forgetpass::~forgetpass() { delete ui; } void forgetpass::closeEvent(QCloseEvent * event) { ui->userid->clear(); ui->password->clear(); ui->confirmpassword->clear(); ui->masterkey->clear(); event->accept(); } void forgetpass::on_showpass_pressed() { ui->password->setEchoMode(QLineEdit::Normal); } void forgetpass::on_showpass_released() { ui->password->setEchoMode(QLineEdit::Password); } void forgetpass::on_showconfpass_pressed() { ui->confirmpassword->setEchoMode(QLineEdit::Normal); } void forgetpass::on_showconfpass_released() { ui->confirmpassword->setEchoMode(QLineEdit::Password); } void forgetpass::on_showmasterkey_pressed() { ui->masterkey->setEchoMode(QLineEdit::Normal); } void forgetpass::on_showmasterkey_released() { ui->masterkey->setEchoMode(QLineEdit::Password); } void forgetpass::on_reset_clicked() { ui->information->setText(""); if(ui->userid->text().isEmpty()){ ui->userid->setFocus(); ui->warning->setText("USER ID HARUS DIISI !"); }else if(ui->password->text().isEmpty()){ ui->password->setFocus(); ui->warning->setText("PASSWORD HARUS DIISI !"); }else if(ui->confirmpassword->text().isEmpty()){ ui->confirmpassword->setFocus(); ui->warning->setText("KONFIRMASI HARUS DIISI !"); }else if(ui->confirmpassword->text() != ui->password->text()){ ui->confirmpassword->setFocus(); ui->warning->setText("KONFIRMASI HARUS SAMA DENGAN PASSWORD !"); }else if(ui->masterkey->text().isEmpty()){ ui->masterkey->setFocus(); ui->warning->setText("MASTER KEY HARUS DIISI !"); }else{ ui->warning->setText(""); string userid = ui->userid->text().toStdString(); string pass = ui->password->text().toStdString(); string passconf = ui->confirmpassword->text().toStdString(); string master = ui->masterkey->text().toStdString(); connection conn = connection(); QByteArray masterhex = QByteArray::fromStdString(master); QByteArray passhex = QByteArray::fromStdString(pass); conn.hash = new QCryptographicHash(QCryptographicHash::Sha256); conn.hash->addData(masterhex); masterhex = conn.hash->result().toHex(); conn.hash->reset(); conn.hash = new QCryptographicHash(QCryptographicHash::Sha1); conn.hash->addData(passhex); passhex = conn.hash->result().toHex(); delete conn.hash; if(conn.ok){ QSqlQuery query = QSqlQuery(conn.db); query.exec("SELECT * FROM user WHERE id = 1"); if(query.next()){ if(query.value(2) == masterhex){ query.prepare("SELECT * FROM user WHERE username = :user"); query.bindValue(":user",QString::fromStdString(userid)); query.exec(); if(query.next()){ query.prepare("UPDATE user SET password = :pass WHERE username = :user"); query.bindValue(":user",QString::fromStdString(userid)); query.bindValue(":pass",passhex); if(query.exec()){ ui->warning->setText(""); ui->information->setText("KATA SANDI BERHASIL DIGANTI"); ui->userid->clear(); ui->password->clear(); ui->confirmpassword->clear(); ui->masterkey->clear(); ui->userid->setFocus(); }else { ui->warning->setText("KATA SANDI GAGAL DIGANTI"); ui->userid->clear(); ui->password->clear(); ui->confirmpassword->clear(); ui->masterkey->clear(); ui->userid->setFocus(); } }else{ ui->warning->setText("USER ID TIDAK TERDAFTAR"); ui->userid->clear(); ui->password->clear(); ui->confirmpassword->clear(); ui->masterkey->clear(); ui->userid->setFocus(); } }else{ ui->warning->setText("MASTER KEY SALAH !"); ui->masterkey->clear(); ui->masterkey->setFocus(); } } }else{ ui->warning->setText("DB Error !"); } conn.db.close(); } } void forgetpass::on_confirmpassword_textChanged(const QString &arg1) { if(ui->confirmpassword->text() != ui->password->text()){ ui->warning->setText("KONFIRMASI HARUS SAMA DENGAN PASSWORD !"); }else{ ui->warning->setText(""); } } void forgetpass::on_userid_returnPressed() { this->on_reset_clicked(); } void forgetpass::on_password_returnPressed() { this->on_reset_clicked(); } void forgetpass::on_confirmpassword_returnPressed() { this->on_reset_clicked(); } void forgetpass::on_masterkey_returnPressed() { this->on_reset_clicked(); }
// // main.cpp // HashTable // // Created by Georgiy danielyan on 5/10/15. // Copyright (c) 2015 Goga. All rights reserved. // // Hash Table Tutorial by PaulProgramming. // Followed along and replicated the code. // Hash Table and methods work properly. #include "Hash.h" int main(){ Hash Hashy; Hashy.addItem("Georgiy", "Coffee"); /* Hashy.addItem("Paul", "Locha"); Hashy.addItem("Kim", "Iced Mocha"); Hashy.addItem("Emma", "Strawberry Smoothie"); Hashy.addItem("Annie", "Hot Chocolate"); Hashy.addItem("Sarah", "Passion Tea"); Hashy.addItem("Pepper", "Caramel Mocha"); Hashy.addItem("Mike", "Chai Tea"); Hashy.addItem("Steve", "Apple Cider"); Hashy.addItem("Bill", "Root Beer"); Hashy.addItem("Marie", "Skinny Latte"); Hashy.addItem("Susan", "Water"); Hashy.addItem("Joe", "Green Tea"); Hashy.printTable(); string name = ""; while(name != "exit") { cout << "Remove who?"; cin >> name; if(name != "exit") { Hashy.removeItem(name); } } Hashy.printTable();*/ return 0; }
#include<iostream> #include<string> #include<vector> using namespace std; class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<int>> attack(n, vector<int>(n, 0)); //皇后攻击范围 vector<vector<string>> reses; //最后结果集合 vector<string> res; //单个结果 for(int i=0; i<n; i++) { res.push_back(""); res[i].append(n,'.'); } backtrack(reses,res,n,attack, 0); return reses; } // vector<string> generateBoard(vector<string>& res, int n) { // auto board = vector<string>(); // for (int i = 0; i < n; i++) { // board.push_back(res[i]); // } // return board; // } void backtrack(vector<vector<string>>& reses,vector<string>& res, int n,vector<vector<int>>& attack, int index) { if(index==n) { // vector<string> board = generateBoard(res, n); // cout<<"==========="<<endl; // // for(int x=0; x<n; x++) { // cout<<res[x]<<endl; // } reses.push_back(res); return; } for(int i=0; i<n; i++) { if(attack[index][i] == 0) { vector<vector<int>> attack_temp= attack; //保存这个attack; res[index][i] = 'Q'; // 第index行,第i列放一个Q; put_queen(index,i,attack); //更新attack的范围; // for(int j=0; j<n; j++) { // cout<<res[j]<<endl; // } // for(int k=0; k<n; k++) { // for(int j=0; j<n; j++) { // cout<<attack[k][j]; // } // cout<<endl; // } // cout<<endl; backtrack(reses, res, n, attack, index+1); res[index][i] = '.'; // 第index行,第i列放一个Q; attack = attack_temp; } } } void put_queen(int x, int y, vector<vector<int>>& attack) { attack[x][y] = 1;//自身不能放 int n = attack.size(); for(int i=0; i<n; i++) { attack[x][i] = 1;//竖着的不能放 attack[i][y] = 1;//横着的不能放 if(x-i>=0 && y-i>=0) attack[x-i][y-i] = 1;//左上的不能放 if(x+i<n && y+i<n) attack[x+i][y+i] = 1;//右下的不能放 if(x+i<n && y-i>=0) attack[x+i][y-i] = 1;//左下的不能放 if(x-i>=0 && y+i<n) attack[x-i][y+i] = 1;//右上的不能放 } } }; int main() { int n=4; vector<vector<int>> attack(n, vector<int>(n, 0)); //皇后攻击范围 vector<vector<string>> res = Solution().solveNQueens(n); vector<string> ress= res[0]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { cout<<ress[i][j]; } cout<<endl; } return 0; }
#include "wali/domains/binrel/ProgramBddContext.hpp" #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include <map> using namespace std; using namespace wali; using namespace wali::domains::binrel; int main(int argc, char ** argv) { bool dbg = false; long totalCombine = 5e2; long extendPerCombine = 5e2; if(argc < 2) srand(time(NULL)); else{ int seed; istringstream (argv[1]) >> seed; srand(seed); } ProgramBddContext * voc = new ProgramBddContext(); map<string, int > vars; vars["a"] = 2; vars["b"] = 2; vars["c"] = 2; vars["d"] = 2; vars["e"] = 2; vars["f"] = 2; vars["g"] = 2; vars["h"] = 2; voc->setIntVars(vars); sem_elem_tensor_t val = new BinRel(voc, bddfalse); val = val->tensor(val.get_ptr()); sem_elem_tensor_t id = new BinRel(voc, voc->Assign("a", voc->From("a"))); for(long i = 0; i < totalCombine; ++i){ sem_elem_tensor_t com = new BinRel(voc, voc->Assign("a", voc->From("a"))); com = com->tensor(com.get_ptr()); for(long j = 0; j < extendPerCombine; ++j){ unsigned r = ((unsigned) rand()) % 9 + 1; string s; switch(r){ case 1: s = "a"; break; case 2: s = "b"; break; case 3: s = "c"; break; case 4: s = "c"; break; case 5: s = "d"; break; case 6: s = "e"; break; case 7: s = "f"; break; case 8: s = "g"; break; case 9: s = "h"; break; } string ss = s; r = ((unsigned) rand()) % 9 + 1; switch(r){ case 1: s = "a"; break; case 2: s = "b"; break; case 3: s = "c"; break; case 4: s = "c"; break; case 5: s = "d"; break; case 6: s = "e"; break; case 7: s = "f"; break; case 8: s = "g"; break; case 9: s = "h"; break; } sem_elem_tensor_t ext = new BinRel(voc, voc->Assign(s.c_str(), voc->From(ss.c_str()))); r = ((unsigned) rand()) % 100; if(dbg) cout << "r: " << r << endl; if(r < 4) ext = ext->tensor(id.get_ptr()); else ext = id->tensor(ext.get_ptr()); com = dynamic_cast<SemElemTensor*>(com->extend(ext.get_ptr()).get_ptr()); if(dbg) cout << "Next extend" << endl; } val = dynamic_cast<SemElemTensor*>(val->combine(com.get_ptr()).get_ptr()); if(dbg) cout << "Next combine" << endl; } val = NULL; delete voc; cout << "Done!" << endl; }
#ifndef _MSG_0X36_BLOCKACTION_STC_H_ #define _MSG_0X36_BLOCKACTION_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class BlockAction : public BaseMessage { public: BlockAction(); BlockAction(int32_t _x, int16_t _y, int32_t _z, int8_t _byte1, int8_t _byte2, int16_t _blockId); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getX() const; int16_t getY() const; int32_t getZ() const; int8_t getByte1() const; int8_t getByte2() const; int16_t getBlockId() const; void setX(int32_t _val); void setY(int16_t _val); void setZ(int32_t _val); void setByte1(int8_t _val); void setByte2(int8_t _val); void setBlockId(int16_t _val); private: int32_t _pf_x; int16_t _pf_y; int32_t _pf_z; int8_t _pf_byte1; int8_t _pf_byte2; int16_t _pf_blockId; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X36_BLOCKACTION_STC_H_
#include "Mesh.h" Quad::Quad() { V00.x = 0.0; V00.y = 0.0; V01.x = 0.0; V01.y = 0.0; V10.x = 0.0; V10.y = 0.0; V11.x = 0.0; V11.y = 0.0; } Quad::Quad(const Quad &inQuad) { V00.x = inQuad.V00.x; V00.y = inQuad.V00.y; V01.x = inQuad.V01.x; V01.y = inQuad.V01.y; V10.x = inQuad.V10.x; V10.y = inQuad.V10.y; V11.x = inQuad.V11.x; V11.y = inQuad.V11.y; } Quad::Quad(Point2f &inV00, const Point2f &inV01, const Point2f &inV10, const Point2f &inV11) { V00.x = inV00.x; V00.y = inV00.y; V01.x = inV01.x; V01.y = inV01.y; V10.x = inV10.x; V10.y = inV10.y; V11.x = inV11.x; V11.y = inV11.y; } Quad::~Quad() { } void Quad::operator=(const Quad &inQuad) { V00.x = inQuad.V00.x; V00.y = inQuad.V00.y; V01.x = inQuad.V01.x; V01.y = inQuad.V01.y; V10.x = inQuad.V10.x; V10.y = inQuad.V10.y; V11.x = inQuad.V11.x; V11.y = inQuad.V11.y; } double Quad::getMinX() const { float minx = min(V00.x, V01.x); minx = min(minx, V10.x); minx = min(minx, V11.x); return 1.0*minx; } double Quad::getMaxX() const { float maxX = max(V00.x, V01.y); maxX = max(maxX, V10.x); maxX = max(maxX, V11.x); return 1.0*maxX; } double Quad::getMinY() const { float minY = min(V00.y, V01.y); minY = min(minY, V10.y); minY = min(minY, V11.y); return 1.0*minY; } double Quad::getMaxY() const { float maxY = max(V00.y, V01.y); maxY = max(maxY, V10.y); maxY = max(maxY, V11.y); return 1.0*maxY; } bool isPointInTriangular(const Point2f &pt, Point2f &V0, const Point2f &V1, const Point2f V2) { double lambda1 = ((V1.y - V2.y)*(pt.x - V2.x) + (V2.x - V1.x)*(pt.y - V2.y)) / ((V1.y - V2.y)*(V0.x - V2.x) + (V2.x - V1.x)*(V0.y - V2.y)); double lambda2 = ((V2.y - V0.y)*(pt.x - V2.x) + (V0.x - V2.x)*(pt.y - V2.y)) / ((V2.y - V0.y)*(V1.x - V2.x) + (V0.x - V2.x)*(V1.y - V2.y)); if (lambda1 >= 0.0&&lambda1 <= 1.0&&lambda2 >= 0.0&&lambda2 <= 1.0) { return true; } else { return false; } } Mesh::Mesh() { imgRows = 0; imgCols = 0; width = 0; height = 0; } Mesh::Mesh(const Mesh &inMesh) { imgRows = inMesh.imgRows; imgCols = inMesh.imgCols; width = inMesh.width; height = inMesh.height; xMat = cv::Mat::zeros(height, width, CV_64FC1); yMat = cv::Mat::zeros(height, width, CV_64FC1); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { setVertex(i, j, inMesh.getVertex(i, j)); } } } Mesh::Mesh(int rows, int cols) { imgRows = rows; imgCols = cols; width = 0; height = 0; } Mesh::Mesh(int rows, int cols, double quadWidth, double quadHeight) { imgRows = rows; imgCols = cols; buildMesh(quadWidth, quadHeight); this->quadWidth = quadWidth; this->quadHeight = quadHeight; } Mesh::~Mesh() { } //将一个点通过单应矩阵变换为另外一个坐标点 Point2f matMyPointCVMat(const Point2f &pt, const Mat &H) { Mat cvPt = Mat::zeros(3, 1, CV_64F); cvPt.at<double>(0, 0) = pt.x; cvPt.at<double>(1, 0) = pt.y; cvPt.at<double>(2, 0) = 1.0; Mat cvResult = H*cvPt; Point2f result; result.x = cvResult.at<double>(0, 0) / cvResult.at<double>(2, 0); result.y = cvResult.at<double>(1, 0) / cvResult.at<double>(2, 0); return result; } //将一个网格中的所有点通过单应矩阵变换 void Mesh::HomographyTransformation(const Mat &H) { for (int i = 0; i <height; i++) { for (int j = 0; j < width; j++) { Point2f pt = this->getVertex(i, j); Point2f ptTrans = matMyPointCVMat(pt, H); this->setVertex(i, j, ptTrans); } } } void Mesh::setVertex(int i, int j, const Point2f &pos) { xMat.at<double>(i, j) = pos.x; yMat.at<double>(i, j) = pos.y; } Quad Mesh::getQuad(int i, int j) const { Point2f V00; Point2f V01; Point2f V10; Point2f V11; V00 = getVertex(i - 1, j - 1);//网格左上角 V01 = getVertex(i - 1, j);//网格左上角 V10 = getVertex(i, j - 1);//网格右上角 V11 = getVertex(i, j);//网格右下角 Quad qd(V00, V01, V10, V11); return qd; } void Mesh::drawMesh(Mat &targetImg) { Mat temp = targetImg.clone(); Scalar color(255, 255, 255); int gap = 0; int lineWidth = 3; for (int i = 0; i <height; i++) { for (int j = 0; j <width; j++) { Point2f pUp = getVertex(i - 1, j); Point2f pLeft = getVertex(i, j - 1); Point2f pCur = getVertex(i, j); pUp.x += gap; pUp.y += gap; pLeft.x += gap; pLeft.y += gap; pCur.x += gap; pCur.y += gap; if (pUp.x > -9999.0 && pUp.y > -9999.0 && pCur.x > -9999.0 && pCur.y > -9999.0){ double dis = sqrt((pUp.x - pCur.x)*(pUp.x - pCur.x) + (pUp.y - pCur.y)*(pUp.y - pCur.y)); line(temp, cv::Point2f(pUp.x, pUp.y), cv::Point2f(pCur.x, pCur.y), color, lineWidth, CV_AA); } if (pLeft.x > -9999.0 && pLeft.y > -9999.0 && pCur.x > -9999.0 && pCur.y > -9999.0){ double dis = sqrt((pLeft.x - pCur.x)*(pLeft.x - pCur.x) + (pLeft.y - pCur.y)*(pLeft.y - pCur.y)); line(temp, cv::Point2f(pLeft.x, pLeft.y), cv::Point2f(pCur.x, pCur.y), color, lineWidth, CV_AA); } cv::circle(temp, cv::Point(pUp.x, pUp.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); cv::circle(temp, cv::Point(pLeft.x, pLeft.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); cv::circle(temp, cv::Point(pCur.x, pCur.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); } } for (int i = 1; i < height; i++) { cv::Point2f pLeft = getVertex(i, 0); cv::Point2f pLeftUp = getVertex(i - 1, 0); pLeftUp.x += gap; pLeftUp.y += gap; pLeft.x += gap; pLeft.y += gap; if (pLeft.x > -9999.0 && pLeft.y > -9999.0 && pLeftUp.x > -9999.0 && pLeftUp.y > -9999.0){ double dis = sqrt((pLeft.x - pLeftUp.x)*(pLeft.x - pLeftUp.x) + (pLeft.y - pLeftUp.y)*(pLeft.y - pLeftUp.y)); line(temp, cv::Point2f(pLeft.x, pLeft.y), cv::Point2f(pLeftUp.x, pLeftUp.y), color, lineWidth, CV_AA); } cv::circle(temp, cv::Point(pLeftUp.x, pLeftUp.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); cv::circle(temp, cv::Point(pLeft.x, pLeft.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); } for (int j = 1; j < width; j++) { cv::Point2f pLeftUp = getVertex(0, j - 1); cv::Point2f pUp = getVertex(0, j); pLeftUp.x += gap; pLeftUp.y += gap; pUp.x += gap; pUp.y += gap; if (pLeftUp.x > -9999.0 && pLeftUp.y > -9999.0 && pUp.x > -9999.0 && pUp.y > -9999.0){ double dis = sqrt((pLeftUp.x - pUp.x)*(pLeftUp.x - pUp.x) + (pLeftUp.y - pUp.y)*(pLeftUp.y - pUp.y)); line(temp, cv::Point2f(pLeftUp.x, pLeftUp.y), cv::Point2f(pUp.x, pUp.y), color, lineWidth, CV_AA); } cv::circle(temp, cv::Point(pUp.x, pUp.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); cv::circle(temp, cv::Point(pLeftUp.x, pLeftUp.y), lineWidth + 2, cv::Scalar(45, 57, 167), -1); } targetImg = (2.0 / 5 * targetImg + 3.0 / 5 * temp); } void meshWarpRemap(Mat &src, Mat dst, Mat &mapX, Mat mapY, Mesh &m1, Mesh &m2) { int height = src.size().height; int width = src.size().width; vector<Point2f> source(4); vector<Point2f> target(4); Mat H; for (int i = 1; i < m1.height; i++) { for (int j = 1; j < m1.width; i++) { Quad s = m1.getQuad(i, j); Quad t = m2.getQuad(i, j); source[0] = s.V00; source[1] = s.V01; source[2] = s.V10; source[3] = s.V11; target[0] = t.V00; target[1] = t.V01; target[2] = t.V10; target[3] = t.V11; H = findHomography(source, target, 0); for (int ii = source[0].y; ii < source[3].y; ii++) { for (int jj = source[0].x; jj < source[3].x; jj++) { double x = 1.0*jj; double y = 1.0*ii; //矩阵相乘, double X = H.at<double>(0, 0)*x + H.at<double>(0, 1)*y + H.at<double>(0, 2)*1.0; double Y = H.at<double>(1, 0)*x + H.at<double>(1, 1)*y + H.at<double>(1, 2)*1.0; double W = H.at<double>(2, 0)*x + H.at<double>(2, 1)*y + H.at<double>(2, 2)*1.0; W = W ? 1.0 / W : 0; mapX.at<float>(ii, jj) = X*W; mapY.at<float>(ii, jj) = Y*W; } } } } } void myQuickSort(vector<float> &arr, int left, int right) { int i = left, j = right; float tmp; float pivot = arr[(left + right) / 2]; while (i <= j) { while (arr[i]<pivot) i++; while (arr[j]>pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } if (left < j) myQuickSort(arr, left, j); if (i < right) myQuickSort(arr, i, right); } //构建网格 void Mesh::buildMesh(double quadWidth, double quadHeight) { vector<int> xSet; vector<int> ySet; for (int x = 0; imgCols - x > 0.5*quadWidth; x += quadWidth) { xSet.push_back(x); } //加上最后一列 xSet.push_back(imgCols - 1); for (int y = 0; imgRows - y>0.5*quadHeight; y += quadHeight) { ySet.push_back(y); } ySet.push_back(imgRows - 1); width = xSet.size();// height = ySet.size(); xMat.create(height, width, CV_64FC1); yMat.create(height, width, CV_64FC1); for (int y = 0; y <height; y++) { for (int x = 0; x <width; x++) { xMat.at<double>(y, x) = xSet[x]; yMat.at<double>(y, x) = ySet[y]; } } } Point2f Mesh::getVertex(int i, int j) const { double x; double y; x = xMat.at<double>(i, j); y = yMat.at<double>(i, j); return Point2f(x, y); } Mat Mesh::getXMat() { return xMat; } Mat Mesh::getYMat() { return yMat; }
// // Created by manout on 17-7-1. // #include "all_include.h" #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/opencv.hpp> #include <iostream> #define use_filter2D #define w 400 using std::cin; using std::cout; using std::endl; //显示一个图像 int show_img(const string& file_path) { cv::Mat img = cv::imread(file_path); if (img.empty()) return -1; cv::namedWindow(file_path, CV_WINDOW_AUTOSIZE); cv::imshow(file_path, img); while(cv::waitKey(1000) not_eq 27); return 0; } //将图像转换为灰度图显示 int grey_img(const string& file_path) { cv::Mat origin_img = cv::imread(file_path, cv::IMREAD_COLOR); if (origin_img.empty()) return -1; cv::Mat grey_img; string grey_img_title = "grey_img"; cv::namedWindow(file_path, cv::WINDOW_AUTOSIZE); cv::imshow(file_path, origin_img); cv::cvtColor(origin_img, grey_img, cv::COLOR_BGR2GRAY); cv::namedWindow(grey_img_title, CV_WINDOW_AUTOSIZE); cv::imshow(grey_img_title, grey_img); while(cv::waitKey(1000) not_eq 27); return 0; } int scan_img(const string& img_file) { cv::Mat img = cv::imread(img_file); assert(not img_file.empty()); assert(img.depth() == CV_8U); int channel = img.channels(); // divide = 10 的时候图像变化不明显,加大到100才有明显的变化,可能是原图像的清晰度就不高吧 int divide = 100; uchar table[256]; for(int i = 0; i < 256; ++i) { table[i] = static_cast<uchar> (divide * (i / divide)); } switch (channel) { case 1: for (cv::MatIterator_<uchar> it = img.begin<uchar>(); it not_eq img.end<uchar>(); ++it) { *it = table[*it]; } break; case 3: for (cv::MatIterator_<cv::Vec3b> it = img.begin<cv::Vec3b>(); it not_eq img.end<cv::Vec3b>(); ++it) { (*it)[0] = table[(*it)[0]] ; (*it)[1] = table[(*it)[1]]; (*it)[2] = table[(*it)[2]]; } break; } cv::namedWindow(img_file, cv::WINDOW_AUTOSIZE); cv::imshow(img_file, img); while(cv::waitKey(1000) not_eq 27); return 0; } //使用LUT函数转换一个矩阵 cv::Mat scan_img_LUT(const string& file_path) { cv::Mat imgfile = cv::imread(file_path); cv::Mat ret; assert(not imgfile.empty()); uchar table[256]; int divide = 100; for (int i = 0; i < 256; ++i) { table[i] = static_cast<uchar>( divide * (i / divide) ); } //一行,256列的行矩阵 cv::Mat lookuptable(1, 256, CV_8U); uchar* p = lookuptable.ptr(); for (int i = 0; i < 256; ++i, ++p) { *p = table[i]; } cv::LUT(imgfile, lookuptable, ret); return ret; } //图片的对比增强算法,就是要对每个像素点使用以下公式 // // I(i, j) = 5 * I(i, j) - [I(i - 1, j) + I(i + 1, j) + I(i, j - 1) + I(i, j + 1)] // cv::Mat sharpen(const cv::Mat& origin_img) { assert(origin_img.depth() == CV_8U); //只接受unchar图像 const int channels= origin_img.channels(); cv::Mat ret(origin_img.size(), origin_img.type()); #ifndef use_filter2D for (int i = 1; i < origin_img.rows - 1; ++i) { //cv::Mat::ptr(int i) 返回指向第i行的指针 const uchar* previous = origin_img.ptr(i - 1); const uchar* current = origin_img.ptr(i); const uchar* next = origin_img.ptr(i + 1); uchar * output = ret.ptr(i); for (int j = channels; j < channels * (origin_img.cols - 1); ++j, ++output) { //channels 为一个像素的通道数,当前通道加上channels即为下一个像素该通道 *output = static_cast<uchar> (5 * current[j] - current[j -channels] - current[j + channels] - previous[j] - next[j]); } } #endif #ifdef use_filter2D cv::Mat kernel; kernel = (cv::Mat_<uchar>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1 , 0); //奇怪,使用filter2D结果与之前并不相同,是核函数的原因吗? cv::filter2D(origin_img, ret, origin_img.depth(), kernel); #endif cv::Scalar sa(255, 255, 255); ret.row(0).setTo(sa); ret.row(ret.rows- 1).setTo(sa); ret.col(0).setTo(sa); ret.col(ret.cols - 1).setTo(sa); return ret; } //使用 cv::addWeighted()alpah融合两个图像,指定ROI区域只需获取原图像的一个矩形区域即可 void alpha_fusion(cv::Mat& img_1, cv::Mat& img_2) { //因为Mat不显式复制时并不复制数据体,所以只需获取图像的一个子矩形区域便可得到原图像的ROI cv::Mat src_roi (img_2, cv::Rect(100, 100, img_1.rows, img_1.cols)); cv::Mat ret; double alpha = 0.5; double beta = 0.5; cv::addWeighted(img_1, alpha, src_roi, beta, 0, src_roi); } //调整图像的亮度和对比度 //常用的像素点运算为如下公式 /* * G(x) = a * F(x) + b */ //其中 a 常被称为增益参数, b 常被成为偏置参数,同样可以表示成以下形式 /* * G(i, j) = a * F(i, j) + b * (i, j) 表示第 i 行,第 i 列 */ // alpha  表示增益参数,简单对比度控制。 // beta  表示偏置参数,简单亮度控制 void change_contrast_bright(cv::Mat& img, double alpha, int beta) { for (int i = 0; i < img.rows; ++i) { for (int j = 0; j < img.cols; ++j) { for (int k = 0; k < 3; ++k) { img.at<cv::Vec3b>(i, j)[k] = cv::saturate_cast<uchar>(alpha * img.at<cv::Vec3b>(i, j)[k] + beta); } } } } void MyEllipse(cv::Mat img, double angle) { int thickness = 2; int lineType = 8; cv::ellipse(img, cv::Point(w / 2, w /2),cv::Size(w / 4, w / 16), angle, 0 ,360, cv::Scalar(255, 0, 0), thickness, lineType); } void MyFilledCircle(cv::Mat img, cv::Point center) { //在图像的中心画一个半径为 w / 32,红色圆 cv::circle(img, center, w /32, cv::Scalar(0, 0, 255), cv::FILLED); } //多边形 void MyPolygon( cv::Mat img ) { int lineType = cv::LINE_8; cv::Point rook_points[1][20]; rook_points[0][0] = cv::Point(w / 4, 7 * w / 8); rook_points[0][1] = cv::Point(3 * w / 4, 7 * w / 8); rook_points[0][2] = cv::Point(3 * w / 4, 13 * w / 16); rook_points[0][3] = cv::Point(11 * w / 16, 13 * w / 16); rook_points[0][4] = cv::Point(19 * w / 32, 3 * w / 8); rook_points[0][5] = cv::Point(3 * w / 4, 3 * w / 8); rook_points[0][6] = cv::Point(3 * w / 4, w / 8); rook_points[0][7] = cv::Point(26 * w / 40, w / 8); rook_points[0][8] = cv::Point(26 * w / 40, w / 4); rook_points[0][9] = cv::Point(22 * w / 40, w / 4); rook_points[0][10] = cv::Point(22 * w / 40, w / 8); rook_points[0][11] = cv::Point(18 * w / 40, w / 8); rook_points[0][12] = cv::Point(18 * w / 40, w / 4); rook_points[0][13] = cv::Point(14 * w / 40, w / 4); rook_points[0][14] = cv::Point(14 * w / 40, w / 8); rook_points[0][15] = cv::Point(w / 4, w / 8); rook_points[0][16] = cv::Point(w / 4, 3 * w / 8); rook_points[0][17] = cv::Point(13 * w / 32, 3 * w / 8); rook_points[0][18] = cv::Point(5 * w / 16, 13 * w / 16); rook_points[0][19] = cv::Point(w / 4, 13 * w / 16); const cv::Point *ppt[1] = {rook_points[0]}; int npt[] = {20}; cv::fillPoly(img, ppt, npt, 1, cv::Scalar(255, 255, 255), lineType); } void MyLine(cv::Mat img, cv::Point start, cv::Point end) { int thickness = 2; int lineType = cv::LINE_8; cv::line(img, start, end, cv::Scalar(0, 0 ,0 ), thickness, lineType); } void show_atom() { string atom_window("Drawing 1: Atom"); cv::Mat atom_img = cv::Mat::zeros(w, w, CV_8UC3); MyEllipse(atom_img, 90); MyEllipse(atom_img, 0); MyEllipse(atom_img, 45); MyEllipse(atom_img, -45); MyFilledCircle(atom_img, cv::Point(w / 2, w / 2)); cv::namedWindow(atom_window, cv::WINDOW_AUTOSIZE); cv::imshow(atom_window, atom_img); } void show_rook() { string rook_window("Drawing 2: Rook"); cv::Mat rook_img = cv::Mat::zeros(w, w, CV_8UC3); MyPolygon(rook_img); cv::rectangle(rook_img, cv::Point(0, 7 * w / 8), cv::Point(w, w), cv::Scalar(0, 255, 255), cv::FILLED, cv::LINE_8); MyLine(rook_img, cv::Point(0, 15 * w / 16), cv::Point(w, 15 * w / 16)); MyLine(rook_img, cv::Point(w / 4, 7 * w /8), cv::Point(w / 4, w)); MyLine(rook_img, cv::Point(w / 2, 7 * w / 8), cv::Point(w / 2, w)); MyLine(rook_img, cv::Point(3 * w /4, 7 * w / 8), cv::Point(3 * w / 4, w)); cv::namedWindow(rook_window, cv::WINDOW_AUTOSIZE); cv::imshow(rook_window, rook_img); }
#include "stdafx.h" #include "FreqToken.h" FreqToken::FreqToken() : QsoTokenType("freq") { m_minSize = 5; // minimum number of characters when writing out as a string } FreqToken::~FreqToken() { } bool FreqToken::Parse(const string& token) { m_token = token; return true; }
// Created on: 1998-01-29 // Created by: Laurent BOURESCHE // Copyright (c) 1998-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 _BRepFilletAPI_LocalOperation_HeaderFile #define _BRepFilletAPI_LocalOperation_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BRepBuilderAPI_MakeShape.hxx> #include <Standard_Integer.hxx> #include <ChFiDS_SecHArray1.hxx> class TopoDS_Edge; class TopoDS_Vertex; //! Construction of fillets on the edges of a Shell. class BRepFilletAPI_LocalOperation : public BRepBuilderAPI_MakeShape { public: DEFINE_STANDARD_ALLOC //! Adds a contour in the builder (builds a //! contour of tangent edges). Standard_EXPORT virtual void Add (const TopoDS_Edge& E) = 0; //! Reset the contour of index IC, there is nomore //! information in the contour. Standard_EXPORT virtual void ResetContour (const Standard_Integer IC) = 0; //! Number of contours. Standard_EXPORT virtual Standard_Integer NbContours() const = 0; //! Returns the index of the contour containing the edge //! E, returns 0 if E doesn't belong to any contour. Standard_EXPORT virtual Standard_Integer Contour (const TopoDS_Edge& E) const = 0; //! Number of Edges in the contour I. Standard_EXPORT virtual Standard_Integer NbEdges (const Standard_Integer I) const = 0; //! Returns the Edge J in the contour I. Standard_EXPORT virtual const TopoDS_Edge& Edge (const Standard_Integer I, const Standard_Integer J) const = 0; //! remove the contour containing the Edge E. Standard_EXPORT virtual void Remove (const TopoDS_Edge& E) = 0; //! returns the length the contour of index IC. Standard_EXPORT virtual Standard_Real Length (const Standard_Integer IC) const = 0; //! Returns the first Vertex of the contour of index IC. Standard_EXPORT virtual TopoDS_Vertex FirstVertex (const Standard_Integer IC) const = 0; //! Returns the last Vertex of the contour of index IC. Standard_EXPORT virtual TopoDS_Vertex LastVertex (const Standard_Integer IC) const = 0; //! returns the abscissa of the vertex V on //! the contour of index IC. Standard_EXPORT virtual Standard_Real Abscissa (const Standard_Integer IC, const TopoDS_Vertex& V) const = 0; //! returns the relative abscissa([0.,1.]) of the //! vertex V on the contour of index IC. Standard_EXPORT virtual Standard_Real RelativeAbscissa (const Standard_Integer IC, const TopoDS_Vertex& V) const = 0; //! returns true if the contour of index IC is closed //! an tangent. Standard_EXPORT virtual Standard_Boolean ClosedAndTangent (const Standard_Integer IC) const = 0; //! returns true if the contour of index IC is closed Standard_EXPORT virtual Standard_Boolean Closed (const Standard_Integer IC) const = 0; //! Reset all the fields updated by Build operation and //! leave the algorithm in the same state than before //! build call. It allows contours and radius //! modifications to build the result another time. Standard_EXPORT virtual void Reset() = 0; Standard_EXPORT virtual void Simulate (const Standard_Integer IC) = 0; Standard_EXPORT virtual Standard_Integer NbSurf (const Standard_Integer IC) const = 0; Standard_EXPORT virtual Handle(ChFiDS_SecHArray1) Sect (const Standard_Integer IC, const Standard_Integer IS) const = 0; protected: private: }; #endif // _BRepFilletAPI_LocalOperation_HeaderFile
//glrenderer.cpp //Fleshes out low-level rendering functions defined in renderer.hpp //Created by Lewis Hosie //16-11-11 //Dependencies: GL (obviously), GLEW #include "glrenderer.hpp" #include "fileio.hpp" #ifdef E_INCLUDE_GLRENDERER #include <sstream> glrenderer::glrenderer(const realwindow& thewin) : thewin(thewin){ glewInit(); thevars.loadlistfromfile("config/glrenderer.ini"); //Gah, my video card doesn't have ARB_COLOR_BUFFER_FLOAT. :/ /*glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB,GL_FALSE); glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB,GL_FALSE); glClampColorARB(GL_CLAMP_READ_COLOR_ARB,GL_FALSE);*/ //Create the displacement map glGenTextures(1,&displacementmap); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB,displacementmap); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB,GL_TEXTURE_MAG_FILTER,GL_NEAREST); //Load the blank data in char *img; img = new char[thewin.thevars.getintvec2("windowsize",640,480).x*thewin.thevars.getintvec2("windowsize",640,480).y*3]; memset(img,128,thewin.thevars.getintvec2("windowsize",640,480).x*thewin.thevars.getintvec2("windowsize",640,480).y*3); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,0,GL_RGB,thewin.thevars.getintvec2("windowsize",640,480).x,thewin.thevars.getintvec2("windowsize",640,480).y,0,GL_RGB,GL_UNSIGNED_BYTE,img); delete[] img; glDisable(GL_TEXTURE_RECTANGLE_ARB); } void glrenderer::loadaccum(){ glAccum(GL_LOAD,1.0f); } void glrenderer::accum(){ glAccum(GL_ACCUM,1.0f); } void glrenderer::returnaccum(){ glAccum(GL_RETURN,1.0f); } void glrenderer::resetmatrix(){ glLoadIdentity(); } void glrenderer::pushmatrix(){ glPushMatrix(); } void glrenderer::popmatrix(){ glPopMatrix(); } void glrenderer::clearscreen(sreal r, sreal g, sreal b){ glClearColor(r, g, b, 0.0); glClear(GL_COLOR_BUFFER_BIT); } void glrenderer::cleardepth(){ glClear(GL_DEPTH_BUFFER_BIT); } void glrenderer::clearaccum(){ glClear(GL_ACCUM_BUFFER_BIT); } void glrenderer::orthoview(int x, int y, int width, int height){ glViewport(x,y,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,width,height,0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Depth range in ortho mode is 0.0-1.0 } void glrenderer::perspectiveview(const realwindow &thewin, sreal dnear, sreal dfar, sreal fov){ intvec2 winsize = thewin.thevars.getintvec2("windowsize",640,480); glViewport(0,0,winsize.x,winsize.y); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov,640.0f/480.0f,dnear,dfar); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glScalef(1.0f,1.0f,1.0f); //SCREW YOU OPENGL, negative is up in this program. glEnable(GL_CULL_FACE); } void checkforerrors(GLuint value, std::string thefile, GLuint theprogram){ if(value != GL_TRUE){ int mlen; char thelog[2048]; std::cout << "Error! Results for shader program " << thefile << std::endl; glGetInfoLogARB(theprogram, 2048, &mlen, thelog); std::cout << thelog << std::endl; //FIXME: Throw some exception here. } } void glrenderer::disableshaders(){ glUseProgramObjectARB(0); currentshader=0; } void glrenderer::endshaderpass(){ } void glrenderer::loadshader(std::string thefile, bool shadowdependent){ char *verttext, *fragtext; std::string dlevel; if(shadowdependent) dlevel= thevars.getstring("shadowtype","hard")=="soft" ? "softshadow/" : "hardshadow/"; else dlevel=""; std::ostringstream thevert; thevert << "glshaders/" << dlevel << thefile << ".vert"; std::ostringstream thefrag; thefrag << "glshaders/" << dlevel << thefile << ".frag"; verttext = textFileRead((char*)thevert.str().c_str()); fragtext = textFileRead((char*)thefrag.str().c_str()); int vertlen = ((int)strlen(verttext)); int fraglen = ((int)strlen(fragtext)); unsigned int fraghandle = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); unsigned int verthandle = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); unsigned int theprogram = 0; glShaderSourceARB(verthandle, 1, ((const char**)&verttext),&vertlen); glCompileShaderARB(verthandle); free(verttext); glShaderSourceARB(fraghandle, 1, ((const char**)&fragtext),&fraglen); glCompileShaderARB(fraghandle); free(fragtext); theprogram = glCreateProgramObjectARB(); glAttachObjectARB(theprogram,fraghandle); glAttachObjectARB(theprogram,verthandle); glLinkProgramARB(theprogram); int value; glGetObjectParameterivARB(theprogram, GL_OBJECT_LINK_STATUS_ARB, &value); checkforerrors(value, thefile, theprogram); glGetObjectParameterivARB(verthandle, GL_OBJECT_COMPILE_STATUS_ARB, &value); checkforerrors(value, thevert.str(), verthandle); glGetObjectParameterivARB(fraghandle, GL_OBJECT_COMPILE_STATUS_ARB, &value); checkforerrors(value, thefrag.str(), fraghandle); theshaders[thefile] = theprogram; selectshader(thefile); } fvec3 glrenderer::toeyespace(fvec2 position){ fvec3 in(position.x, 0.0f, position.y); return toeyespace(in); } fvec3 glrenderer::toeyespace(float x, float y, float z){ fvec3 in(x,y,z); return toeyespace(in); } fvec3 glrenderer::toeyespace(fvec3 position){ sreal modelview[16]; fvec3 output; glGetFloatv(GL_MODELVIEW_MATRIX,modelview); //Multiply the vertex by the modelview matrix output.x=modelview[0]*position.x+modelview[4]*position.y+modelview[8]*position.z+modelview[12]*1.0f; output.y=modelview[1]*position.x+modelview[5]*position.y+modelview[9]*position.z+modelview[13]*1.0f; output.z=modelview[2]*position.x+modelview[6]*position.y+modelview[10]*position.z+modelview[14]*1.0f; return output; } void glrenderer::selectshader(std::string theshader){ glUseProgramObjectARB(theshaders[theshader]); currentshader=theshaders[theshader]; } void glrenderer::passcurrentshader(std::string varname, sreal value){ glUniform1f(glGetUniformLocation(currentshader,varname.c_str()),value); } void glrenderer::passcurrentshader(std::string varname, int value){ glUniform1i(glGetUniformLocation(currentshader,varname.c_str()),value); } void glrenderer::passcurrentshader(std::string varname, fvec3 value){ glUniform3f(glGetUniformLocation(currentshader,varname.c_str()),value.x, value.y, value.z); } void glrenderer::matrixtranslate(float x, float y, float z){ glTranslatef(x,y,z); } void glrenderer::matrixscale(float x, float y, float z){ glScalef(x,y,z); } void glrenderer::matrixrotate(float angle, float x, float y, float z){ glRotatef(angle, x,y,z); } void glrenderer::enableblending(euint32 mode){ glEnable(GL_BLEND); if(mode==blendmode_normal) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(mode==blendmode_multiply) glBlendFunc(GL_DST_COLOR, GL_ZERO); if(mode==blendmode_add) glBlendFunc(GL_SRC_ALPHA, GL_ONE); } void glrenderer::disableblending(){ glDisable(GL_BLEND); } const vertexbuffer& glrenderer::buildvertexbuffer(fvec3 *thevecs, euint32 numvecs, tripoly *theindices, euint32 numindices, fvec3 *thenorms, euint32 numnorms){ glvertexbuffer *m = new glvertexbuffer(); m->indexcount=numindices; m->vertexcount=numindices; m->valid=true; glGenBuffersARB(1, &m->vertices); glBindBufferARB(GL_ARRAY_BUFFER_ARB, m->vertices); glBufferDataARB(GL_ARRAY_BUFFER_ARB, numvecs*sizeof(fvec3), thevecs, GL_STATIC_DRAW_ARB); glGenBuffersARB(1, &m->normals); glBindBufferARB(GL_ARRAY_BUFFER_ARB, m->normals); glBufferDataARB(GL_ARRAY_BUFFER_ARB, numvecs*sizeof(fvec3), thenorms, GL_STATIC_DRAW_ARB); glGenBuffersARB(1, &m->indices); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m->indices); glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numindices*sizeof(tripoly), theindices, GL_STATIC_DRAW_ARB); thevertexbuffers.push_back(reinterpret_cast<vertexbuffer*>(m)); return (**thevertexbuffers.rbegin()); } const vertexbuffer& glrenderer::buildinvalidvertexbuffer(){ glvertexbuffer *m = new glvertexbuffer(); m->valid=false; thevertexbuffers.push_back(reinterpret_cast<vertexbuffer*>(m)); return (**thevertexbuffers.rbegin()); } void glvertexbuffer::draw() const{ if(!valid) return; glEnableClientState(GL_VERTEX_ARRAY); glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertices); glVertexPointer(3, GL_FLOAT, 0, 0); glEnableClientState(GL_NORMAL_ARRAY); glBindBufferARB(GL_ARRAY_BUFFER_ARB, normals); glNormalPointer(GL_FLOAT, 0, 0); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indices); glDrawElements(GL_TRIANGLES, indexcount*3, GL_UNSIGNED_SHORT, 0); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } char* glrenderer::getbuffer(){ return NULL; } void glrenderer::drawunitsquare(){ glVertexAttrib3f(glGetAttribLocation(currentshader,"tangent"), -1.0f,0.0f,0.0f); glNormal3f(0.0f,-1.0f,0.0f); glColor3f(1.0f,1.0f,1.0f); glBegin(GL_QUADS); glTexCoord2f(0.0f,1.0f); glVertex3f(-0.5f,0.0f,0.5f); glTexCoord2f(1.0f,1.0f); glVertex3f(0.5f,0.0f,0.5f); glTexCoord2f(1.0f,0.0f); glVertex3f(0.5f,0.0f,-0.5f); glTexCoord2f(0.0f,0.0f); glVertex3f(-0.5f,0.0f,-0.5f); glEnd(); } euint32 glrenderer::loadtexture(texture& thetexture){ GLuint textureid; glGenTextures(1,&textureid); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,textureid); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, thetexture.size, thetexture.size, GL_RGBA, GL_UNSIGNED_BYTE, thetexture.thedata); return textureid; } void glrenderer::beginscene(){ } void glrenderer::endscene(){ } void glrenderer::selecttexunit(euint32 theunit){ switch(theunit){ case 0: glActiveTextureARB(GL_TEXTURE0_ARB); break; case 1: glActiveTextureARB(GL_TEXTURE1_ARB); break; case 2: glActiveTextureARB(GL_TEXTURE2_ARB); break; case 3: glActiveTextureARB(GL_TEXTURE3_ARB); break; } } void glrenderer::selecttexture(euint32 thetexture){ glDisable(GL_TEXTURE_RECTANGLE_ARB); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,thetexture); } void glrenderer::selectdisplacementmap(){ glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB,displacementmap); } void glrenderer::disabletextures(){ glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_RECTANGLE_ARB); } void glrenderer::copyscreentodisplacementmap(){ glBindTexture(GL_TEXTURE_RECTANGLE_ARB,displacementmap); glCopyTexImage2D(GL_TEXTURE_RECTANGLE_ARB,0,GL_RGB,0,0,thewin.thevars.getintvec2("windowsize",640,480).x,thewin.thevars.getintvec2("windowsize",680,480).y,0); } #endif
#include <iostream> using namespace std; /* compiles == true */ /* this thing prints array ints in reverse order #interviewsuccess */ int figure_out_if_i_am_good_enough_to_program() { int yes_or_no; cin >> yes_or_no; return yes_or_no; } void fight_imposters_syndrome_and_just_keep_going(int the_pressure_is_real[], int i_think_i_can_make_it) { for (int i_am_winning = 0; i_am_winning < i_think_i_can_make_it; i_am_winning++) { cin >> the_pressure_is_real[i_am_winning]; } } void keep_it_up_through_interviewing_and_getting_a_job(int strength[], int endurance) { for (int i_am_almost_there = 0; i_am_almost_there < endurance; i_am_almost_there++) { cout << strength[endurance - i_am_almost_there - 1]; if (i_am_almost_there < endurance - 1) { cout << " "; } } } int main() { int my_first_step; int remember_and_evaluate_everything[1000]; /* is 1000 big enough?? */ my_first_step = figure_out_if_i_am_good_enough_to_program(); fight_imposters_syndrome_and_just_keep_going(remember_and_evaluate_everything, my_first_step); keep_it_up_through_interviewing_and_getting_a_job(remember_and_evaluate_everything, my_first_step); return NULL; } /* success == i passed all the sample test cases */
#pragma once #include "../Indicator/Indicator.h" #include "Serializable/Object/SerializableObject.h" #include "Tree.h" class NamedValue; class IndicatorGroup : public SerializableObject { public: // :: Lifecycle :: virtual ~IndicatorGroup() noexcept = default; // :: Serializable :: virtual QJsonObject toJson() const override; virtual void initWithJsonObject(const QJsonObject &json) override; // :: Accessors :: QString getName() const; void setName(const QString &name); QList<Indicator> getIndicators() const; void setIndicators(const QList<Indicator> &indicators); Tree::NodePtr<NamedValue> toTreeNodePtr(const Tree::NodePtr<NamedValue> &parent) const; private: Tree::NodePtrs<NamedValue> indicatorsToTreeNodePtrs(const Tree::NodePtr<NamedValue> &parent) const; QString m_name; QList<Indicator> m_indicators; };
// // Created by manout on 18-2-25. // #include <tar.h> #include <algorithm> #include <iostream> __always_inline int equation(int x, int y, int z) { return x * x + y * y + z * z; } __always_inline int min(int x, int y, int z) { return std::min(std::min(x, y), std::min(y, z)); } int solve_equation() { for (int x = 0; x < 1000; ++x) { for (int y = 0; y < 1000; ++y) { for (int z = 0; z < 1000; ++z) { if (equation(x, y, z) == 1000) { return min(x, y, z); } } } } }
#ifndef int_view_h #define int_view_h #include <chuffed/core/sat-types.h> #include <chuffed/core/sat.h> #include <chuffed/vars/int-var.h> #include <cassert> // y = (-1)a*x + b // affine: type = 1*minus + 2*scale + 4*offset template <int type = 0> class IntView { public: IntVar* var; int a; int b; IntView(IntVar* v = nullptr, int _a = 1, int _b = 0) : var(v), a(_a), b(_b) {} template <int type2> IntView(const IntView<type2>& o) : var(o.var), a(o.a), b(o.b) {} void attach(Propagator* p, int pos, int eflags) const { var->attach(p, pos, getEvent(eflags)); } int getType() { int t = 0; if (a < 0) { a = -a; t |= 1; } if (a > 1) { t |= 2; } if (b != 0) { t |= 4; } return t; } IntVar* getVar() const { return var; } int getEvent(int e) const { return (type & 1) != 0 ? (e & 9) + ((e & 2) << 1) + ((e & 4) >> 1) : e; } bool isFixed() const { return var->isFixed(); } int64_t getMin() const { int64_t v = (type & 1) != 0 ? -var->getMax() : var->getMin(); if ((type & 2) != 0) { v *= a; } if ((type & 4) != 0) { v += b; } return v; } int64_t getMax() const { int64_t v = (type & 1) != 0 ? -var->getMin() : var->getMax(); if ((type & 2) != 0) { v *= a; } if ((type & 4) != 0) { v += b; } return v; } int64_t getVal() const { int64_t v = (type & 1) != 0 ? -var->getVal() : var->getVal(); if ((type & 2) != 0) { v *= a; } if ((type & 4) != 0) { v += b; } return v; } int64_t getShadowVal() const { int64_t v = (type & 1) != 0 ? -var->getShadowVal() : var->getShadowVal(); if ((type & 2) != 0) { v *= a; } if ((type & 4) != 0) { v += b; } return v; } bool indomain(int64_t v) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { if ((v % a) != 0) { return false; } v = v / a; } if ((type & 1) != 0) { v = -v; } return var->indomain(v); } class iterator { const IntView* view; IntVar::iterator forward; public: iterator() {} iterator(const IntView* _view, IntVar::iterator _forward) : view(_view), forward(_forward) {} int operator*() const { int v; if ((type & 1) != 0) { IntVar::iterator temp = forward; v = -*--temp; } else { v = *forward; } if ((type & 2) != 0) { v *= view->a; } if ((type & 4) != 0) { v += view->b; } return v; } iterator& operator++() { if ((type & 1) != 0) { --forward; } else { ++forward; } return *this; } iterator operator++(int dummy) { iterator temp = *this; ++*this; return temp; } iterator& operator--() { if ((type & 1) != 0) { ++forward; } else { --forward; } return *this; } iterator operator--(int dummy) { iterator temp = *this; --*this; return temp; } bool operator==(const iterator& rhs) const { assert(view == rhs.view); return (forward == rhs.forward); } bool operator!=(const iterator& rhs) const { assert(view == rhs.view); return (forward != rhs.forward); } }; typedef iterator const_iterator; iterator begin() const { return iterator(this, (type & 1) != 0 ? var->end() : var->begin()); } iterator end() const { return iterator(this, (type & 1) != 0 ? var->begin() : var->end()); } class reverse_iterator { iterator forward; public: reverse_iterator() {} reverse_iterator(iterator _forward) : forward(_forward) {} int operator*() const { iterator temp = forward; return *--temp; } reverse_iterator& operator++() { --forward; return *this; } reverse_iterator operator++(int dummy) { reverse_iterator temp = *this; ++*this; return temp; } reverse_iterator& operator--() { ++forward; return *this; } reverse_iterator operator--(int dummy) { reverse_iterator temp = *this; --*this; return temp; } iterator base() const { return forward; } bool operator==(const reverse_iterator& rhs) const { return (forward == rhs.forward); } bool operator!=(const reverse_iterator& rhs) const { return (forward != rhs.forward); } }; typedef reverse_iterator const_reverse_iterator; reverse_iterator rbegin() const { return reverse_iterator(end()); } reverse_iterator rend() const { return reverse_iterator(begin()); } int size() const { return var->size(); } bool setMinNotR(int64_t m) const { return m > getMin(); } bool setMaxNotR(int64_t m) const { return m < getMax(); } bool setValNotR(int64_t v) const { return !isFixed() || v != getVal(); } bool remValNotR(int64_t v) const { return indomain(v); } Lit getMinLit() const { return (type & 1) != 0 ? var->getMaxLit() : var->getMinLit(); } Lit getMaxLit() const { return (type & 1) != 0 ? var->getMinLit() : var->getMaxLit(); } Lit getValLit() const { return var->getValLit(); } Lit getFMinLit(int64_t v) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { v = v / a - static_cast<long long>(v % a < 0); } if ((type & 1) != 0) { return var->getFMaxLit(-v); } return var->getFMinLit(v); } Lit getFMaxLit(int64_t v) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { v = v / a + static_cast<long long>(v % a > 0); } if ((type & 1) != 0) { return var->getFMinLit(-v); } return var->getFMaxLit(v); } // y = 2*x // [y <= 3] = [x <= 1] // [y <= -5] = [x <= -3] // y = -2*x // [y <= 3] = [x >= -1] = ![x <= -2] // [y <= -5] = [x >= 3] = ![x <= 2] Lit getLit(int64_t v, int t) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { int k = v % a; v = v / a; if (k != 0) { if (t == 0) { NEVER; } if (t == 1) { return lit_False; } if (t == 2 && k > 0) { v++; } if (t == 3 && k < 0) { v--; } } } if ((type & 1) != 0) { v = -v; if (t >= 2) { assert(5 - t >= 0 && 5 - t <= 3); return var->getLit(v, static_cast<LitRel>(5 - t)); } } return var->getLit(v, static_cast<LitRel>(t)); } // Set ![y <= m-1] // y = 2*x // [y >= 4] = ![y <= 3] = ![x <= 1] = [x >= 2] // [y >= 3] = ![y <= 2] = ![x <= 1] = [x >= 2] // y = -2*x // [y >= 4] = ![y <= 3] = ![x >= -1] = [x <= -2] // [y >= 3] = ![y <= 2] = ![x >= -1] = [x <= -2] // [y >= -4] = ![y <= -5] = ![x >= 3] = [x <= 2] bool setMin(int64_t v, Reason r = nullptr, bool channel = true) const { v--; if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { v = v / a - static_cast<long long>(v % a < 0); } if ((type & 1) != 0) { return var->setMax(-v - 1, r, channel); } return var->setMin(v + 1, r, channel); } // Set [y <= m] // y = 2*x // [y <= 4] = [x <= 2] // [y <= 3] = [x <= 1] // y = -2*x // [y <= 3] = [x >= -1] // [y <= -4] = [x >= 2] // [y <= -5] = [x >= 3] bool setMax(int64_t v, Reason r = nullptr, bool channel = true) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { v = v / a - static_cast<long long>(v % a < 0); } if ((type & 1) != 0) { return var->setMin(-v, r, channel); } return var->setMax(v, r, channel); } bool setVal(int64_t v, Reason r = nullptr, bool channel = true) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { if ((v % a) != 0) { sat.cEnqueue(lit_False, r); return false; } v = v / a; } if ((type & 1) != 0) { v = -v; } return var->setVal(v, r, channel); } bool remVal(int64_t v, Reason r = nullptr, bool channel = true) const { if ((type & 4) != 0) { v -= b; } if ((type & 2) != 0) { if ((v % a) != 0) { return true; } v = v / a; } if ((type & 1) != 0) { v = -v; } return var->remVal(v, r, channel); } Lit operator=(int val) const { return getLit(val, LR_EQ); } Lit operator!=(int val) const { return getLit(val, LR_NE); } }; const IntView<> iv_null; #endif
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "filter_setup.hpp" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "mock_filter.hpp" namespace { const int kExpectedChunkId = 1; const int kExpectedPosition = 14; const int kInputStreamId = 0; const int kOutputStreamId = 1; const std::vector<int> capacity = {8, 1}; using orkhestrafs::dbmstodspi::FilterSetup; using orkhestrafs::dbmstodspi::module_config_values::FilterCompareFunctions; using orkhestrafs::dbmstodspi::module_config_values::LiteralTypes; const std::vector<std::vector<int>> kFilterConfigData{ {1, 14, 1}, {0}, {12000}, {1}, {0}}; TEST(FilterSetupTest, FilterStreamsSetting) { MockFilter mock_filter; EXPECT_CALL(mock_filter, FilterSetStreamIDs(kInputStreamId, kOutputStreamId, kOutputStreamId)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } TEST(FilterSetupTest, FilterModesSetting) { bool expected_request_on_invalid_if_last = true; bool expected_forward_invalid_record_first_chunk = false; bool expected_forward_full_invalid_records = false; bool expected_first_module_in_resource_elastic_chain = true; bool expected_last_module_in_resource_elastic_chain = true; MockFilter mock_filter; EXPECT_CALL(mock_filter, FilterSetMode(expected_request_on_invalid_if_last, expected_forward_invalid_record_first_chunk, expected_forward_full_invalid_records, expected_first_module_in_resource_elastic_chain, expected_last_module_in_resource_elastic_chain)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } TEST(FilterSetupTest, CompareTypesSetting) { MockFilter mock_filter; EXPECT_CALL(mock_filter, FilterSetCompareTypes(kExpectedChunkId, kExpectedPosition, FilterCompareFunctions::kLessThan32Bit, testing::_, testing::_, testing::_)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } TEST(FilterSetupTest, ReferenceValuesSetting) { int expected_compare_reference_value = 12000; int expected_compare_unit_index = 0; MockFilter mock_filter; EXPECT_CALL(mock_filter, FilterSetCompareReferenceValue( kExpectedChunkId, kExpectedPosition, expected_compare_unit_index, expected_compare_reference_value)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } TEST(FilterSetupTest, DNFClauseSetting) { int expected_compare_unit_index = 0; int expected_dnf_clause_id = 0; MockFilter mock_filter; EXPECT_CALL(mock_filter, FilterSetDNFClauseLiteral(expected_dnf_clause_id, expected_compare_unit_index, kExpectedChunkId, kExpectedPosition, LiteralTypes::kLiteralPositive)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } TEST(FilterSetupTest, CorrectLargeFilterCalled) { int expected_datapath_width = 16; MockFilter mock_filter; EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_1CMP_8DNF(testing::_)) .Times(0); EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_2CMP_16DNF(testing::_)) .Times(0); EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_4CMP_32DNF( expected_datapath_width)) .Times(1); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, {32, 4}); } TEST(FilterSetupTest, CorrectSmallFilterCalled) { int expected_datapath_width = 16; MockFilter mock_filter; EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_1CMP_8DNF(expected_datapath_width)) .Times(1); EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_2CMP_16DNF(testing::_)) .Times(0); EXPECT_CALL(mock_filter, WriteDNFClauseLiteralsToFilter_4CMP_32DNF(testing::_)) .Times(0); FilterSetup::SetupFilterModule(mock_filter, kInputStreamId, kOutputStreamId, kFilterConfigData, capacity); } } // namespace
/************************************************************************/ /* File name : BkGnuPGDef.h */ /************************************************************************/ /* Contents : Becky! GNU Privacy Guard プラグイン 共通定義 */ /* */ /* Auther : Yasuhiro ARAKAWA Version 0.00 2000.09.12 */ /* Version 0.10 2000.09.27 */ /* Version 0.20 2000.10.02 */ /* Version 0.30 2000.10.06 */ /* Version 1.0.0 2000.11.08 */ /************************************************************************/ #ifndef _BKGNUPGDEF_H_ #define _BKGNUPGDEF_H_ /**** Incude Files ****/ #define WIN32_LEAN_AND_MEAN // Windows ヘッダーから殆ど使用されないスタッフを除外します #include <windows.h> #include "resource.h" #include <string> #include <vector> /**** Global Macro ****/ #define WM_SET_TRANSFER_SAFE (WM_USER+300) // Makes compose window to encode text in transfer safe form. /**** Typedef ****/ /**** External Declarelation ****/ /**** Prototyping ****/ //Common.cpp extern void ErrorMessage(HWND hWnd, UINT uID); //エラーメッセージを表示する extern void FatalErrorMessage(HWND hWnd, const char* fileName, int lineno, const char* pMsg=NULL); //致命的エラーメッセージを表示する extern std::string& GetLegalFileName(const char* name, std::string& fileName); //ファイル名として利用可能な名前に変換する extern char* FileToString(const std::string& fileName); //テキストファイル内容を文字列情報としてメモリにロードする extern void GetNameAndAddr(const char* src, std::string& name, std::string& email); //「name <email>」形式の文字列を要素に分解する extern bool IsFileExist(const std::string& path); //ファイルの有無を問いあわせる extern void RemoveFiles(const std::string& path); //ファイル削除 (ワイルドカード有効) extern std::string& TrimSpace(std::string& element); //前後の空白文字を取り除く #endif // _BKGNUPGDEF_H_ /* Copyright (C) Yasuhiro ARAKAWA **************************************/
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string s; cin>>s; int n=s.length(); stack<int> s1; for(int i=0;i<=n;i++) { s1.push(i+1); if(i==n || s[i]=='I') { while(!s1.empty()) { cout<<s1.top(); s1.pop(); } } } cout<<endl; } return 0; }
#ifndef HEADER_CURL_CONNCACHE_H #define HEADER_CURL_CONNCACHE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2012 - 2014, Linus Nielsen Feltzing, <linus@haxx.se> * * 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. * ***************************************************************************/ namespace youmecommon { struct conncache { struct curl_hash *hash; size_t num_connections; long next_connection_id; struct timeval last_cleanup; }; struct conncache *Curl_conncache_init(int size); void Curl_conncache_destroy(struct conncache *connc); /* return the correct bundle, to a host or a proxy */ struct connectbundle *Curl_conncache_find_bundle(struct connectdata *conn, struct conncache *connc); CURLcode Curl_conncache_add_conn(struct conncache *connc, struct connectdata *conn); void Curl_conncache_remove_conn(struct conncache *connc, struct connectdata *conn); void Curl_conncache_foreach(struct conncache *connc, void *param, int(*func)(struct connectdata *conn, void *param)); struct connectdata * Curl_conncache_find_first_connection(struct conncache *connc); void Curl_conncache_print(struct conncache *connc); } #endif /* HEADER_CURL_CONNCACHE_H */
#ifndef SOCKS6MSG_EXCEPTION_HH #define SOCKS6MSG_EXCEPTION_HH #include <stdint.h> #include <stdexcept> namespace S6M { class BadVersionException: public std::runtime_error { uint8_t version; public: BadVersionException(uint8_t version) : runtime_error("Unsupported protocol version"), version(version) {} uint8_t getVersion() const { return version; } }; class EndOfBufferException: public std::length_error { public: EndOfBufferException() : length_error("End of buffer") {} }; class BadAddressTypeException: public std::invalid_argument { public: BadAddressTypeException() : invalid_argument("Bad address type") {} }; } #endif // SOCKS6MSG_EXCEPTION_HH
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef LINK_MANAGER_DIALOG_H #define LINK_MANAGER_DIALOG_H #include "adjunct/quick_toolkit/widgets/Dialog.h" class OpLinksView; /*********************************************************************************** ** ** LinkManagerDialog ** ***********************************************************************************/ class LinkManagerDialog : public Dialog { public: LinkManagerDialog() : m_links_view(NULL) {}; virtual ~LinkManagerDialog(); DialogType GetDialogType() {return TYPE_CLOSE;} Type GetType() {return DIALOG_TYPE_LINK_MANAGER;} const char* GetWindowName() {return "Link Manager Dialog";} BOOL GetModality() {return FALSE;} const char* GetHelpAnchor() {return "panels.html#links";} virtual void OnInit(); virtual BOOL OnInputAction(OpInputAction* action); virtual void OnClick(OpWidget *widget, UINT32 id = 0); private: OpLinksView* m_links_view; }; #endif //LINK_MANAGER_DIALOG_H
#include "dirgraph.h" using namespace std; class DirectedDFS { private: vector<bool> marked; private: void dfs(Digraph &G,int v) { marked[v] = true; list<int> *l = G.adj_vertex(v); for(int w : *l) { if(! marked[w]) dfs(G,w); } } public: DirectedDFS(Digraph &G,int s):marked(G.vertex()) { dfs(G,s); } DirectedDFS(Digraph &G,vector<int> &sources):marked(G.vertex()) { for(int s:sources) { if(!marked[s]) dfs(G,s); } } bool is_marked(int v) { return marked[v]; } };
#include <string> #include <iostream> using namespace std; bool IsPalindrome(const string& s) { string s_rev(s.rbegin(),s.rend()); return s == s_rev; } int main() { do { cout << "Enter a string: <q to quit> "; string s; getline(cin, s); if(s=="q"||s=="Q") break; cout << (IsPalindrome(s) ? "It's a palindrome." : "It's not a palindrome.") << endl; } while (true); }
/** Underscore @file /.../Source/Kabuki_SDK-Impl/_Id/Entity.h @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt @brief This file contains the _2D.Vector_f interface. */ #include "_Id/Entity.h" using namespace _Id; Entity::Entity (const string& anEmailAdress = "", const string& aFirstName = "", const string& aLastName = "", const string& aPrimaryPhoneNum = "", const string& aStreetAdress1 = "", const string& aZipCode1 = "", const string& aStreetAdress2 = "", const string& aZipCode2 = "") { firstName = aFirstName; lastName = aLastName; phoneNumber = aPrimaryPhoneNum; emailAdress = anEmailAdress; streetAdress1 = aStreetAdress1; zipCode1 = aZipCode1; } string Entity::GetName () { return name; } int Entity::SetName (const string& S) { name = S; } bool Entity::Contains (string queery) { for_each (tags.begin(), tags.end (), [](string &S) { if (S == queery) return true; }); for_each (addresses.begin (), addresses.end(), [](Address& A) { if (S == queery) return true; }); for_each (emailAddresses.begin (), emailAddresses.end(), [](EmailAddress& A) { if (a == queery) return true; }); for_each (profiles.begin (), profiles.end(), Profile& P) { if (a == queery) return true; }); for_each (tags.begin (), tags.end(), [](String& S) { if (a == queery) return true; }); return false; }
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include <cstdio> #include "sgfx/Gfx.hpp" using namespace sgfx; void GfxMap::set_dim(const Dim & dim){ data()->size.h = dim.h(); data()->size.w = dim.w(); } void GfxMap::set_shift(const Point & p){ data()->shift.x = p.x(); data()->shift.y = p.y(); } void GfxMap::set_dim(sg_size_t w, sg_size_t h){ data()->size.w = w; data()->size.h = h; } void GfxMap::set_shift(sg_int_t x, sg_int_t y){ data()->shift.x = x; data()->shift.y = y; } GfxMap::GfxMap(const Pen & pen){ data()->pen = pen; set_shift(0,0); set_dim(0,0); } GfxMap::GfxMap(const Bitmap & bitmap, const Pen & pen, s16 rotation){ set_bitmap_center(bitmap, pen, rotation); } void GfxMap::set_bitmap_center(const Bitmap & bitmap, const Pen & pen, s16 rotation){ u8 thickness = pen.thickness(); data()->size.w = (bitmap.w() - 2*thickness)*2; data()->size.h = (bitmap.h() - 2*thickness)*2; data()->shift.x = (data()->size.w + 2*thickness)/4; data()->shift.y = (data()->size.h + 2*thickness)/4; data()->rotation = rotation; data()->pen = pen; } void Gfx::draw(Bitmap & bitmap, const sg_icon_t & icon, const sg_map_t & map, sg_bounds_t * bounds){ sg_draw_icon(bitmap.bmap(), &icon, &map, bounds); } sg_icon_primitive_t Gfx::line(sg_int_t x1, sg_int_t y1, sg_int_t x2, sg_int_t y2){ sg_icon_primitive_t ret; memset(&ret, 0, sizeof(ret)); ret.type = SG_LINE | SG_ENABLE_FLAG; ret.shift.x = x1; ret.shift.y = y1; ret.line.p.x = x2; ret.line.p.y = y2; ret.rotation = 0; return ret; } sg_icon_primitive_t Gfx::circle(sg_int_t x, sg_int_t y, sg_size_t r){ sg_icon_primitive_t ret; memset(&ret, 0, sizeof(ret)); ret.type = SG_ARC | SG_ENABLE_FLAG; ret.shift.x = x; ret.shift.y = y; ret.arc.rx = r; ret.arc.ry = r; ret.arc.start = 0; ret.arc.stop = SG_TRIG_POINTS; return ret; } sg_icon_primitive_t Gfx::arc(sg_int_t x, sg_int_t y, sg_size_t rx, sg_size_t ry, sg_int_t start, sg_int_t stop, sg_int_t rotation){ sg_icon_primitive_t ret; memset(&ret, 0, sizeof(ret)); ret.type = SG_ARC | SG_ENABLE_FLAG; ret.shift.x = x; ret.shift.y = y; ret.arc.rx = rx; ret.arc.ry = ry; ret.arc.start = start; ret.arc.stop = stop; ret.rotation = rotation; return ret; } sg_icon_primitive_t Gfx::fill(sg_int_t x1, sg_int_t y1){ sg_icon_primitive_t ret; memset(&ret, 0, sizeof(ret)); ret.type = SG_FILL | SG_ENABLE_FLAG; ret.shift.x = x1; ret.shift.y = y1; ret.rotation = 0; return ret; } void Gfx::show(const sg_icon_primitive_t & mg){ size_t i; const unsigned char * p = (const unsigned char *)(&mg); printf("{ "); for(i=0; i < sizeof(sg_icon_primitive_t); i++){ printf("0x%X", p[i]); if( i < (sizeof(sg_icon_primitive_t)-1) ){ printf(","); } printf(" "); } printf("}"); } void Gfx::show(const sg_icon_t & icon){ u8 i; for(i=0; i < icon.total; i++){ show(icon.elements[i]); if( i < (icon.total-1) ){ printf(","); } printf("\n"); } } void Gfx::draw_remove(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/2, -SG_MAX/2, SG_MAX/2, SG_MAX/2); objs[1] = line(-SG_MAX/2, SG_MAX/2, SG_MAX/2, -SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_ok(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/2, SG_MAX/4, -SG_MAX/4, SG_MAX/2); objs[1] = line(-SG_MAX/4, SG_MAX/2, SG_MAX/2, -SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_bars(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 3; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(SG_MIN/2, SG_MIN/2, SG_MAX/2, SG_MIN/2); objs[1] = Gfx::line(SG_MIN/2, 0, SG_MAX/2, 0); objs[2] = Gfx::line(SG_MIN/2, SG_MAX/2, SG_MAX/2, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_circle(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 1; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = circle(0, 0, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_circle_fill(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = circle(0, 0, SG_MAX/2); objs[1] = fill(0, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_toggle_off(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 5; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/4, -SG_MAX/4, SG_MAX/4, -SG_MAX/4); objs[1] = line(-SG_MAX/4, SG_MAX/4, SG_MAX/4, SG_MAX/4); objs[2] = arc(-SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS/4, SG_TRIG_POINTS*3/4); objs[3] = arc(SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS*3/4, SG_TRIG_POINTS*5/4); objs[4] = circle(-SG_MAX/4, 0, SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_toggle_on(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 6; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/4, -SG_MAX/4, SG_MAX/4, -SG_MAX/4); objs[1] = line(-SG_MAX/4, SG_MAX/4, SG_MAX/4, SG_MAX/4); objs[2] = arc(-SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS/4, SG_TRIG_POINTS*3/4); objs[3] = arc(SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS*3/4, SG_TRIG_POINTS*5/4); objs[4] = circle(SG_MAX/4, 0, SG_MAX/4); objs[5] = fill(-SG_MAX/4, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_power(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(0, 0, 0, -SG_MAX/2); objs[1] = arc(0, 0, SG_MAX/2, SG_MAX/2, SG_TRIG_POINTS*7/8, SG_TRIG_POINTS*7/8 + SG_TRIG_POINTS*3/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_chevron(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/8, -SG_MAX/2, SG_MAX/8, 0); objs[1] = line(SG_MAX/8, 0, -SG_MAX/8, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_arrow(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 3; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/2, 0, SG_MAX/2, 0); objs[1] = line(0, SG_MAX/2, SG_MAX/2, 0); objs[2] = line(0, -SG_MAX/2, SG_MAX/2, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_zoom(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = circle(SG_MAX/6, -SG_MAX/6, SG_MAX*3/10); objs[1] = line(-SG_MAX/20, SG_MAX/20, -SG_MAX/2, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_reset(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 3; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(SG_MAX*3/10, 0, SG_MAX*5/10, -SG_MAX*2/20); objs[1] = line(SG_MAX*3/10, 0, SG_MAX*1/10, -SG_MAX*2/20); objs[2] = arc(-SG_MAX/40, 0, SG_MAX*3/10 + SG_MAX*3/40, SG_MAX*3/10 + SG_MAX*3/40, SG_TRIG_POINTS/12, SG_TRIG_POINTS); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_lightning(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 3; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(0, -SG_MAX/2, -SG_MAX/4, SG_MAX/10); objs[1] = line(-SG_MAX/4, SG_MAX/10, SG_MAX/4, -SG_MAX/10); objs[2] = line(SG_MAX/4, -SG_MAX/10, 0, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_play(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 4; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/2, -SG_MAX/2, -SG_MAX/2, SG_MAX/2); objs[1] = line(-SG_MAX/2, SG_MAX/2, SG_MAX/2, 0); objs[2] = line(SG_MAX/2, 0, -SG_MAX/2, -SG_MAX/2); objs[3] = fill(0, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_pause(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 2; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = line(SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_button_bar(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 7; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(SG_MIN/2, 0, SG_MAX/2, 0); objs[1] = Gfx::line(SG_MIN/2+SG_MAX/32, SG_MAX/4, SG_MAX/2-SG_MAX/32, SG_MAX/4); objs[2] = Gfx::line(SG_MIN/2, 0, SG_MIN/2, SG_MAX/4 - SG_MAX/32); objs[3] = Gfx::line(SG_MAX/2, 0, SG_MAX/2, SG_MAX/4 - SG_MAX/32); objs[4] = Gfx::arc(SG_MAX/2-SG_MAX/32, SG_MAX/4-SG_MAX/32, SG_MAX/32, SG_MAX/32, 0, SG_TRIG_POINTS/4); objs[5] = Gfx::arc(SG_MIN/2+ SG_MAX/32, SG_MAX/4-SG_MAX/32, SG_MAX/32, SG_MAX/32, SG_TRIG_POINTS/4, SG_TRIG_POINTS*2/4); objs[6] = Gfx::fill(0, SG_MAX/8); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_mic(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 8; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::arc(0, -SG_MAX/6, SG_MAX/6, SG_MAX/6, SG_TRIG_POINTS/2, SG_TRIG_POINTS); objs[1] = Gfx::line(-SG_MAX/6, -SG_MAX/6, -SG_MAX/6, 0); objs[2] = Gfx::line(SG_MAX/6, -SG_MAX/6, SG_MAX/6, 0); objs[3] = Gfx::arc(0, 0, SG_MAX/6, SG_MAX/6, 0, SG_TRIG_POINTS/2); objs[4] = Gfx::arc(0, 0, SG_MAX/3, SG_MAX/3, 0, SG_TRIG_POINTS/2); objs[5] = Gfx::line(0, SG_MAX/3, 0, SG_MAX/2); objs[6] = Gfx::line(-SG_MAX/5, SG_MAX/2, SG_MAX/5, SG_MAX/2); objs[7] = Gfx::fill(0, -SG_MAX/8); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_clock(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 3; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::circle(0, 0, SG_MAX/2); objs[1] = Gfx::line(0, 0, SG_MAX/4, 0); objs[2] = Gfx::line(0, 0, 0, -SG_MAX/3); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_heart(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 5; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::arc(-SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS*3/8, SG_TRIG_POINTS); objs[1] = Gfx::arc(SG_MAX/4, 0, SG_MAX/4, SG_MAX/4, SG_TRIG_POINTS/2, SG_TRIG_POINTS + SG_TRIG_POINTS/8); objs[2] = Gfx::line(-SG_MAX/2 + SG_MAX*1/20, SG_MAX*3/10 - SG_MAX*3/20, 0, SG_MAX/2); objs[3] = Gfx::line(SG_MAX/2 - SG_MAX*1/20, SG_MAX*3/10 - SG_MAX*3/20, 0, SG_MAX/2); objs[4] = Gfx::fill(SG_MAX/4, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_plot(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 6; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/2, -SG_MAX/2, -SG_MAX/2, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/2, SG_MAX/2, SG_MAX/2, SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/2, SG_MAX/2, -SG_MAX/4, -SG_MAX/3); objs[3] = Gfx::line(-SG_MAX/4, -SG_MAX/3, 0, 0); objs[4] = Gfx::line(0, 0, SG_MAX/4, -SG_MAX/4); objs[5] = Gfx::line(SG_MAX/4, -SG_MAX/4, SG_MAX/2, SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_bike(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 11; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::circle(-SG_MAX/4, 0, SG_MAX/6); objs[1] = Gfx::circle(SG_MAX/4, 0, SG_MAX/6); objs[2] = Gfx::line(-SG_MAX/4, 0, 0, 0); objs[3] = Gfx::line(-SG_MAX/4, 0, -SG_MAX/8, -SG_MAX/4); objs[4] = Gfx::line(0, 0, SG_MAX*1/8, -SG_MAX/4); objs[5] = Gfx::line(-SG_MAX/8, -SG_MAX/4, SG_MAX*1/8, -SG_MAX/4); objs[6] = Gfx::line(SG_MAX/4, 0, SG_MAX*1/8, -SG_MAX/4); objs[7] = Gfx::line(SG_MAX*1/8, -SG_MAX*3/8, SG_MAX*1/8, -SG_MAX/4); objs[8] = Gfx::line(-SG_MAX*3/16, -SG_MAX*5/16, -SG_MAX*1/8, -SG_MAX/4); objs[9] = Gfx::line(SG_MAX*1/16, -SG_MAX*3/8, SG_MAX*3/16, -SG_MAX*3/8); objs[10] = Gfx::line(-SG_MAX*4/16, -SG_MAX*5/16, -SG_MAX*2/16, -SG_MAX*5/16); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_mountain(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 6; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/2, SG_MAX/2, -SG_MAX/4, -SG_MAX/3); objs[1] = Gfx::line(-SG_MAX/4, -SG_MAX/3, 0, 0); objs[2] = Gfx::line(0, 0, SG_MAX/4, -SG_MAX/4); objs[3] = Gfx::line(SG_MAX/4, -SG_MAX/4, SG_MAX/2, SG_MAX/2); objs[4] = Gfx::line(-SG_MAX/2, SG_MAX/2, SG_MAX/2, SG_MAX/2); objs[5] = Gfx::fill(SG_MAX/8, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_compass(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 6; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/8, 0, SG_MAX/8, 0); objs[1] = Gfx::line(-SG_MAX/8, 0, 0, -SG_MAX/4); objs[2] = Gfx::line(SG_MAX/8, 0, 0, -SG_MAX/4); objs[3] = Gfx::line(-SG_MAX/8, 0, 0, SG_MAX/4); objs[4] = Gfx::line(SG_MAX/8, 0, 0, SG_MAX/4); objs[5] = Gfx::fill(0, -SG_MAX/8); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_compass_outer(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 9; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::circle(0, 0, SG_MAX*4/10); objs[1] = Gfx::line(SG_MAX*3/10, 0, SG_MAX*5/10, 0); objs[2] = Gfx::line(-SG_MAX*3/10, 0, -SG_MAX*5/10, 0); objs[3] = Gfx::line(0, -SG_MAX*3/10, 0, -SG_MAX*5/10); objs[4] = Gfx::line(0, SG_MAX*3/10, 0, SG_MAX*5/10); objs[5] = Gfx::line(SG_MAX*5/20, SG_MAX*5/20, SG_MAX*7/20, SG_MAX*7/20); objs[6] = Gfx::line(-SG_MAX*5/20, SG_MAX*5/20, -SG_MAX*7/20, SG_MAX*7/20); objs[7] = Gfx::line(SG_MAX*5/20, -SG_MAX*5/20, SG_MAX*7/20, -SG_MAX*7/20); objs[8] = Gfx::line(-SG_MAX*5/20, -SG_MAX*5/20, -SG_MAX*7/20, -SG_MAX*7/20); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_panel(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 8; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::arc(-SG_MAX/2+SG_MAX/16, -SG_MAX/2+SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS/2, SG_TRIG_POINTS*3/4); objs[1] = Gfx::arc(-SG_MAX/2+SG_MAX/16, SG_MAX/2-SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS/4, SG_TRIG_POINTS/2); objs[2] = Gfx::arc(SG_MAX/2-SG_MAX/16, -SG_MAX/2+SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS*3/4, SG_TRIG_POINTS); objs[3] = Gfx::arc(SG_MAX/2-SG_MAX/16, SG_MAX/2-SG_MAX/16, SG_MAX/16, SG_MAX/16, 0, SG_TRIG_POINTS/4); objs[4] = Gfx::line(-SG_MAX/2+SG_MAX/16, -SG_MAX/2, SG_MAX/2-SG_MAX/16, -SG_MAX/2); objs[5] = Gfx::line(-SG_MAX/2+SG_MAX/16, SG_MAX/2, SG_MAX/2-SG_MAX/16, SG_MAX/2); objs[6] = Gfx::line(-SG_MAX/2, -SG_MAX/4+SG_MAX/16, -SG_MAX/2, SG_MAX/4-SG_MAX/16); objs[7] = Gfx::line(SG_MAX/2, -SG_MAX/4+SG_MAX/16, SG_MAX/2, SG_MAX/4-SG_MAX/16); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_panel_fill(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 9; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::arc(-SG_MAX/2+SG_MAX/16, -SG_MAX/2+SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS/2, SG_TRIG_POINTS*3/4); objs[1] = Gfx::arc(-SG_MAX/2+SG_MAX/16, SG_MAX/2-SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS/4, SG_TRIG_POINTS/2); objs[2] = Gfx::arc(SG_MAX/2-SG_MAX/16, -SG_MAX/2+SG_MAX/16, SG_MAX/16, SG_MAX/16, SG_TRIG_POINTS*3/4, SG_TRIG_POINTS); objs[3] = Gfx::arc(SG_MAX/2-SG_MAX/16, SG_MAX/2-SG_MAX/16, SG_MAX/16, SG_MAX/16, 0, SG_TRIG_POINTS/4); objs[4] = Gfx::line(-SG_MAX/2+SG_MAX/16, -SG_MAX/2, SG_MAX/2-SG_MAX/16, -SG_MAX/2); objs[5] = Gfx::line(-SG_MAX/2+SG_MAX/16, SG_MAX/2, SG_MAX/2-SG_MAX/16, SG_MAX/2); objs[6] = Gfx::line(-SG_MAX/2, -SG_MAX/4+SG_MAX/16, -SG_MAX/2, SG_MAX/4-SG_MAX/16); objs[7] = Gfx::line(SG_MAX/2, -SG_MAX/4+SG_MAX/16, SG_MAX/2, SG_MAX/4-SG_MAX/16); objs[8] = Gfx::fill(0, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_sun(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 9; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::circle(0, 0, SG_MAX*2/10); objs[1] = Gfx::line(SG_MAX*3/10, 0, SG_MAX*5/10, 0); objs[2] = Gfx::line(-SG_MAX*3/10, 0, -SG_MAX*5/10, 0); objs[3] = Gfx::line(0, -SG_MAX*3/10, 0, -SG_MAX*5/10); objs[4] = Gfx::line(0, SG_MAX*3/10, 0, SG_MAX*5/10); objs[5] = Gfx::line(SG_MAX*5/20, SG_MAX*5/20, SG_MAX*7/20, SG_MAX*7/20); objs[6] = Gfx::line(-SG_MAX*5/20, SG_MAX*5/20, -SG_MAX*7/20, SG_MAX*7/20); objs[7] = Gfx::line(SG_MAX*5/20, -SG_MAX*5/20, SG_MAX*7/20, -SG_MAX*7/20); objs[8] = Gfx::line(-SG_MAX*5/20, -SG_MAX*5/20, -SG_MAX*7/20, -SG_MAX*7/20); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_battery(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 7; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/2, -SG_MAX/4, -SG_MAX/2, SG_MAX/4); objs[1] = Gfx::line(-SG_MAX/2, -SG_MAX/4, SG_MAX*4/10, -SG_MAX/4); objs[2] = Gfx::line(-SG_MAX/2, SG_MAX/4, SG_MAX*4/10, SG_MAX/4); objs[3] = Gfx::line(SG_MAX*4/10, -SG_MAX/4, SG_MAX*4/10, SG_MAX/4); objs[4] = Gfx::line(SG_MAX*4/10, SG_MAX*1/10, SG_MAX*5/10, SG_MAX*1/10); objs[5] = Gfx::line(SG_MAX*4/10, -SG_MAX*1/10, SG_MAX*5/10, -SG_MAX*1/10); objs[6] = Gfx::line(SG_MAX*5/10, -SG_MAX*1/10, SG_MAX*5/10, SG_MAX*1/10); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_arrowhead(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 4; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(0, -SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(0, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(SG_MAX/4, SG_MAX/2, 0, SG_MAX/4); objs[3] = Gfx::line(-SG_MAX/4, SG_MAX/2, 0, SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_dot(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 1; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::circle(0, 0, SG_MAX*1/10); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_dash(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 1; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/4, 0, SG_MAX/4, 0); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_message(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ int total = 6; sg_icon_primitive_t objs[total]; sg_icon_t icon; icon.elements = objs; icon.total = total; icon.fill_total = 0; objs[0] = Gfx::line(-SG_MAX/2, -SG_MAX/4, SG_MAX/2, -SG_MAX/4); objs[1] = Gfx::line(-SG_MAX/2, SG_MAX/4, SG_MAX/2, SG_MAX/4); objs[2] = Gfx::line(SG_MAX/2, -SG_MAX/4, SG_MAX/2, SG_MAX/4); objs[3] = Gfx::line(-SG_MAX/2, -SG_MAX/4, -SG_MAX/2, SG_MAX/4); objs[4] = Gfx::line(-SG_MAX/2, -SG_MAX/4, 0, 0); objs[5] = Gfx::line(0, 0, SG_MAX/2, -SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } } void Gfx::draw_ALPHA(Bitmap & bitmap, const GfxMap & map, sg_bounds_t * bounds, bool show){ sg_icon_primitive_t objs[6]; sg_icon_t icon; icon.elements = objs; icon.fill_total = 0; //A icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, 0, -SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, SG_MAX/2, 0, -SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/8, 0, SG_MAX/8, 0); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //B icon.total = 6; //C icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/4, -SG_MAX/4, SG_MAX/4); objs[1] = Gfx::arc(0,SG_MAX/4,SG_MAX/4,0,0,SG_TRIG_POINTS/2); objs[2] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS/2,SG_TRIG_POINTS); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //D icon.total = 2; //E icon.total = 4; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, 0, 0, 0); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[3] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //F icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, 0, 0, 0); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //G icon.total = 5; //H icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, 0, SG_MAX/4, 0); objs[1] = Gfx::line(SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //I icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(0, -SG_MAX/2, 0, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //J icon.total = 2; //K icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, 0, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, 0, SG_MAX/4, -SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //L icon.total = 2; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //M icon.total = 4; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, -SG_MAX/4, -SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, 0, SG_MAX/4); objs[3] = Gfx::line(SG_MAX/4, -SG_MAX/2, 0, SG_MAX/4); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //N icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, -SG_MAX/4, -SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //O icon.total = 4; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/4, -SG_MAX/4, SG_MAX/4); objs[1] = Gfx::line(SG_MAX/4, -SG_MAX/4, SG_MAX/4, SG_MAX/4); objs[2] = Gfx::arc(0,SG_MAX/4,SG_MAX/4,SG_MAX/4,0,SG_TRIG_POINTS/2); objs[3] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS/2,SG_TRIG_POINTS); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //P icon.total = 4; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, -SG_MAX/2, 0, -SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, 0, 0, 0); objs[3] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS*3/4,SG_TRIG_POINTS*5/4); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //Q icon.total = 5; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/4, -SG_MAX/4, SG_MAX/4); objs[1] = Gfx::line(SG_MAX/4, -SG_MAX/4, SG_MAX/4, SG_MAX/4); objs[2] = Gfx::arc(0,SG_MAX/4,SG_MAX/4,SG_MAX/4,0,SG_TRIG_POINTS/2); objs[3] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS/2,SG_TRIG_POINTS); objs[4] = Gfx::line(SG_MAX/4, SG_MAX/4, SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //R icon.total = 5; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, -SG_MAX/2, 0, -SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, 0, 0, 0); objs[3] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS*3/4,SG_TRIG_POINTS*5/4); objs[4] = Gfx::line(0, 0, SG_MAX/4, SG_MAX/2); //draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //S icon.total = 2; objs[0] = Gfx::arc(0,-SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS/4,SG_TRIG_POINTS); objs[1] = Gfx::arc(0,SG_MAX/4,SG_MAX/4,SG_MAX/4,SG_TRIG_POINTS*3/4,SG_TRIG_POINTS*3/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } return; //T icon.total = 2; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(0, SG_MAX/2, 0, -SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //U icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/4, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, -SG_MAX/4, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::arc(0,-SG_MAX/4,0,0,SG_TRIG_POINTS/2,SG_TRIG_POINTS); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //V icon.total = 2; objs[0] = Gfx::line(-SG_MAX/4, SG_MAX/2, 0, -SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, SG_MAX/2, 0, -SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //W icon.total = 4; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, -SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, 0, SG_MAX/4); objs[3] = Gfx::line(SG_MAX/4, -SG_MAX/2, 0, SG_MAX/4); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //X icon.total = 2; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, -SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //Y icon.total = 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, 0, 0); objs[1] = Gfx::line(SG_MAX/4, SG_MAX/2, 0, 0); objs[2] = Gfx::line(0, 0, 0, -SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } //Z icon.total= 3; objs[0] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, -SG_MAX/2); objs[1] = Gfx::line(-SG_MAX/4, SG_MAX/2, SG_MAX/4, SG_MAX/2); objs[2] = Gfx::line(-SG_MAX/4, -SG_MAX/2, SG_MAX/4, SG_MAX/2); draw(bitmap, icon, map.item()); if( show ){ Gfx::show(icon); } }
// Problem - NHAY on SPOJ #include <bits/stdc++.h> using namespace std; #define ll long long ll n,m,lps[5000001]; string a,b; void computelps() { ll i,len; lps[0]=0; i=1; len=0; while(i<n) { if(a[i]==a[len]) { len++; lps[i]=len; i++; } else { if(len!=0) len=lps[len-1]; else { lps[i]=0; i++; } } } } void searchstr() { m=b.size(); ll i,j,cnt; i=j=cnt=0; while(i<m) { if(a[j]==b[i]) { i++; j++; } if(j==n) { cnt++; printf("%lld\n",i-j); j=lps[j-1]; } if(i<m&&a[j]!=b[i]) { if(j!=0) j=lps[j-1]; else i++; } } if(cnt==0) printf("\n"); } int main() { while(scanf("%lld",&n)!=EOF) { cin>>a>>b; computelps(); searchstr(); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SVGGRADIENT_H #define SVGGRADIENT_H #ifdef SVG_SUPPORT #ifdef SVG_SUPPORT_GRADIENTS #include "modules/svg/src/SVGMatrix.h" #include "modules/svg/src/SVGRect.h" #include "modules/svg/src/SVGLength.h" #include "modules/svg/src/SVGInternalEnum.h" #include "modules/svg/src/svgpaintserver.h" class SVGDocumentContext; class SVGElementResolver; class SVGStop { public: SVGStop() : m_stopcolor(OP_RGB(0,0,0)), m_stopopacity(0xFF), m_offset(0) {} SVGStop(const SVGStop& s) : m_stopcolor(s.m_stopcolor), m_stopopacity(s.m_stopopacity), m_offset(s.m_offset) {} UINT32 GetColorRGB() const; UINT8 GetOpacity() const { return m_stopopacity; } SVGNumber GetOffset() const { return m_offset; } void SetOffset(SVGNumber offset) { m_offset = offset; } void SetColorRGB(UINT32 color) { m_stopcolor = color; } void SetOpacity(UINT8 opacity) { m_stopopacity = opacity; } private: UINT32 m_stopcolor; UINT8 m_stopopacity; SVGNumber m_offset; }; struct SVGGradientParameters; class SVGGradient : public SVGPaintServer { public: enum GradientType { LINEAR, RADIAL }; SVGGradient(GradientType type) : m_a(0), m_b(0), m_c(0), m_d(0), m_e(0), m_type(type), m_spread(SVGSPREAD_UNKNOWN), m_units(SVGUNITS_UNKNOWN) {} virtual OP_STATUS GetFill(VEGAFill** vfill, VEGATransform& vfilltrans, SVGPainter* painter, SVGPaintNode* context_node); virtual void PutFill(VEGAFill* vfill); static OP_STATUS Create(HTML_Element *gradient_element, SVGElementResolver* resolver, SVGDocumentContext* doc_ctx, const SVGValueContext& vcxt, SVGGradient **outgrad); GradientType Type() const { return m_type; } void SetType(GradientType t) { m_type = t; } SVGSpreadMethodType GetSpreadMethod() const { return m_spread; } void SetSpreadMethod(SVGSpreadMethodType type) { m_spread = type; } SVGUnitsType GetUnits() const { return m_units; } void SetUnits(SVGUnitsType type) { m_units = type; } UINT32 GetNumStops() const { return m_stops.GetCount(); } const SVGStop* GetStop(UINT32 index) const { return m_stops.Get(index); } OP_STATUS AddStop(SVGStop *stop) { return stop ? m_stops.Add(stop) : OpStatus::ERR; } const SVGMatrix& GetTransform() const { return m_transform; } void SetTransform(const SVGMatrix& t) { m_transform.Copy(t); } SVGNumber GetCx() const { return m_a; } SVGNumber GetCy() const { return m_b; } SVGNumber GetFx() const { return m_c; } SVGNumber GetFy() const { return m_d; } SVGNumber GetR() const { return m_e; } void SetCx(SVGNumber cx) { m_a = cx; } void SetCy(SVGNumber cy) { m_b = cy; } void SetFx(SVGNumber fx) { m_c = fx; } void SetFy(SVGNumber fy) { m_d = fy; } void SetR(SVGNumber r) { m_e = r; } SVGNumber GetX1() const { return m_a; } SVGNumber GetY1() const { return m_b; } SVGNumber GetX2() const { return m_c; } SVGNumber GetY2() const { return m_d; } void SetX1(SVGNumber x1) { m_a = x1; } void SetY1(SVGNumber y1) { m_b = y1; } void SetX2(SVGNumber x2) { m_c = x2; } void SetY2(SVGNumber y2) { m_d = y2; } const SVGRect& GetTargetBoundingBox() const { return m_bbox; } void SetTargetBoundingBox(SVGNumber x, SVGNumber y, SVGNumber w, SVGNumber h); OP_STATUS CreateCopy(SVGGradient **outcopy) const; #ifdef SELFTEST BOOL operator==(const SVGGradient& other) const; #endif // SELFTEST #ifdef _DEBUG void Print() const; #endif private: OP_STATUS FetchValues(HTML_Element *gradient_element, SVGElementResolver* resolver, SVGDocumentContext* doc_ctx, SVGGradientParameters* params, HTML_Element** stop_root); OP_STATUS FetchGradientStops(HTML_Element* stop_root); void ResolveGradientParameters(const SVGGradientParameters& params, const SVGValueContext& vcxt); static OP_STATUS CreateStop(HTML_Element *stopelm, LayoutProperties* props, LayoutInfo& info, SVGStop **outstop); virtual ~SVGGradient() {} SVGNumber m_a; SVGNumber m_b; SVGNumber m_c; SVGNumber m_d; SVGNumber m_e; GradientType m_type; SVGSpreadMethodType m_spread; SVGUnitsType m_units; OpAutoVector<SVGStop> m_stops; SVGMatrix m_transform; SVGRect m_bbox; }; #endif // SVG_SUPPORT_GRADIENTS #endif // SVG_SUPPORT #endif // SVGGRADIENT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SCOPE_CONSOLE_LOGGER_H #define SCOPE_CONSOLE_LOGGER_H #ifdef SCOPE_CONSOLE_LOGGER #include "modules/scope/src/scope_service.h" #include "modules/console/opconsoleengine.h" #include "modules/scope/src/generated/g_scope_console_logger_interface.h" class OpScopeWindowManager; class OpScopeConsoleLogger : public OpScopeConsoleLogger_SI , protected OpConsoleListener { public: OpScopeConsoleLogger(); virtual ~OpScopeConsoleLogger(); virtual OP_STATUS Construct(); virtual OP_STATUS OnPostInitialization(); protected: // From OpConsoleListener virtual OP_STATUS NewConsoleMessage(unsigned int id, const OpConsoleEngine::Message *message); private: // Request/Response functions virtual OP_STATUS DoClear(); virtual OP_STATUS DoListMessages(ConsoleMessageList &out); BOOL AcceptWindowID(unsigned window_id); OP_STATUS SetConsoleMessage(const OpConsoleEngine::Message *msg, ConsoleMessage &out); OpScopeWindowManager *window_manager; }; #endif // SCOPE_CONSOLE_LOGGER #endif // SCOPE_CONSOLE_LOGGER_H
#include <bits/stdc++.h> using namespace std; unsigned long long int N,ini,fin,uno=1,dos,i; unsigned long long int fibo[100]; int posi = -1; int main() { fibo[1] = fibo[2] = 1; for(i=3; i<=93; i++){ fibo[i] = fibo[i-1] + fibo[i-2]; } cin >> N; for(i=1; i<=93; i++){ if(N == fibo[i]){ posi = i; break; } } cout << posi; return 0; }
#include<iostream> #include<algorithm> #include<vector> #include<unordered_map> using namespace std; class Solution { public: int subarraySum(vector<int>& nums, int k) { //基本思想:暴力超时,双重循环遍历所有可能的连续子序列,这道题不能用滑动窗口,因为元素存在负数 int res=0,sum=0; for(int i=0;i<nums.size();i++) { sum=0; for(int j=i;j<nums.size();j++) { sum+=nums[j]; if(sum==k) res++; } } return res; } }; class Solution1 { public: int subarraySum(vector<int>& nums, int k) { //基本思想:前缀和+哈希表HashMap,HashMap[i]表示前缀和为i的子序列出现的次数,pre[i]-pre[j-1]==k,pre[j-1]==pre[i]-k //遍历数组nums,计算从第0个元素到当前元素的和sum,用哈希表Map保存出现过的累积和sum的次数; //如果sum-k在哈希表中出现过,则代表从当前下标i往前有连续的子数组的和为sum. int res=0; unordered_map<int,int> Map; Map[0]=1; int sum=0; for(int i=0;i<nums.size();i++) { sum+=nums[i]; if(Map.find(sum-k)!=Map.end()) { res+=Map[sum-k]; } Map[sum]++; } return res; } }; int main() { Solution1 solute; vector<int> nums={1,1,1}; int k=2; cout<<solute.subarraySum(nums,k)<<endl; return 0; }
#pragma once #include <vector> #include <ionir/construct/construct.h> namespace ionir { template<class T = Construct> class ConstructBuilder { private: std::vector<Construct> parts; public: ConstructBuilder() : parts({}) { // } [[nodiscard]] std::vector<Construct> getParts() const { return this->parts; } void clear() { this->parts.clear(); } template<class TConstruct, typename... TArgs> ionshared::Ptr<ConstructBuilder> push(TArgs... args) { // TODO: Ensure TConstruct inherits from Construct or derived. this->parts.push_back(std::make_shared<TConstruct>(args)); return nullptr; } ionshared::Ptr<T> make() { std::vector<Construct> parts = this->parts; this->clear(); return std::make_shared<T>(parts...); } }; }
/************************************************************* This sketch is cutomized for M5Stack + USB Host Shield + FTDI. USB_Host_Shield_2.0: https://github.com/felis/USB_Host_Shield_2.0 *************************************************************/ #include <M5Stack.h> #include "M5StackUpdater.h" #include "cdcftdimod.h" #include <usbhub.h> #include "pgmstrings.h" // Satisfy the IDE, which needs to see the include statment in the ino too. #ifdef dobogusinclude #include <spi4teensy3.h> #endif #include <SPI.h> class FTDIMODAsync : public FTDIMODAsyncOper { public: uint8_t OnInit(FTDIMOD *pftdi); }; uint8_t FTDIMODAsync::OnInit(FTDIMOD *pftdi) { uint8_t rcode = 0; // rcode = pftdi->SetBaudRate(115200); rcode = pftdi->SetBaudRate(9600); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetBaudRate"), rcode); return rcode; } rcode = pftdi->SetFlowControl(FTDI_SIO_DISABLE_FLOW_CTRL); if (rcode) ErrorMessage<uint8_t>(PSTR("SetFlowControl"), rcode); return rcode; } USB Usb; //USBHub Hub(&Usb); FTDIMODAsync FtdiAsync; FTDIMOD Ftdi(&Usb, &FtdiAsync); // A few test variables used during debugging boolean change_colour = 1; boolean selected = 1; // We have to blank the top line each time the display is scrolled, but this takes up to 13 milliseconds // for a full width line, meanwhile the serial buffer may be filling... and overflowing // We can speed up scrolling of short text lines by just blanking the character we drew int blank[19]; // We keep all the strings pixel lengths to optimise the speed of the top line blanking // GVS Logo extern const unsigned char gImage_logoGVS[]; boolean InitFlag = false; // for GVS char buffer[10]; char ID = 1; int Dat = 0; char pole = 0; char A = '0'; void setup() { // Setup the TFT display M5.begin(); if(digitalRead(BUTTON_A_PIN) == 0) { Serial.println("Will Load menu binary"); updateFromFS(SD); ESP.restart(); } // Use GVS Logo M5.Lcd.pushImage(0, 0, 320, 240, (uint16_t *)gImage_logoGVS); // Serial.begin( 115200 ); #if !defined(__MIPSEL__) while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection #endif Serial.println("Start"); /* drawString(const char *string, int poX, int poY, int font), drawCentreString(const char *string, int dX, int poY, int font), // Deprecated, use setTextDatum() and drawString() drawRightString(const char *string, int dX, int poY, int font), // Deprecated, use setTextDatum() and drawString() */ if (Usb.Init() == -1){ Serial.println("OSC did not start."); } // Change colour for scrolling zone text M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK); } void loop() { Usb.Task(); if( Usb.getUsbTaskState() == USB_STATE_RUNNING ){ uint8_t rcode; if(InitFlag == false){ /* char strbuf[] = "R"; //char strbuf[] = "The quick brown fox jumps over the lazy dog"; //char strbuf[] = "This string contains 61 character to demonstrate FTDI buffers"; //add one symbol to it to see some garbage rcode = Ftdi.SndData(strlen(strbuf), (uint8_t*)strbuf); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } */ InitFlag = true; delay(50); } if(M5.BtnA.wasPressed()){ M5.Lcd.fillRect(0,0,320,240, TFT_RED); M5.Lcd.setTextColor(TFT_BLUE, TFT_RED); if(A == '0'){ A = '5'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 2) * PI) * 120), TFT_GREEN); } }else if(A == '5'){ A = '4'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 4) * PI) * 120), TFT_GREEN); } }else if(A == '4'){ A = '3'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 6) * PI) * 120), TFT_GREEN); } }else if(A == '3'){ A = '2'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 8) * PI) * 120), TFT_GREEN); } }else if(A == '2'){ A = '1'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 10) * PI) * 120), TFT_GREEN); } }else if(A == '1'){ A = '5'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 2) * PI) * 120), TFT_GREEN); } } M5.Lcd.drawCentreString("Mode" + (String)A, 320/2, 240/2, 4); } if(M5.BtnB.wasPressed()){ M5.Lcd.fillRect(0,0,320,240, TFT_RED); M5.Lcd.setTextColor(TFT_BLUE, TFT_RED); if(A == '0'){ A = '1'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 10) * PI) * 120), TFT_GREEN); } }else if(A == '1'){ A = '2'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 8) * PI) * 120), TFT_GREEN); } }else if(A == '2'){ A = '3'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 6) * PI) * 120), TFT_GREEN); } }else if(A == '3'){ A = '4'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 4) * PI) * 120), TFT_GREEN); } }else if(A == '4'){ A = '5'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 2) * PI) * 120), TFT_GREEN); } }else if(A == '5'){ A = '1'; for (int16_t i = 0; i < 320; i++){ M5.Lcd.drawPixel(i, (240 / 2) - (int16_t)(sin((double)i / (320 / 10) * PI) * 120), TFT_GREEN); } } M5.Lcd.drawCentreString("Mode" + (String)A, 320/2, 240/2, 4); } if(M5.BtnC.wasPressed()){ A = '0'; Serial.println("Stopped"); M5.Lcd.fillRect(0,0,320,240, TFT_GREEN); M5.Lcd.setTextColor(TFT_BLUE, TFT_GREEN); M5.Lcd.drawCentreString("Stopped", 320/2, 240/2, 4); delay(1500); M5.Lcd.fillRect(0,0,320,240, TFT_BLACK); // Use GVS Logo M5.Lcd.pushImage(0, 0, 320, 240, (uint16_t *)gImage_logoGVS); } uint8_t buf[64]; for (uint8_t i=0; i<64; i++){ buf[i] = 0; } uint16_t rcvd = 64; rcode = Ftdi.RcvData(&rcvd, buf); if (rcode && rcode != hrNAK){ ErrorMessage<uint8_t>(PSTR("Ret"), rcode); } if( rcvd > 2 ) { //more than 2 bytes received for(uint16_t i = 2; i < rcvd; i++ ) { Serial.print((char)buf[i]); M5.Lcd.print((char)buf[i]); } } GVStest(A); // 前庭電気刺激(Galvanic Vestibular Stimulation) } M5.update(); } // ############################################################################################## // GVS Control // ############################################################################################## void GVStest(char Mode){ uint8_t rcode; int i; if (Mode == '1'){ if (pole == 1){ pole = 0; } else{ pole = 1; } for (i = 0; i < 256; i++){ Dat = (int)(sin((double)i / 256 * PI) * 4095); // M5.lcd.printf("D = %d,%d\n", Dat,pole); Serial.printf("D = %d,%d\n", Dat,pole); ID = 1; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } delay(1); } } else if (Mode== '2'){ if (pole == 1){ pole = 0; } else{ pole = 1; } for (i = 0; i < 128; i++){ Dat = (int)(sin((double)i / 128 * PI) * 4095); // M5.lcd.printf("D = %d,%d\n", Dat,pole); Serial.printf("D = %d,%d\n", Dat,pole); ID = 1; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } delay(1); } } else if (Mode == '3'){ if (pole == 1){ pole = 0; } else{ pole = 1; } for (i = 0; i < 64; i++) { Dat = (int)(sin((double)i / 64 * PI) * 4095); // M5.lcd.printf("D = %d,%d\n", Dat,pole); Serial.printf("D = %d,%d\n", Dat,pole); ID = 1; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } delay(1); } } else if (Mode == '4'){ if (pole == 1){ pole = 0; } else{ pole = 1; } for (i = 0; i < 32; i++) { Dat = (int)(sin((double)i / 32 * PI) * 4095); // M5.lcd.printf("D = %d,%d\n", Dat,pole); Serial.printf("D = %d,%d\n", Dat,pole); ID = 1; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } delay(1); } } else if (Mode == '5') { if (pole == 1) { pole = 0; } else{ pole = 1; } for (i = 0; i < 16; i++) { Dat = (int)(sin((double)i / 16 * PI) * 4095); // M5.lcd.printf("D = %d,%d\n", Dat,pole); Serial.printf("D = %d,%d\n", Dat,pole); ID = 1; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } delay(1); } } /* else{ //'G'を送るとデータを受け取る MSBで16ビットのうち 先頭3ビットがチャンネル 4ビット目が極(+か-の), //のこり12bitがデータというフォーマットです. for (i = 0; i < 256; i++) { ID = 1; Dat = i * 16 * 2; buffer[0] = 'G'; buffer[1] = (ID << 5) + (pole << 4) + (Dat >> 8); buffer[2] = (char)Dat; // hCom1->transmit((BYTE*)buffer, 3); rcode = Ftdi.SndData(strlen(buffer), (uint8_t*)buffer); if (rcode){ ErrorMessage<uint8_t>(PSTR("SndData"), rcode); } Serial.printf("D = %d,%d\n", Dat,pole); delay(20); } } */ }
#include <iostream> #include <collections/shaders.hpp> shaderShadowMap::shaderShadowMap(void) { const std::string vs_source = #include <collections/shaders/shadowmapvs.glsl> ; const std::string fs_source = #include <collections/shaders/shadowmapfs.glsl> ; this->shaders.resize(2); shaders[0] = ShaderMan::createShaderFromString(vs_source, GL_VERTEX_SHADER); shaders[1] = ShaderMan::createShaderFromString(fs_source, GL_FRAGMENT_SHADER); this->pid = ShaderMan::loadShaderProgram(&shaders[0], shaders.size()); } phongWithShadowMap::phongWithShadowMap(void) { const std::string vs_source = #include <collections/shaders/phongvs.glsl> ; const std::string fs_source = #include <collections/shaders/phongfs.glsl> ; this->shaders.resize(2); shaders[0] = ShaderMan::createShaderFromString(vs_source, GL_VERTEX_SHADER); shaders[1] = ShaderMan::createShaderFromString(fs_source, GL_FRAGMENT_SHADER); this->pid = ShaderMan::loadShaderProgram(&shaders[0], shaders.size()); } const std::string phongNoShadow::uniform_MVP = "MVP"; const std::string phongNoShadow::uniform_lightPos = "lightPos"; const std::string phongNoShadow::uniform_texdiffuse = "diffuse_tex"; const std::string phongNoShadow::uniform_texspecular = "specular_tex"; const std::string phongNoShadow::uniform_viewPos = "viewPos"; phongNoShadow::phongNoShadow(void) { const std::string vs_source = #include <collections/shaders/phong0vs.glsl> ; const std::string fs_source = #include <collections/shaders/phong0fs.glsl> ; this->shaders.resize(2); shaders[0] = ShaderMan::createShaderFromString(vs_source, GL_VERTEX_SHADER); shaders[1] = ShaderMan::createShaderFromString(fs_source, GL_FRAGMENT_SHADER); this->pid = ShaderMan::loadShaderProgram(&shaders[0], shaders.size()); this->useProgram(); GLuint mvp = glGetUniformLocation(this->pid, this->uniform_MVP.c_str()); GLuint lightpos = glGetUniformLocation(this->pid, this->uniform_lightPos.c_str()); GLuint viewpos = glGetUniformLocation(this->pid, this->uniform_viewPos.c_str()); this->uniforms.insert(std::make_pair(this->uniform_MVP, mvp)); this->uniforms.insert(std::make_pair(this->uniform_lightPos, lightpos)); this->addTextureUniform(phongNoShadow::uniform_texdiffuse, TEX_Diffuse); this->addTextureUniform(phongNoShadow::uniform_texspecular, TEX_Specular); this->uniforms.insert(std::make_pair(this->uniform_viewPos, viewpos)); }
#include"DetectorConstruction.hh" #include"SensitiveDetector.hh" #include<G4NistManager.hh> #include<G4Box.hh> #include<G4Tubs.hh> #include<G4LogicalVolume.hh> #include<G4PVPlacement.hh> #include<G4SDManager.hh> #include<G4VisAttributes.hh> #include <G4SystemOfUnits.hh> using namespace std; #define Mat(x) (G4NistManager::Instance()->FindOrBuildMaterial(x)) World::World(double size_x, double size_y, double size_z, G4Material *mater_): mater(mater_), sizex(size_x), sizey(size_y), sizez(size_z) { //double size05 = size/2; solid = new G4Box("world", sizex/2, sizey/2, sizez/2); logic = new G4LogicalVolume( solid, mater, "World", 0, 0, 0); physic = new G4PVPlacement(0, G4ThreeVector(), logic, "World", 0, false, 0); } DetectorConstruction::DetectorConstruction() { } DetectorConstruction::~DetectorConstruction() { } G4VPhysicalVolume* DetectorConstruction::Construct() { world = new World(30*cm, 30*cm, 30*cm, Mat("G4_Galactic")); G4Box *solidTgt = new G4Box("solidTgt", 5*cm, 5*cm, 1.2*mm); G4LogicalVolume *logiclTgt = new G4LogicalVolume(solidTgt, Mat("G4_Be"), "logiclTgt"); G4PVPlacement *physilTgt = new G4PVPlacement(0, G4ThreeVector(0,0,-5*cm), logiclTgt, "physilTgt", world->getLogic(), false, 0); G4Box *solidDet = new G4Box("solidDet", 5*cm, 5*cm, 0.5*mm); G4LogicalVolume *logicDet = new G4LogicalVolume(solidDet, Mat("G4_WATER"), "logicDet"); G4PVPlacement *physiDet = new G4PVPlacement(0, G4ThreeVector(0,0,5*cm), logicDet, "physiDet", world->getLogic(), false, 0); SensitiveDetector *detector = new SensitiveDetector("1"); G4SDManager* SDman = G4SDManager::GetSDMpointer(); SDman->AddNewDetector(detector); logicDet->SetSensitiveDetector(detector); world->getLogic()->SetVisAttributes (G4VisAttributes::Invisible); return world->getPhysic(); }
#include<iostream> #include<list> #include<conio.h> using namespace std; class graph { int V; list<int> *adj; int DFSUTIL(int v,bool visited[],int count); public: void DFS(int v); graph(int V); void add_edge(int v,int w); }; graph::graph(int V) { this->V = V; adj = new list<int>[V]; } void graph::add_edge(int v,int w) { adj[v].push_back(w);} void graph::DFS(int v) { int c=0,count; bool *visited = new bool[V]; for(int i=0;i<V;i++) visited[i]= false; count = DFSUTIL(v,visited,c); printf("%d",count); } int graph::DFSUTIL(int v,bool visited[],int count) { visited[v]=true; cout<<v<<" "; list<int>::iterator i; for(i=adj[v].begin();i!=adj[v].end();++i) { if(!visited[*i]) { DFSUTIL(*i,visited,count); } count++; } return count; } int main() { graph g(4); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(1, 2); g.add_edge(2, 0); g.add_edge(2, 3); g.add_edge(3, 3); g.DFS(2); getch(); }
#include "Md5Utils.h" #include <stdio.h> #include <stdlib.h> #include "../VFS/GUtMd5.h" #include <assert.h> #include <fstream> void HashToString(const unsigned char hash[16], char str[16*2+1]) { for(int i = 0; i < 16; ++i) sprintf(&str[i*2], "%02x", (int)hash[i]); str[16*2] = '\0'; } void StringToHash(const char str[32], unsigned char hash[16]) { for(int i = 0; i < 16; ++i) { char tmp[3]; tmp[0] = str[i*2]; tmp[1] = str[i*2 + 1]; tmp[2] = '\0'; char *st; hash[i] = (unsigned char)strtol(tmp, &st, 16); } } void GenerateHash(const std::string & name, unsigned char hash[16], std::vector<Md5Digest> &hash_set, offset_type & length) { hash_set.clear(); length.offset = 0; memset(hash, 0, 16); IFile* pTemp = OpenDiskFile(name.c_str(), IFile::O_ReadOnly); if(pTemp) { MD5Context ctx; MD5Init(&ctx, 0); length = pTemp->GetSize(); hash_set.reserve(size_t(length.offset/block_size.offset)); std::vector<unsigned char> buffer((size_t)block_size.offset); for(offset_type i(0); i<length; i = i + block_size) { offset_type size_read = pTemp->Read(&buffer[0], block_size); assert(size_read.offset>0); MD5Update(&ctx, &buffer[0], (unsigned int)size_read.offset); MD5Context ctx_file; MD5Init(&ctx_file, 0); MD5Update(&ctx_file, &buffer[0], (unsigned int)size_read.offset); Md5Digest result; MD5Final(&result.hash[0], &ctx_file); hash_set.push_back(result); } delete pTemp; MD5Final(hash, &ctx); } } void LoadHashSet( const std::string & name, std::vector<Md5Digest> & hash_set, offset_type & length ) { hash_set.clear(); length.offset = 0; std::ifstream file(name.c_str()); file >> length.offset; std::string h; while(file>>h) { assert(h.size() == 32); Md5Digest d; StringToHash(h.c_str(), d.hash); hash_set.push_back(d); } }
#include "Socio.hpp" Socio::Socio(string nome, string email) { // Sem necessidade de implementação. } Socio::~Socio() { // Sem necessidade de implementação. } void Socio::cadastraCliente(string nome, string email){ ofstream insereSocio; insereSocio.open("doc/cadastroSocios.txt", ios::app); insereSocio << nome << endl; insereSocio << email << endl; insereSocio.close(); }
// Created on: 1992-02-11 // Created by: Christian CAILLET // Copyright (c) 1992-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 _StepData_StepReaderData_HeaderFile #define _StepData_StepReaderData_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Resource_FormatType.hxx> #include <Interface_IndexedMapOfAsciiString.hxx> #include <TColStd_DataMapOfIntegerInteger.hxx> #include <Standard_Integer.hxx> #include <Interface_FileReaderData.hxx> #include <Standard_CString.hxx> #include <Interface_ParamType.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <StepData_Logical.hxx> class Interface_Check; class TCollection_AsciiString; class StepData_PDescr; class Standard_Transient; class StepData_SelectMember; class StepData_Field; class StepData_ESDescr; class StepData_FieldList; class StepData_SelectType; class TCollection_HAsciiString; class StepData_EnumTool; class StepData_StepReaderData; DEFINE_STANDARD_HANDLE(StepData_StepReaderData, Interface_FileReaderData) //! Specific FileReaderData for Step //! Contains literal description of entities (for each one : type //! as a string, ident, parameter list) //! provides references evaluation, plus access to literal data //! and specific access methods (Boolean, XY, XYZ) class StepData_StepReaderData : public Interface_FileReaderData { public: //! creates StepReaderData correctly dimensionned (necessary at //! creation time, because it contains arrays) //! nbheader is nb of records for Header, nbtotal for Header+Data //! and nbpar gives the total count of parameters Standard_EXPORT StepData_StepReaderData(const Standard_Integer nbheader, const Standard_Integer nbtotal, const Standard_Integer nbpar, const Resource_FormatType theSourceCodePage = Resource_FormatType_UTF8); //! Fills the fields of a record Standard_EXPORT void SetRecord (const Standard_Integer num, const Standard_CString ident, const Standard_CString type, const Standard_Integer nbpar); //! Fills the fields of a parameter of a record. This is a variant //! of AddParam, Adapted to STEP (optimized for specific values) Standard_EXPORT void AddStepParam (const Standard_Integer num, const Standard_CString aval, const Interface_ParamType atype, const Standard_Integer nument = 0); //! Returns Record Type Standard_EXPORT const TCollection_AsciiString& RecordType (const Standard_Integer num) const; //! Returns Record Type as a CString //! was C++ : return const Standard_EXPORT Standard_CString CType (const Standard_Integer num) const; //! Returns record identifier (Positive number) //! If returned ident is not positive : Sub-List or Scope mark Standard_EXPORT Standard_Integer RecordIdent (const Standard_Integer num) const; //! Returns SubList numero designated by a parameter (nump) in a //! record (num), or zero if the parameter does not exist or is //! not a SubList address. Zero too If aslast is True and nump //! is not for the last parameter Standard_EXPORT Standard_Integer SubListNumber (const Standard_Integer num, const Standard_Integer nump, const Standard_Boolean aslast) const; //! Returns True if <num> corresponds to a Complex Type Entity //! (as can be defined by ANDOR Express clause) Standard_EXPORT Standard_Boolean IsComplex (const Standard_Integer num) const; //! Returns the List of Types which correspond to a Complex Type //! Entity. If not Complex, there is just one Type in it //! For a SubList or a Scope mark, <types> remains empty Standard_EXPORT void ComplexType (const Standard_Integer num, TColStd_SequenceOfAsciiString& types) const; //! Returns the Next "Component" for a Complex Type Entity, of //! which <num> is already a Component (the first one or a next one) //! Returns 0 for a Simple Type or for the last Component Standard_EXPORT Standard_Integer NextForComplex (const Standard_Integer num) const; //! Determines the first component which brings a given name, for //! a Complex Type Entity //! <num0> is the very first record of this entity //! <num> is given the last NextNamedForComplex, starts at zero //! it is returned as the newly found number //! Hence, in the normal case, NextNamedForComplex starts by num0 //! if <num> is zero, else by NextForComplex(num) //! If the alphabetic order is not respected, it restarts from //! num0 and loops on NextForComplex until finding <name> //! In case of "non-alphabetic order", <ach> is filled with a //! Warning for this name //! In case of "not-found at all", <ach> is filled with a Fail, //! and <num> is returned as zero //! //! Returns True if alphabetic order, False else Standard_EXPORT Standard_Boolean NamedForComplex (const Standard_CString name, const Standard_Integer num0, Standard_Integer& num, Handle(Interface_Check)& ach) const; //! Determines the first component which brings a given name, or //! short name for a Complex Type Entity //! <num0> is the very first record of this entity //! <num> is given the last NextNamedForComplex, starts at zero //! it is returned as the newly found number //! Hence, in the normal case, NextNamedForComplex starts by num0 //! if <num> is zero, else by NextForComplex(num) //! If the alphabetic order is not respected, it restarts from //! num0 and loops on NextForComplex until finding <name> //! In case of "non-alphabetic order", <ach> is filled with a //! Warning for this name //! In case of "not-found at all", <ach> is filled with a Fail, //! and <num> is returned as zero //! //! Returns True if alphabetic order, False else Standard_EXPORT Standard_Boolean NamedForComplex (const Standard_CString theName, const Standard_CString theShortName, const Standard_Integer num0, Standard_Integer& num, Handle(Interface_Check)& ach) const; //! Checks Count of Parameters of record <num> to equate <nbreq> //! If this Check is successful, returns True //! Else, fills <ach> with an Error Message then returns False //! <mess> is included in the Error message if given non empty Standard_EXPORT Standard_Boolean CheckNbParams (const Standard_Integer num, const Standard_Integer nbreq, Handle(Interface_Check)& ach, const Standard_CString mess = "") const; //! reads parameter <nump> of record <num> as a sub-list (may be //! typed, see ReadTypedParameter in this case) //! Returns True if OK. Else (not a LIST), returns false and //! feeds Check with appropriate check //! If <optional> is True and Param is not defined, returns True //! with <ach> not filled and <numsub> returned as 0 //! Works with SubListNumber with <aslast> false (no specific case //! for last parameter) Standard_EXPORT Standard_Boolean ReadSubList (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Integer& numsub, const Standard_Boolean optional = Standard_False, const Standard_Integer lenmin = 0, const Standard_Integer lenmax = 0) const; //! reads the content of a sub-list into a transient : //! SelectNamed, or HArray1 of Integer,Real,String,Transient ... //! recursive call if list of list ... //! If a sub-list has mixed types, an HArray1OfTransient is //! produced, it may contain SelectMember //! Intended to be called by ReadField //! The returned status is : negative if failed, 0 if empty. //! Else the kind to be recorded in the field Standard_EXPORT Standard_Integer ReadSub (const Standard_Integer numsub, const Standard_CString mess, Handle(Interface_Check)& ach, const Handle(StepData_PDescr)& descr, Handle(Standard_Transient)& val) const; //! Reads parameter <nump> of record <num> into a SelectMember, //! self-sufficient (no Description needed) //! If <val> is already created, it will be filled, as possible //! And if reading does not match its own description, the result //! will be False //! If <val> is not it not yet created, it will be (SelectNamed) //! useful if a field is defined as a SelectMember, directly //! (SELECT with no Entity as member) //! But SelectType also manages SelectMember (for SELECT with //! some members as Entity, some other not) Standard_EXPORT Standard_Boolean ReadMember (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Handle(StepData_SelectMember)& val) const; //! Safe variant for arbitrary type of argument template <class T> Standard_Boolean ReadMember (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Handle(T)& val) const { Handle(StepData_SelectMember) aVal = val; return ReadMember (num, nump, mess, ach, aVal) && ! (val = Handle(T)::DownCast(aVal)).IsNull(); } //! reads parameter <nump> of record <num> into a Field, //! controlled by a Parameter Descriptor (PDescr), which controls //! its allowed type(s) and value //! <ach> is filled if the read parameter does not match its //! description (but the field is read anyway) //! If the description is not defined, no control is done //! Returns True when done Standard_EXPORT Standard_Boolean ReadField (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const Handle(StepData_PDescr)& descr, StepData_Field& fild) const; //! reads a list of fields controlled by an ESDescr Standard_EXPORT Standard_Boolean ReadList (const Standard_Integer num, Handle(Interface_Check)& ach, const Handle(StepData_ESDescr)& descr, StepData_FieldList& list) const; //! Reads parameter <nump> of record <num> into a Transient Value //! according to the type of the parameter : //! Named for Integer,Boolean,Logical,Enum,Real : SelectNamed //! Immediate Integer,Boolean,Logical,Enum,Real : SelectInt/Real //! Text : HAsciiString //! Ident : the referenced Entity //! Sub-List not processed, see ReadSub //! This value is controlled by a Parameter Descriptor (PDescr), //! which controls its allowed type and value //! <ach> is filled if the read parameter does not match its //! description (the select is nevertheless created if possible) //! //! Warning : val is in out, hence it is possible to predefine a specific //! SelectMember then to fill it. If <val> is Null or if the //! result is not a SelectMember, val itself is returned a new ref //! For a Select with a Name, <val> must then be a SelectNamed Standard_EXPORT Standard_Boolean ReadAny (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const Handle(StepData_PDescr)& descr, Handle(Standard_Transient)& val) const; //! reads parameter <nump> of record <num> as a sub-list of //! two Reals X,Y. Returns True if OK. Else, returns false and //! feeds Check with appropriate Fails (parameter not a sub-list, //! not two Reals in the sub-list) composed with "mess" which //! gives the name of the parameter Standard_EXPORT Standard_Boolean ReadXY (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Real& X, Standard_Real& Y) const; //! reads parameter <nump> of record <num> as a sub-list of //! three Reals X,Y,Z. Return value and Check managed as by //! ReadXY (demands a sub-list of three Reals) Standard_EXPORT Standard_Boolean ReadXYZ (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Real& X, Standard_Real& Y, Standard_Real& Z) const; //! reads parameter <nump> of record <num> as a single Real value. //! Return value and Check managed as by ReadXY (demands a Real) Standard_EXPORT Standard_Boolean ReadReal (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Real& val) const; //! Reads parameter <nump> of record <num> as a single Entity. //! Return value and Check managed as by ReadReal (demands a //! reference to an Entity). In Addition, demands read Entity //! to be Kind of a required Type <atype>. //! Remark that returned status is False and <ent> is Null if //! parameter is not an Entity, <ent> remains Not Null is parameter //! is an Entity but is not Kind of required type Standard_EXPORT Standard_Boolean ReadEntity (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const Handle(Standard_Type)& atype, Handle(Standard_Transient)& ent) const; //! Safe variant for arbitrary type of argument template <class T> Standard_Boolean ReadEntity (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const Handle(Standard_Type)& atype, Handle(T)& ent) const { Handle(Standard_Transient) anEnt = ent; return ReadEntity (num, nump, mess, ach, atype, anEnt) && ! (ent = Handle(T)::DownCast(anEnt)).IsNull(); } //! Same as above, but a SelectType checks Type Matching, and //! records the read Entity (see method Value from SelectType) Standard_EXPORT Standard_Boolean ReadEntity (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, StepData_SelectType& sel) const; //! reads parameter <nump> of record <num> as a single Integer. //! Return value & Check managed as by ReadXY (demands an Integer) Standard_EXPORT Standard_Boolean ReadInteger (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Integer& val) const; //! reads parameter <nump> of record <num> as a Boolean //! Return value and Check managed as by ReadReal (demands a //! Boolean enum, i.e. text ".T." for True or ".F." for False) Standard_EXPORT Standard_Boolean ReadBoolean (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Boolean& flag) const; //! reads parameter <nump> of record <num> as a Logical //! Return value and Check managed as by ReadBoolean (demands a //! Logical enum, i.e. text ".T.", ".F.", or ".U.") Standard_EXPORT Standard_Boolean ReadLogical (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, StepData_Logical& flag) const; //! reads parameter <nump> of record <num> as a String (text //! between quotes, quotes are removed by the Read operation) //! Return value and Check managed as by ReadXY (demands a String) Standard_EXPORT Standard_Boolean ReadString (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Handle(TCollection_HAsciiString)& val) const; Standard_EXPORT Standard_Boolean ReadEnumParam (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_CString& text) const; //! Fills a check with a fail message if enumeration value does //! match parameter definition //! Just a help to centralize message definitions Standard_EXPORT void FailEnumValue (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach) const; //! Reads parameter <nump> of record <num> as an Enumeration (text //! between dots) and converts it to an integer value, by an //! EnumTool. Returns True if OK, false if : this parameter is not //! enumeration, or is not recognized by the EnumTool (with fail) Standard_EXPORT Standard_Boolean ReadEnum (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const StepData_EnumTool& enumtool, Standard_Integer& val) const; //! Resolves a parameter which can be enclosed in a type def., as //! TYPE(val). The parameter must then be read normally according //! its type. Parameter to be resolved is <nump> of record <num> //! <mustbetyped> True demands a typed parameter //! <mustbetyped> False accepts a non-typed parameter as option //! mess and ach as usual //! <numr>,<numrp> are the resolved record and parameter numbers //! = num,nump if no type, else numrp=1 //! <typ> returns the recorded type, or empty string //! Remark : a non-typed list is considered as "non-typed" Standard_EXPORT Standard_Boolean ReadTypedParam (const Standard_Integer num, const Standard_Integer nump, const Standard_Boolean mustbetyped, const Standard_CString mess, Handle(Interface_Check)& ach, Standard_Integer& numr, Standard_Integer& numrp, TCollection_AsciiString& typ) const; //! Checks if parameter <nump> of record <num> is given as Derived //! If this Check is successful (i.e. Param = "*"), returns True //! Else, fills <ach> with a Message which contains <mess> and //! returns False. According to <errstat>, this message is Warning //! if errstat is False (Default), Fail if errstat is True Standard_EXPORT Standard_Boolean CheckDerived (const Standard_Integer num, const Standard_Integer nump, const Standard_CString mess, Handle(Interface_Check)& ach, const Standard_Boolean errstat = Standard_False) const; //! Returns total count of Entities (including Header) Standard_EXPORT virtual Standard_Integer NbEntities() const Standard_OVERRIDE; //! determines the first suitable record following a given one //! that is, skips SCOPE,ENDSCOPE and SUBLIST records //! Note : skips Header records, which are accessed separately Standard_EXPORT Standard_Integer FindNextRecord (const Standard_Integer num) const Standard_OVERRIDE; //! determines reference numbers in EntityNumber fields //! called by Prepare from StepReaderTool to prepare later using //! by a StepModel. This method is attached to StepReaderData //! because it needs a massive amount of data accesses to work //! //! If <withmap> is given False, the basic exploration algorithm //! is activated, otherwise a map is used as far as it is possible //! this option can be used only to test this algorithm Standard_EXPORT void SetEntityNumbers (const Standard_Boolean withmap = Standard_True); //! determine first suitable record of Header //! works as FindNextRecord, but treats only Header records Standard_EXPORT Standard_Integer FindNextHeaderRecord (const Standard_Integer num) const; //! Works as SetEntityNumbers but for Header : more simple because //! there are no Reference, only Sub-Lists Standard_EXPORT void PrepareHeader(); //! Returns the Global Check. It can record Fail messages about //! Undefined References (detected by SetEntityNumbers) Standard_EXPORT const Handle(Interface_Check) GlobalCheck() const; DEFINE_STANDARD_RTTIEXT(StepData_StepReaderData,Interface_FileReaderData) protected: private: //! Searches for a Parameter of the record <num>, which refers to //! the Ident <id> (form #nnn). [Used by SetEntityNumbers] //! If found, returns its EntityNumber, else returns Zero. Standard_EXPORT Standard_Integer FindEntityNumber (const Standard_Integer num, const Standard_Integer id) const; //! Prepare string to use in OCCT exchange structure. //! If code page is Resource_FormatType_NoConversion, //! clean only special characters without conversion; //! else convert a string to UTF8 using the code page //! and handle the control directives. Standard_EXPORT void cleanText(const Handle(TCollection_HAsciiString)& theVal) const; private: TColStd_Array1OfInteger theidents; TColStd_Array1OfInteger thetypes; Interface_IndexedMapOfAsciiString thenametypes; TColStd_DataMapOfIntegerInteger themults; Standard_Integer thenbents; Standard_Integer thelastn; Standard_Integer thenbhead; Standard_Integer thenbscop; Handle(Interface_Check) thecheck; Resource_FormatType mySourceCodePage; }; #endif // _StepData_StepReaderData_HeaderFile
#include <iostream> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/strand.hpp> #include <boost/make_shared.hpp> #include <boost/bind.hpp> #include "SG_ServerBase.h" #include "SG_Config.h" #include "SG_ClientSession.h" #include "Tools/SG_DataConverter.h" #include "Packets/PacketBaseMessage.h" #include "Tools/SG_Logger.h" MySQLConnection *SG_ClientSession::SQLConn = nullptr; SG_Config *SG_ClientSession::conf = nullptr; RC4Cipher cachedCipher("}h79q~B%al;k'y $E"); SG_ClientSession::SG_ClientSession(boost::asio::io_service &rService, boost::asio::strand &rStrand, boost::shared_ptr<SG_ServerBase> pServer): m_Socket(rService), m_Strand(rStrand), m_Server(pServer), m_SocketTimout(rService), m_Player(boost::make_shared<SG_Client>()) { Socketstatus = false; initRC4Cipher(); } SG_ClientSession::~SG_ClientSession() { initRC4Cipher(); } // ------------------------------------------------------------------ // boost::asio::ip::tcp::socket& SG_ClientSession::getSocket() { return m_Socket; } void SG_ClientSession::StartConnection() { if (!m_Server->OnClientConnected(shared_from_this())) return SG_ClientSession::DisconnectClient(); m_Strand.post(boost::bind(&SG_ClientSession::Read, shared_from_this())); m_SocketTimout.expires_from_now(boost::posix_time::milliseconds(conf->SocketTimeout)); m_SocketTimout.async_wait(m_Strand.wrap(boost::bind(&SG_ClientSession::HandleTimeout, shared_from_this()))); } void SG_ClientSession::DisconnectClient() { m_SocketTimout.cancel(); m_Server->OnClientDisconnect(shared_from_this()); boost::system::error_code ec; m_Socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); m_Socket.close(); } void SG_ClientSession::SendPacketStruct(const TS_MESSAGE* packet) { boost::asio::async_write(m_Socket, boost::asio::buffer(packet,packet->size), m_Strand.wrap(boost::bind(&SG_ClientSession::HandleSend, shared_from_this(), boost::asio::placeholders::error))); } // ------------------------------------------------------------------ // void SG_ClientSession::Read() { boost::shared_ptr<std::vector<uint8_t>> pBuffer(new std::vector<uint8_t>(sizeof(uint16_t))); boost::asio::async_read(m_Socket, boost::asio::buffer(*pBuffer, conf->MaxPacketSize), boost::asio::transfer_exactly(sizeof(uint16_t)), m_Strand.wrap(boost::bind(&SG_ClientSession::HandleRecvHeader, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, pBuffer))); } void SG_ClientSession::HandleRecvHeader(const boost::system::error_code &rEC, std::size_t stSize, boost::shared_ptr<std::vector<uint8_t>> pBuffer) { if (rEC || !stSize) return SG_ClientSession::DisconnectClient(); Socketstatus = true; m_SocketTimout.expires_from_now(boost::posix_time::milliseconds(conf->SocketTimeout)); uint16_t Packetsize = *reinterpret_cast<uint16_t *>(pBuffer->data()); if (Packetsize < conf->MinPacketSize || Packetsize > conf->MaxPacketSize) { std::cout << "Packetsize is not in valid space [" << Packetsize << "]" << std::endl; //return SG_ClientSession::DisconnectClient(); } pBuffer->clear(); pBuffer->resize(Packetsize); boost::asio::async_read(m_Socket, boost::asio::buffer(*pBuffer, Packetsize - sizeof(uint16_t)), boost::asio::transfer_exactly(Packetsize - sizeof(uint16_t)), m_Strand.wrap(boost::bind(&SG_ClientSession::HandleRecvBody, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, pBuffer))); } void SG_ClientSession::HandleRecvBody(const boost::system::error_code &rEC, std::size_t stSize, boost::shared_ptr<std::vector<uint8_t>> pBuffer) { //boost::shared_ptr<SG_MemoryReader> pReader(new SG_MemoryReader(pBuffer)); pBuffer->insert(pBuffer->begin(), static_cast<uint8_t>(stSize & 0xff)); pBuffer->insert(pBuffer->begin() + 1, static_cast<uint8_t>((stSize >> 8) & 0xff)); TS_MESSAGE* pack = reinterpret_cast<TS_MESSAGE*>(pBuffer->data()); if (!m_Server->OnPacketReceived(shared_from_this(), pack)) return SG_ClientSession::DisconnectClient(); pBuffer->clear(); m_Strand.post(boost::bind(&SG_ClientSession::Read, shared_from_this())); } void SG_ClientSession::HandleSend(const boost::system::error_code &rEC) { if (rEC) { std::cout << "[" << __FUNCTION__ << "] Boost error [" << rEC << "]" << std::endl; SG_ClientSession::DisconnectClient(); } } void SG_ClientSession::HandleTimeout() { if (m_SocketTimout.expires_at() <= boost::asio::deadline_timer::traits_type::now()) { if (Socketstatus) { Socketstatus = false; } else { //std::cout << "[" << __FUNCTION__ << "] Client socket timeout" << std::endl; return SG_ClientSession::DisconnectClient(); } m_SocketTimout.expires_from_now(boost::posix_time::milliseconds(conf->SocketTimeout)); } m_SocketTimout.async_wait(m_Strand.wrap(boost::bind(&SG_ClientSession::HandleTimeout, shared_from_this()))); } void SG_ClientSession::initRC4Cipher() { outputEnc = inputEnc = cachedCipher; }
#ifndef CHAINE_HPP #define CHAINE_HPP #include <cstring> class Chaine { private: char* _donnees; unsigned int _taille; public: Chaine(); Chaine(const char*); Chaine(const Chaine&); ~Chaine(); void debug() const; unsigned int taille()const; char get(unsigned int i); const Chaine& operator=(const Chaine&); //char operator[](unsigned int index); char& operator[](unsigned int index); const Chaine operator+(const Chaine&); operator const char*() const; }; #endif
/*********************************************************************** h£ºHash table (spatial hashing) which can be used in vertex-clustering scenarios, like vertex-welding , mesh simplification based on vertex clustering ************************************************************************/ #pragma once namespace Noise3D { //hash table designed for vertex clustering (e.g. in mesh simplification) //so every unitBox will only has one 3D point that represent the AVERAGE vertex //of this vertex cluster. class CSpatialHashTableForVertexClustering { public: CSpatialHashTableForVertexClustering( float unitBoxWidth, float unitBoxHeight,float unitBoxDepth, int bucketCount=256); //1.vector p will be added to corresponding unit box //2.input one triangle at a time to prevent de-generating circumstances at the beginning //3.new vertex&index lists of a mesh will be generated //void AddPoint(NVECTOR3 p,UINT vertexIndex); void AddPoint(N_DefaultVertex v1, N_DefaultVertex v2, N_DefaultVertex v3); bool IsUnitBoxEmpty(NVECTOR3 p); bool IsUnitBoxEmpty(int idX, int idY,int idZ);//integer index of unit box NVECTOR3 GetAveragePosition(int unitBoxIdX, int unitBoxIdY, int unitBoxIdZ); //get all average position vector void GetSimpifiedMesh(std::vector<N_DefaultVertex>& outVertexList,std::vector<UINT>& outIndexList); private: int mBucketCount; float mUnitBoxWidth; float mUnitBoxHeight; float mUnitBoxDepth; struct N_UnitBox { UINT boxIndexX; UINT boxIndexY; UINT boxIndexZ; N_DefaultVertex avgVertex; UINT vertexIndex; }; typedef std::vector<N_UnitBox> N_Bucket; std::vector<N_Bucket>* m_pBucketList;//all unitBoxes in the Buckets will overlap the whole space }; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef XSLT_H #define XSLT_H #ifdef XSLT_SUPPORT #include "modules/logdoc/logdocenum.h" #include "modules/xmlutils/xmllanguageparser.h" #include "modules/xmlutils/xmlnames.h" #include "modules/xmlutils/xmlparser.h" #include "modules/xmlutils/xmltreeaccessor.h" #include "modules/xmlutils/xmltokenhandler.h" #include "modules/xpath/xpath.h" #include "modules/url/url2.h" class XSLT_Stylesheet; /** Parser for XSLT stylesheets. Create using the Make() function, destroy using the Free() function, and fetch the parsed XSLT stylesheet using the GetStylesheet() function, after successful parsing. See the documentation for XMLLanguageParser in the xmlutils module for details about how to parse using an XMLLanguageParser-based parser. */ class XSLT_StylesheetParser : public XMLLanguageParser { public: class Callback { public: virtual OP_STATUS LoadOtherStylesheet(URL stylesheet_url, XMLTokenHandler *token_handler, BOOL is_import); /**< Called when the stylesheet parser encounters an xsl:import (is_import == TRUE) or xsl:include (is_import == FALSE) directive and wants to load another stylesheet. The implementation has two choices: start loading and parsing the requested resource in such a way that the supplied token handler receives the resource's tokens, or refuse. Refusal is signalled by returning OpStatus::ERR, in which case the whole stylesheet parsing will fail. OpStatus::OK signals that the requested resource is being loaded. If the request is refused, the XSLT stylesheet parser will *not* report any error to the message console; it will just stop. The default implementation refuses the request without reporting any errors, and should normally not be used. @param parser XSLT stylesheet parser. @param stylesheet_url URL of additional stylesheet to load. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual void CancelLoadOtherStylesheet(XMLTokenHandler *token_handler); /**< Cancel a previous call to CancelLoadOtherStylesheet(). The token handler should be used to identify which call to cancel. The cancelling must be such that it is okay to delete the token handler directly after this function returns. @param token_handler Token handler. */ #ifdef XSLT_ERRORS /** Message type used for HandleMessage(). */ enum MessageType { MESSAGE_TYPE_ERROR, /**< Fatal error that will cause the parsing to fail. */ MESSAGE_TYPE_WARNING /**< Warning about an non-fatal error in the stylesheet. */ }; virtual OP_BOOLEAN HandleMessage(MessageType type, const uni_char *message); /**< Called when the stylesheet parser encounters an error, with an error message describing it. If the calling code wants to handle the error message itself, it should return OpBoolean::IS_TRUE, otherwise it should return OpBoolean::IS_FALSE, in which case the stylesheet parser will post an error message to the message console (if FEATURE_CONSOLE is enabled.) This callback is enabled by TWEAK_XSLT_ERRORS. @param type Message type. @param message Error message. No formatting to speak of, but sometimes contains linebreaks. @return OpBoolean::IS_TRUE, OpBoolean::IS_FALSE or OpStatus::ERR_NO_MEMORY. */ #endif // XSLT_ERRORS virtual OP_STATUS ParsingFinished(XSLT_StylesheetParser *parser); /**< Called when the stylesheet parser has finished parsing the stylesheet. The default implementation does nothing. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ protected: virtual ~Callback() {} /**< The callback is not owned by the XSL stylesheet parser, and must be destroyed by the caller after the stylesheet parser has been destroyed. */ }; static OP_STATUS Make(XSLT_StylesheetParser *&parser, Callback *callback); /**< Creates an XSLT parser. */ static void Free(XSLT_StylesheetParser *parser); /**< Destroys an XSLT parser. */ virtual OP_STATUS GetStylesheet(XSLT_Stylesheet *&stylesheet) = 0; /**< Retrieves the parsed stylesheet and resets the parser. */ protected: ~XSLT_StylesheetParser(); /**< Use XSLT_StylesheetParser::Free to free stylesheet parsers. */ }; class XSLT_Stylesheet { public: static void Free(XSLT_Stylesheet *stylesheet); /**< Destroys an XSLT stylesheet. All transformations based on this stylesheet must be stopped before the stylesheet is destroyed. */ /** Class representing the input to a transformation, essentially the source tree and any supplied parameter values. The referenced XMLTreeAccessor object is not owned by the Input object; it needs to be freed separately by the calling code. The 'parameters' array along with any parameter values is however owned by the Input object and is freed by its destructor. */ class Input { public: Input(); /**< Constructor. Sets all members to NULL or zero. */ ~Input(); /**< Destructor. Deletes the 'parameters' array, but no other objects. */ XMLTreeAccessor *tree; /**< Source tree accessor. */ XMLTreeAccessor::Node *node; /**< Source node. */ class Parameter { public: Parameter(); /**< Constructor. Sets all members to NULL or zero. */ class Value { public: virtual ~Value() {} static OP_STATUS MakeNumber(Value *&result, double value); static OP_STATUS MakeBoolean(Value *&result, BOOL value); static OP_STATUS MakeString(Value *&result, const uni_char *value); static OP_STATUS MakeNode(Value *&result, XPathNode *value); static OP_STATUS MakeNodeList(Value *&result); virtual OP_STATUS AddNodeToList(XPathNode *value) = 0; }; XMLExpandedName name; /**< Parameter name. */ Value *value; /**< Parameter value. */ }; Parameter *parameters; /**< Parameters to the transformation. Can be NULL if there are no parameters at all. */ unsigned parameters_count; /**< Number of used elements in the 'parameters' array. */ }; /** Output characteristics specified by the stylesheet. The strings are owned by the stylesheet and are valid until the stylesheet is destroyed. */ class OutputSpecification { public: enum Method { METHOD_XML, METHOD_HTML, METHOD_TEXT, METHOD_UNKNOWN // HTML or XML depending on transform result }; Method method; const uni_char *version; const uni_char *encoding; BOOL omit_xml_declaration; XMLStandalone standalone; const uni_char *doctype_public_id; const uni_char *doctype_system_id; const uni_char *media_type; }; /** Output form. Note: the availability and meaning of the output forms varies somewhat depending on the output method specified in the stylesheet, but they are otherwise independent. Selecting a certain output form is never an alternative to specifying a certian output method in the stylesheet; the output form does not override the output method of the stylesheet. */ enum OutputForm { OUTPUT_XMLTOKENHANDLER, /**< Produce output the the form of XMLToken objects sent to a supplied XMLTokenHandler object. Only available for stylesheets with the output method 'xml.' An XMLTokenHandler must be set trough a call to the Transformation::SetXMLTokenHandler() function before the first call to Transformation::Transform(). */ OUTPUT_STRINGDATA, /**< Produce output in the form of string data. If the output method of the stylesheet is 'text,' the resulting string data is the result text, otherwise the string data is the serialization of the result tree. The string data is produced in chunks and sent to a string collection callback that must be set through a call to the Transformation::SetStringCollector() function before the first call to Transformation::Transform(). */ OUTPUT_DELAYED_DECISION /**< If the resulting type of the output can't be determined statically this can be used, and neither a token handler nor a string collector set. The call to Transform will then return with TRANSFORM_NEEDS_OUTPUTHANDLER and the resulting type can be read from the Transformation object. The user must then call SetDelayedOutputForm() and set either a token handler or a string collector. */ }; /** Interface representing an ongoing transformation. */ class Transformation { public: /**< Transformation status codes. */ enum Status { TRANSFORM_PAUSED, /**< The transformation paused but can be continued immediately. If possible, the calling code should let Opera process pending messages before it continues the transformation. */ TRANSFORM_BLOCKED, /**< The transformation is blocked waiting for something external to the XSLT transformation (such as the loading of an XML document or the evaluation of an XPath expression.) The calling code should continue the transformation when its callback is called. It should set a callback if it hasn't already done so. */ TRANSFORM_NEEDS_OUTPUTHANDLER, /**< This can returned from Transform() if the tranformation was started with the OUTPUT_DELAYED_DECISION outputform. */ TRANSFORM_FINISHED, /**< The transformation has finished successfully. */ TRANSFORM_FAILED, /**< The transformation failed. An error will have been reported to the message console (if it is enabled.) */ TRANSFORM_NO_MEMORY /**< The transformation failed due to an OOM error. */ }; virtual Status Transform() = 0; /**< Start or continue the transformation. If TRANSFORM_PAUSED is returned, the transformation is ready to continue immediately after a call. The same is true if TRANSFORM_NEEDS_OUTPUTHANDLER is returned, but before any further calls to Transform a output handler must be set. This return value will only be returned once and only it the OUTPUT_DELAYED_DECISION outputform was specified. If TRANSFORM_BLOCKED is returned, the transformation cannot continue now, and the callback will be called when it can continue. Once TRANSFORM_FINISHED or TRANSFORM_FAILED has been returned, the transformation has stopped, and this function will return the same value if called again. If TRANSFORM_NO_MEMORY is returned, it may be possible to continue the transformation later, assuming some memory has become available then. If not, STATUS_FAILED will be returned the next time this function is called. */ class Callback { public: virtual void ContinueTransformation(Transformation *transformation) = 0; /**< Called when a previously blocked transformation is ready to be continued. The transformation cannot be continued immediately during this call however; a message should be posted that continues the transformation. */ virtual OP_STATUS LoadDocument(URL document_url, XMLTokenHandler *token_handler) = 0; /**< Called when the document() function is called and a document needs to be loaded. The document URL should be loaded and parsed in such a way that the parsed tokens are fed into the supplied token handler. The token handler is owned by the XSLT module internally, and should not be freed by anyone else. If access to the resource is not permitted, OpStatus::ERR can be returned. The document() function will then return an empty nodeset. @param document_url URL to load. @param token_handler Token handler. @param OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual void CancelLoadDocument(XMLTokenHandler *token_handler) {} /**< Called to cancel a previous call to LoadDocument(). The token handler should be used to identify which call to cancel. The cancelling must be such that it is okay to delete the token handler directly after this function returns. @param token_handler Token handler. */ #ifdef XSLT_ERRORS /** Message type used for HandleMessage(). */ enum MessageType { MESSAGE_TYPE_ERROR, /**< Fatal error that will cause the transformation to be aborted. This includes messages triggered by instantiating an xsl:message element whose 'terminate' attribute has the value 'yes'. */ MESSAGE_TYPE_WARNING, /**< Warning about an non-fatal error in the stylesheet. */ MESSAGE_TYPE_MESSAGE /**< Message triggered by instantiating an xsl:message element whose 'terminate' attribute does not have the value 'yes'. */ }; virtual OP_BOOLEAN HandleMessage(MessageType type, const uni_char *message); /**< Called when a transformation encounters a fatal error and aborts, when it encounters a non-fatal error and warns about it or when it instantiates an xsl:message element. The 'type' argument indicates which. If the calling code wants to handle the error message itself, it should return OpBoolean::IS_TRUE, otherwise it should return OpBoolean::IS_FALSE, in which case the XSLT engine will post an error message to the message console (assuming FEATURE_CONSOLE is enabled.) This callback is enabled by TWEAK_XSLT_ERRORS. @param type Message type. @param message Message. No formatting to speak of, but sometimes contains linebreaks. @return OpBoolean::IS_TRUE, OpBoolean::IS_FALSE or OpStatus::ERR_NO_MEMORY. */ #endif // XSLT_ERRORS protected: virtual ~Callback() {} /**< Destructor. The callback object is not owned by the transformation and is not deleted by it. */ }; virtual void SetCallback(Callback *callback) = 0; /**< Set a callback that is notified when the transformation is ready be continued after being blocked. The callback is not owned by the transformation and will not be deleted by it. */ /* Output handling. */ virtual void SetDefaultOutputMethod(OutputSpecification::Method method) = 0; /**< Sets the default output method, if one isn't specified in the stylesheet. Normally, the default output method is determined dynamicly depending on the root element in the result tree according to rules specified in the XSLT specification. If this function is used to set an explicit default output method, those rules are set aside, but an explicit output method specified in the stylesheet is honoured if present. */ virtual void SetDelayedOutputForm(OutputForm outputform) = 0; /**< This method must be used when transform was started with the OUTPUT_DELAYED_DECISION outputform and the Transform() call returned with TRANSFORM_NEEDS_OUTPUTHANDLER. This should be followed by a call to SetXMLTokenHandler or SetStringDataCollector. */ virtual OutputSpecification::Method GetOutputMethod() = 0; /**< Returns the actual output method. Should be called after a Transform with output form OUTPUT_DELAYED_DECISION has stopped with TRANSFORM_NEEDS_OUTPUTHANDLER and will then be one of the values in the enum, except for the METHOD_UNKNOWN. */ virtual void SetXMLTokenHandler(XMLTokenHandler *tokenhandler, BOOL owned_by_transformation) = 0; /**< If the output form OUTPUT_XMLTOKENHANDLER was selected, this function must be called before the first call to Transform() to set the token handler to send the output to. The token handler is owned by the Transformation object if the parameter 'owned_by_transformation' is TRUE. In that case it is deleted when the transformation is stopped through a call to XSLT_Stylesheet::StopTransformation. Otherwise, the token handler is owned by the calling code and must remain valid till after the last call to Transform(). It can be deleted before the transformation is stopped; the token handler is never called from XSLT_Stylesheet::StopTransformation(). */ virtual void SetXMLParseMode(XMLParser::ParseMode parsemode) = 0; /**< If the output form OUTPUT_XMLTOKENHANDLER was selected, this function can be called (at the same time that SetXMLTokenHandler() is called, typically) to set the parse mode of the XML parser used to check the well-formedness of the output. The default is PARSEMODE_DOCUMENT. See the documentation for XMLParser::ParseMode for the exact meaning of the different possible values. The XSLT engine makes no interpretation of them itself, it only passes them along to an XMLParser object. */ class StringDataCollector { public: virtual ~StringDataCollector() {} /**< Destructor. */ virtual OP_STATUS CollectStringData(const uni_char *string, unsigned string_length) = 0; /**< Called to collect string data. It is unspecified how often it is called during a transformation; the result may or may not be buffered internally before being sent to the collector. All data will have been sent to the collector before the transformation reports it has been finished. If the collector runs out of memory, it can return OpStatus::ERR_NO_MEMORY, which will cause the current call to Transformation::Transform() to return STATUS_NO_MEMORY, and a subsequent call to Transformation::Transform() to send the same (or more) string data to the string collector again. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ virtual OP_STATUS StringDataFinished() = 0; /**< Called when all string data has been processed. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ }; virtual void SetStringDataCollector(StringDataCollector *collector, BOOL owned_by_transformation) = 0; /**< If the output form OUTPUT_STRINGDATA, this function must be called before the first call to Transform() to set the string data collector to send output to. The string data collector is owned by the Transformation if the parameter 'owned_by_transformation' is TRUE. In that case it is deleted when the transformation is stopped through a call to XSLT_Stylesheet::StopTransformation. Otherwise, the string data collector is owned by the calling code and must remain valid till after the last call to Transform(). It can be deleted before the transformation is stopped; the string data collector is never called from XSLT_Stylesheet::StopTransformation(). */ protected: virtual ~Transformation() {} /**< Destructor. Use XSLT_Stylesheet::StopTransformation() to (stop and) free a transformation. */ }; virtual const OutputSpecification *GetOutputSpecification() = 0; /**< Returns the output characteristics specified by the stylesheet. The returned object is owned by the stylesheet and is valid until the stylesheet is destroyed. */ virtual BOOL ShouldStripWhitespaceIn(const XMLExpandedName &name) = 0; /**< Returns TRUE if whitespace-only text nodes in elements name 'name' should be stripped in the source (input) tree. The lookup can be considered quick enough that there is no need for caching of the result (beyond the trivial.) If 'name' is empty (as made by default constructor) TRUE is returned whitespace should be stripped in any elements at all. This can be used to determine whether the source document needs to be traversed at all. @return TRUE or FALSE. */ virtual OP_STATUS StartTransformation(Transformation *&transformation, const Input &input, OutputForm outputform) = 0; /**< Start a transformation that applies this stylesheet to the source tree specified in 'input' and produces output in the form requested through 'outputform.' The transformation is only initialized by this function, no output will be produced until the function Transformation::Transform() is called. The stylesheet can be freed after this has finished successfully. */ static OP_STATUS StopTransformation(Transformation *transformation); /**< Stop a transformation and destroy it. No output is produced during a call to this function, and none of the callbacks set on the transformation are called. Any objects owned by the transformation are destroyed. */ protected: virtual ~XSLT_Stylesheet(); /**< Use XSLT_Stylesheet::Free() to free stylesheets. */ }; /* Enabled by API_XSLT_HANDLER. */ #ifdef XSLT_HANDLER_SUPPORT /** Interface for handling XSLT inclusion and application while loading an XML document. To use, sub-class this interface, create a token handler using XSLT_Handler::MakeTokenHandler() and parse the XML document using that token handler. */ class XSLT_Handler { public: static OP_STATUS MakeTokenHandler(XMLTokenHandler *&token_handler, XSLT_Handler *handler); virtual ~XSLT_Handler(); /**< Destructor. */ virtual URL GetDocumentURL() = 0; /**< Called to retrieve the URL of the XML document being parsed. Needed to resolve the 'href' attribute of any xml-stylesheet processing instructions found. */ enum ResourceType { RESOURCE_LINKED_STYLESHEET, /**< Stylesheet linked via an xml-stylesheet processing instruction in the source document. */ RESOURCE_IMPORTED_STYLESHEET, /**< Stylesheet imported by an xsl:import element in another stylesheet already being parsed. */ RESOURCE_INCLUDED_STYLESHEET, /**< Stylesheet included by an xsl:include element in another stylesheet already being parsed. */ RESOURCE_LOADED_DOCUMENT /**< Arbitrary XML document loaded via the document() function. */ }; virtual OP_STATUS LoadResource(ResourceType resource_type, URL resource_url, XMLTokenHandler *token_handler) = 0; /**< Called when an additional resource needs to be loaded. The resource URL should be loaded and parsed in such a way that the parsed tokens are fed into the supplied token handler. The token handler is owned by the XSLT module internally, and should not be freed by anyone else. If access to the resource is not permitted, OpStatus::ERR can be returned. If the resource type is RESOURCE_LINKED_STYLESHEET, this means the processing instruction is ignored, and the document is loaded "unstyled" unless another processing instruction is found. If the resource type is RESOURCE_IMPORTED_STYLESHEET or RESOURCE_INCLUDED_STYLESHEET, the parsing of the whole stylesheet will fail. If the resource type is RESOURCE_LOADED_DOCUMENT, the effect will be the same as if the resource had been empty. @param resource_type Type of resource to load. @param resource_url URL of resource to load. @param token_handler Token handler. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual void CancelLoadResource(XMLTokenHandler *token_handler) {} /**< Called to cancel a previous call to LoadResource(). The token handler should be used to identify which call to cancel. The cancelling must be such that it is okay to delete the token handler directly after this function returns. @param token_handler Token handler.*/ /**< Tree collector interface. Should be implemented together with the XSLT_Handler interface. */ class TreeCollector { public: virtual ~TreeCollector() {} /**< Destructor. The tree collector will be destroyed when the tree is no longer needed, or if XSLT processing is aborted early. */ virtual XMLTokenHandler *GetTokenHandler() = 0; /**< Called to retrieve a token handler that will be called to process the tokens that make up the tree to collect. The token handler is owned by the tree collector. @return A token handler object. */ virtual void StripWhitespace(XSLT_Stylesheet *stylesheet) = 0; /**< If the stylesheet included any declaration of elements in which whitespace-only text nodes should be stripped, this function is called prior to GetTreeAccessor() to perform the stripping. The implementation should use the function XSLT_Stylesheet::ShouldStripWhitespaceIn() to determine whether whitespace-only text nodes in an element should be stripped or preserved, in addition to preserving such text nodes inside elements with xml:space="preserve" attributes (and descendants of such elements.) */ virtual OP_STATUS GetTreeAccessor(XMLTreeAccessor *&tree_accessor) = 0; /**< Called once to retrieve a tree accessor accessing the collected tree. Will never be called before the token handler returned by GetTokenHandler() has processed a XMLToken::TYPE_Finished token, and thus should have finished collecting the tree. The returned tree accessor will be used throughout the XSLT handling, and must remain valid as long as the tree collector objects is. The tree collector will be destroyed when the tree will no longer be used, at which point the tree collector should destroy the tree accessor and any other data allocated to represent the tree. @param tree_accessor Should be set on success. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ }; virtual OP_STATUS StartCollectingSourceTree(TreeCollector *&tree_collector) = 0; /**< Called to create a tree collector for collecting the source tree, when an XSL stylesheet has been found and is being loaded and applied. The created tree collector is owned by the caller, and will be deleted when the tree it collects is no longer needed. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ virtual OP_STATUS OnXMLOutput(XMLTokenHandler *&tokenhandler, BOOL &destroy_when_finished); /**< Called when this token handler has determined that the actual output is XML tokens. This happens both when no xml-stylesheet processing instructions linking XSL stylesheets are found, and when such are found and the output of the XSL transformation is XML. This function can either refuse to handle XML output by returning OpStatus::ERR, or handle the XML tokens by creating its own token handler, assign it to 'tokenhandler' and return OpStatus::OK. If a token handler is assigned to 'tokenhandler' the argument 'destroy_when_finished' determines who owns it. If TRUE, this object owns the token handler and destroys it whenever it is destroyed. The default implementation of this function returns OpStatus::ERR. @param tokenhandler Should be set to a token handler if OpStatus::OK is returned. @param destroy_when_finished If TRUE, the token handler set to 'tokenhandler' is owned by this object and destroyed automatically. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual OP_STATUS OnHTMLOutput(XSLT_Stylesheet::Transformation::StringDataCollector *&collector, BOOL &destroy_when_finished); /**< Called when this token handler has determined that the actual output is HTML source code. This happens only when a xml-stylesheet processing instruction has been found and the output of the XSL transformation is HTML. This function can either refuse to handle HTML output by returning OpStatus::ERR, or handle it by supplying a string data collector that processes the HTML source code appropriately. If a string data collector is assigned to 'collector' the argument 'destroy_when_finished' determines who owns it. If TRUE, this object owns the string data collector and destroys it whenever it is destroyed. The default implementation of this function returns OpStatus::ERR. @param collector Should be set to a string data collector if OpStatus::OK is returned. @param destroy_when_finished If TRUE, the string data collector set to 'collector' is owned by this object and destroyed automatically. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual OP_STATUS OnTextOutput(XSLT_Stylesheet::Transformation::StringDataCollector *&collector, BOOL &destroy_when_finished); /**< Called when this token handler has determined that the actual output is plain text. This happens only when a xml-stylesheet processing instruction has been found and the output of the XSL transformation is text. This function can either refuse to handle text output by returning OpStatus::ERR, or handle it by supplying a string data collector that processes the text data appropriately. If a string data collector is assigned to 'collector' the argument 'destroy_when_finished' determines who owns it. If TRUE, this object owns the string data collector and destroys it whenever it is destroyed. The default implementation of this function returns OpStatus::ERR. @param collector Should be set to a string data collector if OpStatus::OK is returned. @param destroy_when_finished If TRUE, the string data collector set to 'collector' is owned by this object and destroyed automatically. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ virtual void OnFinished() = 0; /**< Called when everything this token handler is going to do has been done. If a token handler created via OnXMLOutput() has been used, it will have received its XMLToken::TYPE_Finished token by now. If a string data collector created via OnHTMLOutput() or OnTextOutput() has been used, it will have received all data. */ virtual void OnAborted() = 0; /**< Called if the loading, parsing or transforming performed by this token handler is aborted. */ #ifdef XSLT_ERRORS /** Message type used for HandleMessage(). */ enum MessageType { MESSAGE_TYPE_ERROR, /**< Fatal error that will cause the transformation to be aborted. This includes messages triggered by instantiating an xsl:message element whose 'terminate' attribute has the value 'yes'. */ MESSAGE_TYPE_WARNING, /**< Warning about an non-fatal error in the stylesheet. */ MESSAGE_TYPE_MESSAGE /**< Message triggered by instantiating an xsl:message element whose 'terminate' attribute does not have the value 'yes'. */ }; virtual OP_BOOLEAN HandleMessage(MessageType type, const uni_char *message); /**< Called when the XSLT engine encounters an error, with an error message describing it. If the calling code wants to handle the error message itself, it should return OpBoolean::IS_TRUE, otherwise it should return OpBoolean::IS_FALSE, in which case the XSLT engine will post an error message to the message console (if FEATURE_CONSOLE is enabled.) This callback is enabled by TWEAK_XSLT_ERRORS. @param type Message type. @param message Error message. No formatting to speak of, but sometimes contains linebreaks. @return OpBoolean::IS_TRUE, OpBoolean::IS_FALSE or OpStatus::ERR_NO_MEMORY. */ #endif // XSLT_ERRORS }; #endif // XSLT_SOURCETREETOKENHANDLER_SUPPORT #endif // XSLT_SUPPORT #endif // XSLT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2009-2011 * * WebGL GLSL compiler -- dumping output. * */ #ifndef WGL_PRINTER_STDIO_H #define WGL_PRINTER_STDIO_H #ifdef WGL_STANDALONE #include "modules/webgl/src/wgl_printer.h" class WGL_StdioPrinter : public WGL_Printer { public: WGL_StdioPrinter(FILE *f, BOOL gl_es, BOOL highp, BOOL flag = FALSE) : WGL_Printer(gl_es, highp) , fp(f) , owns_file(flag) { } virtual ~WGL_StdioPrinter() { if (owns_file) fclose(fp); } virtual void OutInt(int i); virtual void OutDouble(double d); virtual void OutBool(BOOL b); virtual void OutString(const char *s); virtual void OutString(uni_char *s); virtual void OutString(const uni_char *s); virtual void OutStringId(const uni_char *s); virtual void OutString(WGL_VarName *s); virtual void OutNewline(); virtual void Flush(BOOL as_error); private: FILE *fp; BOOL owns_file; /**< TRUE => printer has ownership of FILE and must close on delete. */ }; #endif // WGL_STANDALONE #endif // WGL_PRINTER_STDIO_H
#define _USE_MATH_DEFINES #include <cmath> #include <iostream> #ifndef TRIANGLE_H #define TRIANGLE_H #include "Shape.h" class Triangle: public Shape { protected: double height; double base; public: Triangle( int newX = 0, int newY= 0, int newSize = 0, double h = 0, double b = 0) : Shape(newX,newY,newSize) , height(h), base(b) { } void draw() const { cout << " * \n" << " * * \n" << " * * \n" << " * * \n" << "* * * * * * * * \n" << endl; } double area() { return base * height / 2.0; } ~Triangle(){} }; #endif /* TRIANGLE_H */
#pragma once #include "../../system.hpp" #include <memory> namespace sbg{ struct CollisionEntity; struct ResultData; struct CollisionTester : Clonable { virtual std::pair<std::unique_ptr<ResultData>, bool> test(std::shared_ptr<const CollisionEntity> self, std::shared_ptr<const CollisionEntity> other) const = 0; CollisionTester* clone() const override = 0; }; }
/******************************************************************************************* * Student: Vikram Singh StudentID: 11491025 * * Class: CptS 122, Fall 2016; Lab Section 5 * * Programming Assignment: Programming Assignment 5 * * Date: February 21, 2016 * * Description: Writing a program that will manage student data * *******************************************************************************************/ //gaurd code #pragma once //error handler for ctime #define _CRT_SECURE_NO_WARNINGS //Include standard libraries #include <iostream> #include <stdlib.h> #include <fstream> #include <string> #include <ctime> //Include local libararies #include "node.h" //include easier use for following using namespace std; using std::cout; using std::endl; using std::cin; using std::string; using std::fstream; using std::ifstream; using std::ofstream; class List { //public functions public: //construct and destructor List() { this->mphead = nullptr; } ~List(){ deleteDataStructure(this->mphead); } //main logic void runApp(void); //data structure caller void printList(void); void printListRecInOrder(void) { printListRecInOrder(this->mphead); } //private functions private: //private vars Node *mphead; //pointer to start of the list Node *& returnHead(void) { return this->mphead; } //getter for var //main functions void printMainMenu(void); //prints menu int mainMenu(void); //logic for main menu void exitProgram(void); //exit for main menu void checkCsvFile(void); //call readInscvfile void readInCsvFile(void); //load from csv file void storeMasterList(void); //store master list to file void writetoFile(ofstream &inpuFileStream, Node* inputNode);//write to file void markAbsences(void); //makr absences void loadMasterListFromFile(void); //load from master.txt void genReports(void); //generate Reports void printReportmenu(void); //prints menu for report int mainSelectorReport(void); //return 1-3 void printAllStudents(void); //prints everything void fileprintAllStudents(ofstream &filehandler, Node* inputNode); //write report to file void printWithSpecificAbs(void); //print with a specific absences void recursivelySpecificsAbs(ofstream &filehandler,Node * head, int compare); //rec to print things void specificDateAbs(void); //will handle specific date void recSpecificDateAbs(ofstream &filehandler, Node* head, string compare); //rec to print things to file void editAbs(void); //edit absences //data structure functions void insertatFront(Node *& head, Data inputData); //insert in order void deleteDataStructure(Node *head); //free memeory void printListRecInOrder(Node *head); //print in order int isEmpty(void) {return !this->mphead;}//check for empty };
// ************* Bridges, articulations points and blocks ************** const int inf = 0x3f3f3f3f; const int maxn = 1 << 10; const int maxe = maxn * maxn; vector<int> g[maxn]; int low[maxn], was[maxn], num[maxn], comp_num[maxn], cur; int n; vector<int> is_bridge[maxn], back[maxn], comp[maxn]; pair<int, int> stck[maxe]; int ssize, comp_cnt, is_art[maxn]; void add_biedge(int u, int v) { back[u].push_back(g[v].size()); back[v].push_back(g[u].size()); g[u].push_back(v); g[v].push_back(u); comp[u].push_back(-1); comp[v].push_back(-1); is_bridge[u].push_back(0); is_bridge[v].push_back(0); } void clear() { for (int i = 0; i < n; ++i) { g[i].clear(); is_bridge[i].clear(); back[i].clear(); comp[i].clear(); } memset(num, -1, sizeof(num)); memset(was, 0, sizeof(was)); cur = comp_cnt = ssize = 0; } // ***** Searching for articulation points ***** void dfs(int v, int par) { was[v] = 1; num[v] = low[v] = cur++; int d = 0, maxlo = -1; for (int i = 0; i < g[v].size(); ++i) { if (g[v][i] == par) continue; if (was[g[v][i]]) { low[v] = min(low[v], num[g[v][i]]); continue; } dfs(g[v][i], v); ++d; maxlo = max(maxlo, low[g[v][i]]); low[v] = min(low[v], low[g[v][i]]); } if (par >= 0) is_art[v] = (maxlo >= num[v]); else is_art[v] = (d > 1); } //Searching for bridges void dfs(int v, int par) { was[v] = 1; num[v] = low[v] = cur++; for (int i = 0; i < g[v].size(); ++i) { is_bridge[v][i] = 0; if (g[v][i] == par) continue; if (was[ g[v][i] ]) { low[v] = min(low[v], num[ g[v][i] ]); continue; } dfs(g[v][i], v); low[v] = min(low[v], low[ g[v][i] ]); if (low[ g[v][i] ] > num[v]) is_bridge[v][i] = 1; } } // ***** Searching for biconnected components ***** void release(int u, int v) { while (ssize --> 0) { int i = stck[ssize].first, j = stck[ssize].second; comp[i][j] = comp[ g[i][j] ][ back[i][j] ] = comp_cnt; if ((i == u && g[i][j] == v) || (i == v && g[i][j] == u)) break; } comp_cnt++; } void dfs(int v, int par) { was[v] = 1; num[v] = low[v] = cur++; for (int i = 0; i < g[v].size(); ++i) { if (g[v][i] == par) continue; if (num[ g[v][i] ] < num[v]) stck[ssize++] = make_pair(v, i); if (was[ g[v][i] ]) { low[v] = min(low[v], num[ g[v][i] ]); continue; } dfs(g[v][i], v); low[v] = min(low[v], low[ g[v][i] ]); if (low[ g[v][i] ] >= num[v]) release(v, g[v][i]); } }
bool visited[MAXN]; int dfs(int u, int fa){//树的直径 visited[u]=1; int fi=0,se=0; for (int i=head[u];~i;i=edge[i].next){ int v=edge[i].to; if(v==fa) continue; int d=dfs(v,u)+1; if(d>fi) se=fi,fi=d; else if(d>se)se=d; } if(fi+se>ans) ans=fi+se; return fi; }
// Created on: 2000-08-22 // Created by: Andrey BETENEV // Copyright (c) 2000-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 _ShapeProcess_ShapeContext_HeaderFile #define _ShapeProcess_ShapeContext_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_DataMapOfShapeShape.hxx> #include <TopAbs_ShapeEnum.hxx> #include <ShapeProcess_Context.hxx> #include <Message_Gravity.hxx> #include <GeomAbs_Shape.hxx> class ShapeExtend_MsgRegistrator; class ShapeBuild_ReShape; class BRepTools_Modifier; class Message_Msg; class ShapeProcess_ShapeContext; DEFINE_STANDARD_HANDLE(ShapeProcess_ShapeContext, ShapeProcess_Context) //! Extends Context to handle shapes //! Contains map of shape-shape, and messages //! attached to shapes class ShapeProcess_ShapeContext : public ShapeProcess_Context { public: Standard_EXPORT ShapeProcess_ShapeContext(const Standard_CString file, const Standard_CString seq = ""); //! Initializes a tool by resource file and shape //! to be processed Standard_EXPORT ShapeProcess_ShapeContext(const TopoDS_Shape& S, const Standard_CString file, const Standard_CString seq = ""); //! Initializes tool by a new shape and clears all results Standard_EXPORT void Init (const TopoDS_Shape& S); //! Returns shape being processed Standard_EXPORT const TopoDS_Shape& Shape() const; //! Returns current result Standard_EXPORT const TopoDS_Shape& Result() const; //! Returns map of replacements shape -> shape //! This map is not recursive Standard_EXPORT const TopTools_DataMapOfShapeShape& Map() const; Standard_EXPORT const Handle(ShapeExtend_MsgRegistrator)& Messages() const; //! Returns messages recorded during shape processing //! It can be nullified before processing in order to //! avoid recording messages Standard_EXPORT Handle(ShapeExtend_MsgRegistrator)& Messages(); Standard_EXPORT void SetDetalisation (const TopAbs_ShapeEnum level); //! Set and get value for detalisation level //! Only shapes of types from TopoDS_COMPOUND and until //! specified detalisation level will be recorded in maps //! To cancel mapping, use TopAbs_SHAPE //! To force full mapping, use TopAbs_VERTEX //! The default level is TopAbs_FACE Standard_EXPORT TopAbs_ShapeEnum GetDetalisation() const; //! Sets a new result shape //! NOTE: this method should be used very carefully //! to keep consistency of modifications //! It is recommended to use RecordModification() methods //! with explicit definition of mapping from current //! result to a new one Standard_EXPORT void SetResult (const TopoDS_Shape& S); Standard_EXPORT void RecordModification (const TopTools_DataMapOfShapeShape& repl, const Handle(ShapeExtend_MsgRegistrator)& msg = 0); Standard_EXPORT void RecordModification (const Handle(ShapeBuild_ReShape)& repl, const Handle(ShapeExtend_MsgRegistrator)& msg); Standard_EXPORT void RecordModification (const Handle(ShapeBuild_ReShape)& repl); //! Records modifications and resets result accordingly //! NOTE: modification of resulting shape should be explicitly //! defined in the maps along with modifications of subshapes //! //! In the last function, sh is the shape on which Modifier //! was run. It can be different from the whole shape, //! but in that case result as a whole should be reset later //! either by call to SetResult(), or by another call to //! RecordModification() which contains mapping of current //! result to a new one explicitly Standard_EXPORT void RecordModification (const TopoDS_Shape& sh, const BRepTools_Modifier& repl, const Handle(ShapeExtend_MsgRegistrator)& msg = 0); //! Record a message for shape S //! Shape S should be one of subshapes of original shape //! (or whole one), but not one of intermediate shapes //! Records only if Message() is not Null Standard_EXPORT void AddMessage (const TopoDS_Shape& S, const Message_Msg& msg, const Message_Gravity gravity = Message_Warning); //! Get value of parameter as being of the type GeomAbs_Shape //! Returns False if parameter is not defined or has a wrong type Standard_EXPORT Standard_Boolean GetContinuity (const Standard_CString param, GeomAbs_Shape& val) const; //! Get value of parameter as being of the type GeomAbs_Shape //! If parameter is not defined or does not have expected //! type, returns default value as specified Standard_EXPORT GeomAbs_Shape ContinuityVal (const Standard_CString param, const GeomAbs_Shape def) const; //! Prints statistics on Shape Processing onto the current Messenger. Standard_EXPORT void PrintStatistics() const; //! Set NonManifold flag void SetNonManifold(Standard_Boolean theNonManifold) { myNonManifold = theNonManifold; } //! Get NonManifold flag Standard_Boolean IsNonManifold() { return myNonManifold; } DEFINE_STANDARD_RTTIEXT(ShapeProcess_ShapeContext,ShapeProcess_Context) protected: private: TopoDS_Shape myShape; TopoDS_Shape myResult; TopTools_DataMapOfShapeShape myMap; Handle(ShapeExtend_MsgRegistrator) myMsg; TopAbs_ShapeEnum myUntil; Standard_Boolean myNonManifold; }; #endif // _ShapeProcess_ShapeContext_HeaderFile
#ifndef STATUS_TEXT_TEST_H #define STATUS_TEXT_TEST_H class StatusTextTest { public: StatusTextTest() = default; ~StatusTextTest() = default; void Update(const float& someDeltaTime); private: float myTextTimer; }; #endif
#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; typedef long long ll; const int N = 50055; string w[N], a[N]; char b[111]; ll s[11], x[11]; ll c[11][11]; ll f[333], g[333]; int cnt[333]; int main() { freopen("high.in", "r", stdin); freopen("high.out", "w", stdout); int n; cin >> n; cin.ignore(); for (int i = 0; i < n; ++i) { scanf("%s", b); w[i] = b; } for (int msk = 0; msk < 32; ++msk) for (int i = 0; i < 5; ++i) if (msk & (1 << i)) ++cnt[msk]; int lim = 32; for (int i = 0; i < lim; ++i) { for (int j = 0; j < n; ++j) { a[j] = ""; for (int q = 0; q < 5; ++q) if (!(i & (1 << q))) a[j] += w[j][q]; } sort(a, a + n); ll len = 1; ll ans = 0; for (int j = 1; j < n; ++j) { if (a[j] == a[j - 1]) { ans += len; ++len; } else { len = 1; } } f[i] = ans; g[i] = ans; for (int msk = 0; msk < i; ++msk) if (((msk & i)) == msk) { if ((cnt[i] - cnt[msk]) & 1) { g[i] -= f[msk]; } else { g[i] += f[msk]; } } //cerr << i << " " << ans << endl; //s[cnt] += ans; x[cnt[i]] += g[i]; } /* c[0][0] = 1; for (int i = 1; i <= 5; ++i) { c[i][0] = c[i][i] = 1; for (int j = 1; j < i; ++j) c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; } for (int i = 0; i <= 5; ++i) { x[i] = s[i]; for (int k = 0; k < i; ++k) x[i] -= c[i - k][5 - k] * x[k]; cout << x[i] << " "; } cout << endl; */ for (int i = 0; i <= 5; ++i) cout << x[i] << " "; cout << endl; return 0; }
#define _CRT_SECURE_NO_WARNINGS #include "BaseElement.cpp" #include "BitmapFont.cpp" #include "ButtonBase.cpp" #include "ButtonImage.cpp" #include "ButtonText.cpp" #include "Cursor.cpp" #include "EditBox.cpp" #include "Frame.cpp" #include "Image.cpp" #include "LinearLayout.cpp" #include "TypeMesh.cpp" #include "Utils.cpp" #if defined(USE_GL_RENDER) #include "RendererGL.cpp" #elif defined(USE_SW_RENDER) #include "RendererSW.cpp" #endif
#include<cstdio> #include<iostream> #include<vector> #include<set> using namespace std; vector<int> v[]; int main() {int a,b,k=0; while (1) {v.clear(); cin >> a >> b; if ((a < 0) && (b < 0)) break; while ((a) && (b)) { } printf("Case %d is not a tree.",++k); } return 0; }
/* * Copyright (c) 2017-2021 Morwenn * SPDX-License-Identifier: MIT */ #include <functional> #include <string> #include <catch2/catch.hpp> #include <cpp-sort/comparators/partial_less.h> #include <cpp-sort/comparators/total_less.h> #include <cpp-sort/comparators/weak_less.h> #include <cpp-sort/utility/branchless_traits.h> #include <cpp-sort/utility/functional.h> TEST_CASE( "test that some specific comparisons are branchless", "[utility][branchless][comparison]" ) { using namespace cppsort::utility; SECTION( "standard library function objects" ) { CHECK(( is_probably_branchless_comparison_v<std::less<int>, int> )); CHECK(( is_probably_branchless_comparison_v<std::less<>, int> )); CHECK(( is_probably_branchless_comparison_v<std::less<long double>, long double> )); #ifdef __cpp_lib_ranges CHECK(( is_probably_branchless_comparison_v<std::ranges::less, int> )); CHECK(( is_probably_branchless_comparison_v<std::ranges::less, long double> )); #endif CHECK(( is_probably_branchless_comparison_v<std::greater<int>, int> )); CHECK(( is_probably_branchless_comparison_v<std::greater<>, int> )); CHECK(( is_probably_branchless_comparison_v<std::greater<long double>, long double> )); #ifdef __cpp_lib_ranges CHECK(( is_probably_branchless_comparison_v<std::ranges::greater, int> )); CHECK(( is_probably_branchless_comparison_v<std::ranges::greater, long double> )); #endif CHECK_FALSE(( is_probably_branchless_comparison_v<std::less<std::string>, std::string> )); CHECK_FALSE(( is_probably_branchless_comparison_v<std::less<>, std::string> )); #ifdef __cpp_lib_ranges CHECK_FALSE(( is_probably_branchless_comparison_v<std::ranges::less, std::string> )); #endif CHECK_FALSE(( is_probably_branchless_comparison_v<std::greater<std::string>, std::string> )); CHECK_FALSE(( is_probably_branchless_comparison_v<std::greater<>, std::string> )); #ifdef __cpp_lib_ranges CHECK_FALSE(( is_probably_branchless_comparison_v<std::ranges::greater, std::string> )); #endif } SECTION( "partial/weak/less function objects" ) { using partial_t = decltype(cppsort::partial_less); using weak_t = decltype(cppsort::weak_less); using total_t = decltype(cppsort::total_less); CHECK(( is_probably_branchless_comparison_v<partial_t, int> )); CHECK(( is_probably_branchless_comparison_v<weak_t, int> )); CHECK(( is_probably_branchless_comparison_v<total_t, int> )); CHECK(( is_probably_branchless_comparison_v<partial_t, float> )); CHECK_FALSE(( is_probably_branchless_comparison_v<weak_t, float> )); CHECK_FALSE(( is_probably_branchless_comparison_v<total_t, float> )); CHECK_FALSE(( is_probably_branchless_comparison_v<partial_t, std::string> )); CHECK_FALSE(( is_probably_branchless_comparison_v<weak_t, std::string> )); CHECK_FALSE(( is_probably_branchless_comparison_v<total_t, std::string> )); } SECTION( "cv-qualified and reference-qualified types" ) { CHECK(( is_probably_branchless_comparison_v<std::less<>, const int> )); CHECK(( is_probably_branchless_comparison_v<const std::less<>&, int> )); CHECK(( is_probably_branchless_comparison_v<const std::greater<>, int&&> )); #ifdef __cpp_lib_ranges CHECK(( is_probably_branchless_comparison_v<std::ranges::greater, const int&> )); #endif } } TEST_CASE( "test that some specific projections are branchless", "[utility][branchless][projection]" ) { using namespace cppsort::utility; struct foobar { int foo; int bar() { return 0; } }; CHECK(( is_probably_branchless_projection_v<identity, std::string> )); #if CPPSORT_STD_IDENTITY_AVAILABLE CHECK(( is_probably_branchless_projection_v<std::identity, std::string> )); #endif CHECK(( is_probably_branchless_projection_v<decltype(&foobar::foo), foobar> )); CHECK_FALSE(( is_probably_branchless_projection_v<decltype(&foobar::bar), foobar> )); #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) CHECK(( is_probably_branchless_projection_v<decltype(std::mem_fn(&foobar::foo)), foobar> )); #endif CHECK_FALSE(( is_probably_branchless_projection_v<decltype(std::mem_fn(&foobar::bar)), foobar> )); }
#ifndef _SBRP_STRUCT_DEF_H #define _SBRP_STRUCT_DEF_H struct SearchSpace { int i; int k; int r; }; class VRPNeighborElement { public: double val; int position; }; int VRPNeighborCompare (const void *a, const void *b); int VRPNeighborCompare2 (const void *a, const void *b); #endif
// Created on: 1997-10-22 // Created by: Philippe MANGIN / Sergey SOKOLOV // Copyright (c) 1997-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 _PLib_Base_HeaderFile #define _PLib_Base_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> #include <Standard_Integer.hxx> #include <TColStd_Array1OfReal.hxx> #include <Standard_Real.hxx> class PLib_Base; DEFINE_STANDARD_HANDLE(PLib_Base, Standard_Transient) //! To work with different polynomial's Bases class PLib_Base : public Standard_Transient { public: //! Convert the polynomial P(t) in the canonical base. Standard_EXPORT virtual void ToCoefficients (const Standard_Integer Dimension, const Standard_Integer Degree, const TColStd_Array1OfReal& CoeffinBase, TColStd_Array1OfReal& Coefficients) const = 0; //! Compute the values of the basis functions in u Standard_EXPORT virtual void D0 (const Standard_Real U, TColStd_Array1OfReal& BasisValue) = 0; //! Compute the values and the derivatives values of //! the basis functions in u Standard_EXPORT virtual void D1 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1) = 0; //! Compute the values and the derivatives values of //! the basis functions in u Standard_EXPORT virtual void D2 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1, TColStd_Array1OfReal& BasisD2) = 0; //! Compute the values and the derivatives values of //! the basis functions in u Standard_EXPORT virtual void D3 (const Standard_Real U, TColStd_Array1OfReal& BasisValue, TColStd_Array1OfReal& BasisD1, TColStd_Array1OfReal& BasisD2, TColStd_Array1OfReal& BasisD3) = 0; //! returns WorkDegree Standard_EXPORT virtual Standard_Integer WorkDegree() const = 0; //! Compute NewDegree <= MaxDegree so that MaxError is lower //! than Tol. //! MaxError can be greater than Tol if it is not possible //! to find a NewDegree <= MaxDegree. //! In this case NewDegree = MaxDegree Standard_EXPORT virtual void ReduceDegree (const Standard_Integer Dimension, const Standard_Integer MaxDegree, const Standard_Real Tol, Standard_Real& BaseCoeff, Standard_Integer& NewDegree, Standard_Real& MaxError) const = 0; DEFINE_STANDARD_RTTIEXT(PLib_Base,Standard_Transient) protected: private: }; #endif // _PLib_Base_HeaderFile
class Category_575 { class Skin_Bandit1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_Bandit2_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_BanditW1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_BanditW2_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_GUE_Commander_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_GUE_Soldier_2_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_GUE_Soldier_CO_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_GUE_Soldier_Crew_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_GUE_Soldier_Sniper_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_Ins_Soldier_GL_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_TK_INS_Soldier_EP1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_TK_INS_Warlord_EP1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_RU_Soldier_Crew_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; //new Epoch 1.06 class Skin_TK_INS_Soldier_AR_EP1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_TK_GUE_Soldier_EP1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_RU_Soldier_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_RU_Soldier_Officer_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_RUS_Soldier1_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_RUS_Commander_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_MVD_Soldier_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_Ins_Soldier_2_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_Ins_Commander_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_Ins_Soldier_Crew_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class Skin_CDF_Soldier_DZ { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/dom/src/domcallstate.h" /* static */ OP_STATUS DOM_CallState::Make(DOM_CallState*& new_obj, DOM_Runtime* origining_runtime, ES_Value* argv, int argc) { new_obj = OP_NEW(DOM_CallState, ()); RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj, origining_runtime)); RETURN_IF_ERROR(new_obj->SetArguments(argv, argc)); // no need to free if error - it will be garbage collected return OpStatus::OK; } DOM_CallState::DOM_CallState() : m_argv(NULL) , m_argc(0) , m_user_data(NULL) , m_phase(PHASE_NONE) , m_ready_for_suspend(FALSE) {} /* virtual*/ DOM_CallState::~DOM_CallState() { // freeing strings in args if we copied them if (m_ready_for_suspend) { for (int i = 0; i < m_argc; ++i) { switch (m_argv[i].type) { case VALUE_STRING: OP_DELETEA(m_argv[i].value.string); break; case VALUE_STRING_WITH_LENGTH: OP_ASSERT(m_argv[i].value.string_with_length); OP_DELETEA(m_argv[i].value.string_with_length->string); OP_DELETE(m_argv[i].value.string_with_length); break; } } } OP_DELETEA(m_argv); } /* static */ DOM_CallState* DOM_CallState::FromReturnValue(ES_Value* return_value) { if (return_value && return_value->type == VALUE_OBJECT) return FromES_Object(return_value->value.object); else return NULL; } /* static */ DOM_CallState* DOM_CallState::FromES_Object(ES_Object* es_object) { if (es_object) { EcmaScript_Object* ecmascript_object = ES_Runtime::GetHostObject(es_object); if (ecmascript_object && ecmascript_object->IsA(DOM_TYPE_CALLSTATE)) return static_cast<DOM_CallState*>(ecmascript_object); } return NULL; } OP_STATUS DOM_CallState::SetArguments(ES_Value* argv, int argc) { OP_ASSERT(!m_argv); m_argv = OP_NEWA(ES_Value, (argc)); if (!m_argv) return OpStatus::ERR_NO_MEMORY; m_argc = argc; for (int i = 0; i < m_argc; ++i) m_argv[i] = argv[i]; return OpStatus::OK; } /* virtual */ void DOM_CallState::GCTrace() { for (int i = 0; i < m_argc; ++i) GCMark(m_argv[i]); } /* static */ DOM_CallState::CallPhase DOM_CallState::GetPhaseFromESValue(ES_Value* restart_value) { DOM_CallState* call_state = FromReturnValue(restart_value); if (!call_state) return PHASE_NONE; else return call_state->GetPhase(); } /* static */ OP_STATUS DOM_CallState::RestoreArgumentsFromRestartValue(ES_Value* restart_value, ES_Value*& argv, int& argc) { if (restart_value) { DOM_CallState* call_state = FromReturnValue(restart_value); if (call_state) { call_state->RestoreArguments(argv, argc); return OpStatus::OK; } } return OpStatus::ERR; } OP_STATUS DOM_CallState::PrepareForSuspend() { if (!m_ready_for_suspend) { int i; // needed outside of the loop OP_STATUS error =OpStatus::OK; for (i = 0; i < m_argc; ++i) { switch (m_argv[i].type) { case VALUE_STRING: { m_argv[i].value.string = UniSetNewStr(m_argv[i].value.string); if (!m_argv[i].value.string) error = OpStatus::ERR_NO_MEMORY; break; } case VALUE_STRING_WITH_LENGTH: { ES_ValueString* copy = OP_NEW(ES_ValueString, ()); int len = m_argv[i].value.string_with_length->length; uni_char* str_copy = OP_NEWA(uni_char, len); if (copy && str_copy) { op_memcpy(str_copy, m_argv[i].value.string_with_length->string, len * sizeof(uni_char)); copy->string = str_copy; copy->length = len; m_argv[i].value.string_with_length = copy; } else { OP_DELETE(copy); OP_DELETEA(str_copy); error = OpStatus::ERR_NO_MEMORY; } break; } } if (OpStatus::IsError(error)) break; } if (OpStatus::IsError(error)) { for (i = i - 1; i >= 0; --i) { switch (m_argv[i].type) { case VALUE_STRING: OP_DELETEA(m_argv[i].value.string); break; case VALUE_STRING_WITH_LENGTH: OP_ASSERT(m_argv[i].value.string_with_length); OP_DELETEA(m_argv[i].value.string_with_length->string); OP_DELETE(m_argv[i].value.string_with_length); break; } } return error; } m_ready_for_suspend = TRUE; } return OpStatus::OK; };
// http://oj.leetcode.com/problems/swap-nodes-in-pairs/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode *dummy = new ListNode(-1); ListNode *slow = head; ListNode *fast = head; ListNode *last = dummy; while (fast != nullptr && fast->next != nullptr) { fast = fast->next; slow->next = fast->next; fast->next = slow; last->next = fast; last = slow; fast = slow->next; slow = slow->next; } return dummy->next; } };
#include <boost/range/counting_range.hpp> #include <boost/range/algorithm_ext/push_back.hpp> #include <boost/range.hpp> #include <queue> #include <stack> #include "../parallel/tbb.h" // for task_group template<class T> hera::ws::dnn::KDTree<T>:: KDTree(const Traits& traits, HandleContainer&& handles, double _wassersteinPower): traits_(traits), tree_(std::move(handles)), wassersteinPower(_wassersteinPower) { assert(wassersteinPower >= 1.0); init(); } template<class T> template<class Range> hera::ws::dnn::KDTree<T>:: KDTree(const Traits& traits, const Range& range, double _wassersteinPower): traits_(traits), wassersteinPower(_wassersteinPower) { assert( wassersteinPower >= 1.0); init(range); } template<class T> template<class Range> void hera::ws::dnn::KDTree<T>:: init(const Range& range) { size_t sz = std::distance(std::begin(range), std::end(range)); tree_.reserve(sz); weights_.resize(sz, 0); subtree_weights_.resize(sz, 0); for (PointHandle h : range) tree_.push_back(h); init(); } template<class T> void hera::ws::dnn::KDTree<T>:: init() { if (tree_.empty()) return; #if defined(TBB) hera::dnn::task_group g; g.run(OrderTree(tree_.begin(), tree_.end(), 0, traits())); g.wait(); #else OrderTree(tree_.begin(), tree_.end(), 0, traits()).serial(); #endif for (size_t i = 0; i < tree_.size(); ++i) indices_[tree_[i]] = i; } template<class T> struct hera::ws::dnn::KDTree<T>::OrderTree { OrderTree(HCIterator b_, HCIterator e_, size_t i_, const Traits& traits_): b(b_), e(e_), i(i_), traits(traits_) {} void operator()() const { if (e - b < 1000) { serial(); return; } HCIterator m = b + (e - b)/2; CoordinateComparison cmp(i, traits); std::nth_element(b,m,e, cmp); size_t next_i = (i + 1) % traits.dimension(); hera::dnn::task_group g; if (b < m - 1) g.run(OrderTree(b, m, next_i, traits)); if (e > m + 2) g.run(OrderTree(m+1, e, next_i, traits)); g.wait(); } void serial() const { std::queue<KDTreeNode> q; q.push(KDTreeNode(b,e,i)); while (!q.empty()) { HCIterator b, e; size_t i; std::tie(b,e,i) = q.front(); q.pop(); HCIterator m = b + (e - b)/2; CoordinateComparison cmp(i, traits); std::nth_element(b,m,e, cmp); size_t next_i = (i + 1) % traits.dimension(); // Replace with a size condition instead? if (m - b > 1) q.push(KDTreeNode(b, m, next_i)); if (e - m > 2) q.push(KDTreeNode(m+1, e, next_i)); } } HCIterator b, e; size_t i; const Traits& traits; }; template<class T> template<class ResultsFunctor> void hera::ws::dnn::KDTree<T>:: search(PointHandle q, ResultsFunctor& rf) const { typedef typename HandleContainer::const_iterator HCIterator; typedef std::tuple<HCIterator, HCIterator, size_t> KDTreeNode; if (tree_.empty()) return; DistanceType D = std::numeric_limits<DistanceType>::max(); // TODO: use tbb::scalable_allocator for the queue std::queue<KDTreeNode> nodes; nodes.push(KDTreeNode(tree_.begin(), tree_.end(), 0)); while (!nodes.empty()) { HCIterator b, e; size_t i; std::tie(b,e,i) = nodes.front(); nodes.pop(); CoordinateComparison cmp(i, traits()); i = (i + 1) % traits().dimension(); HCIterator m = b + (e - b)/2; DistanceType dist = (wassersteinPower == 1.0) ? traits().distance(q, *m) + weights_[m - tree_.begin()] : std::pow(traits().distance(q, *m), wassersteinPower) + weights_[m - tree_.begin()]; D = rf(*m, dist); // we are really searching w.r.t L_\infty ball; could prune better with an L_2 ball Coordinate diff = cmp.diff(q, *m); // diff returns signed distance DistanceType diffToWasserPower = (wassersteinPower == 1.0) ? diff : ((diff > 0 ? 1.0 : -1.0) * std::pow(fabs(diff), wassersteinPower)); size_t lm = m + 1 + (e - (m+1))/2 - tree_.begin(); if (e > m + 1 && diffToWasserPower - subtree_weights_[lm] >= -D) { nodes.push(KDTreeNode(m+1, e, i)); } size_t rm = b + (m - b) / 2 - tree_.begin(); if (b < m && diffToWasserPower + subtree_weights_[rm] <= D) { nodes.push(KDTreeNode(b, m, i)); } } } template<class T> void hera::ws::dnn::KDTree<T>:: adjust_weights(DistanceType delta) { for(auto& w : weights_) w -= delta; for(auto& sw : subtree_weights_) sw -= delta; } template<class T> void hera::ws::dnn::KDTree<T>:: change_weight(PointHandle p, DistanceType w) { size_t idx = indices_[p]; if ( weights_[idx] == w ) { return; } bool weight_increases = ( weights_[idx] < w ); weights_[idx] = w; typedef std::tuple<HCIterator, HCIterator> KDTreeNode; // find the path down the tree to this node // not an ideal strategy, but // it's not clear how to move up from the node in general std::stack<KDTreeNode> s; s.push(KDTreeNode(tree_.begin(),tree_.end())); do { HCIterator b,e; std::tie(b,e) = s.top(); size_t im = b + (e - b)/2 - tree_.begin(); if (idx == im) break; else if (idx < im) s.push(KDTreeNode(b, tree_.begin() + im)); else // idx > im s.push(KDTreeNode(tree_.begin() + im + 1, e)); } while(1); // update subtree_weights_ on the path to the root DistanceType min_w = w; while (!s.empty()) { HCIterator b,e; std::tie(b,e) = s.top(); HCIterator m = b + (e - b)/2; size_t im = m - tree_.begin(); s.pop(); // left and right children if (b < m) { size_t lm = b + (m - b)/2 - tree_.begin(); if (subtree_weights_[lm] < min_w) min_w = subtree_weights_[lm]; } if (e > m + 1) { size_t rm = m + 1 + (e - (m+1))/2 - tree_.begin(); if (subtree_weights_[rm] < min_w) min_w = subtree_weights_[rm]; } if (weights_[im] < min_w) { min_w = weights_[im]; } if (weight_increases) { if (subtree_weights_[im] < min_w ) // increase weight subtree_weights_[im] = min_w; else break; } else { if (subtree_weights_[im] > min_w ) // decrease weight subtree_weights_[im] = min_w; else break; } } } template<class T> typename hera::ws::dnn::KDTree<T>::HandleDistance hera::ws::dnn::KDTree<T>:: find(PointHandle q) const { hera::dnn::NNRecord<HandleDistance> nn; search(q, nn); return nn.result; } template<class T> typename hera::ws::dnn::KDTree<T>::Result hera::ws::dnn::KDTree<T>:: findR(PointHandle q, DistanceType r) const { hera::dnn::rNNRecord<HandleDistance> rnn(r); search(q, rnn); std::sort(rnn.result.begin(), rnn.result.end()); return rnn.result; } template<class T> typename hera::ws::dnn::KDTree<T>::Result hera::ws::dnn::KDTree<T>:: findK(PointHandle q, size_t k) const { hera::dnn::kNNRecord<HandleDistance> knn(k); search(q, knn); std::sort(knn.result.begin(), knn.result.end()); return knn.result; } template<class T> struct hera::ws::dnn::KDTree<T>::CoordinateComparison { CoordinateComparison(size_t i, const Traits& traits): i_(i), traits_(traits) {} bool operator()(PointHandle p1, PointHandle p2) const { return coordinate(p1) < coordinate(p2); } Coordinate diff(PointHandle p1, PointHandle p2) const { return coordinate(p1) - coordinate(p2); } Coordinate coordinate(PointHandle p) const { return traits_.coordinate(p, i_); } size_t axis() const { return i_; } private: size_t i_; const Traits& traits_; }; template<class T> void hera::ws::dnn::KDTree<T>:: printWeights(void) { #ifndef FOR_R_TDA std::cout << "weights_:" << std::endl; for(const auto ph : indices_) { std::cout << "idx = " << ph.second << ": (" << (ph.first)->at(0) << ", " << (ph.first)->at(1) << ") weight = " << weights_[ph.second] << std::endl; } std::cout << "subtree_weights_:" << std::endl; for(size_t idx = 0; idx < subtree_weights_.size(); ++idx) { std::cout << idx << " : " << subtree_weights_[idx] << std::endl; } #endif } template<class T> hera::bt::dnn::KDTree<T>::KDTree(const Traits& traits, HandleContainer&& handles): traits_(traits), tree_(std::move(handles)), delete_flags_(handles.size(), static_cast<char>(0) ), subtree_n_elems(handles.size(), static_cast<size_t>(0)), num_points_(handles.size()) { init(); } template<class T> template<class Range> hera::bt::dnn::KDTree<T>::KDTree(const Traits& traits, const Range& range): traits_(traits) { init(range); } template<class T> template<class Range> void hera::bt::dnn::KDTree<T>::init(const Range& range) { size_t sz = std::distance(std::begin(range), std::end(range)); subtree_n_elems = std::vector<int>(sz, 0); delete_flags_ = std::vector<char>(sz, 0); num_points_ = sz; tree_.reserve(sz); for (PointHandle h : range) tree_.push_back(h); parents_.resize(sz, -1); init(); } template<class T> void hera::bt::dnn::KDTree<T>::init() { if (tree_.empty()) return; #if defined(TBB) hera::dnn::task_group g; g.run(OrderTree(this, tree_.begin(), tree_.end(), -1, 0, traits())); g.wait(); #else OrderTree(this, tree_.begin(), tree_.end(), -1, 0, traits()).serial(); #endif for (size_t i = 0; i < tree_.size(); ++i) indices_[tree_[i]] = i; init_n_elems(); } template<class T> struct hera::bt::dnn::KDTree<T>::OrderTree { OrderTree(KDTree* tree_, HCIterator b_, HCIterator e_, ssize_t p_, size_t i_, const Traits& traits_): tree(tree_), b(b_), e(e_), p(p_), i(i_), traits(traits_) {} void operator()() const { if (e - b < 1000) { serial(); return; } HCIterator m = b + (e - b)/2; ssize_t im = m - tree->tree_.begin(); tree->parents_[im] = p; CoordinateComparison cmp(i, traits); std::nth_element(b,m,e, cmp); size_t next_i = (i + 1) % traits.dimension(); hera::dnn::task_group g; if (b < m - 1) g.run(OrderTree(tree, b, m, im, next_i, traits)); if (e > m + 2) g.run(OrderTree(tree, m+1, e, im, next_i, traits)); g.wait(); } void serial() const { std::queue<KDTreeNode> q; q.push(KDTreeNode(b,e,p,i)); while (!q.empty()) { HCIterator b, e; ssize_t p; size_t i; std::tie(b,e,p,i) = q.front(); q.pop(); HCIterator m = b + (e - b)/2; ssize_t im = m - tree->tree_.begin(); tree->parents_[im] = p; CoordinateComparison cmp(i, traits); std::nth_element(b,m,e, cmp); size_t next_i = (i + 1) % traits.dimension(); // Replace with a size condition instead? if (m - b > 1) q.push(KDTreeNode(b, m, im, next_i)); else if (b < m) tree->parents_[im - 1] = im; if (e - m > 2) q.push(KDTreeNode(m+1, e, im, next_i)); else if (e > m + 1) tree->parents_[im + 1] = im; } } KDTree* tree; HCIterator b, e; ssize_t p; size_t i; const Traits& traits; }; template<class T> void hera::bt::dnn::KDTree<T>::update_n_elems(ssize_t idx, const int delta) // add delta to the number of points in node idx and update subtree_n_elems // for all parents of the node idx { //std::cout << "subtree_n_elems.size = " << subtree_n_elems.size() << std::endl; // update the node itself while (idx != -1) { //std::cout << idx << std::endl; subtree_n_elems[idx] += delta; idx = parents_[idx]; } } template<class T> void hera::bt::dnn::KDTree<T>::increase_n_elems(const ssize_t idx) { update_n_elems(idx, static_cast<ssize_t>(1)); } template<class T> void hera::bt::dnn::KDTree<T>::decrease_n_elems(const ssize_t idx) { update_n_elems(idx, static_cast<ssize_t>(-1)); } template<class T> void hera::bt::dnn::KDTree<T>::init_n_elems() { for(size_t idx = 0; idx < tree_.size(); ++idx) { increase_n_elems(idx); } } template<class T> template<class ResultsFunctor> void hera::bt::dnn::KDTree<T>::search(PointHandle q, ResultsFunctor& rf) const { typedef typename HandleContainer::const_iterator HCIterator; typedef std::tuple<HCIterator, HCIterator, size_t> KDTreeNode; if (tree_.empty()) return; DistanceType D = std::numeric_limits<DistanceType>::infinity(); // TODO: use tbb::scalable_allocator for the queue std::queue<KDTreeNode> nodes; nodes.push(KDTreeNode(tree_.begin(), tree_.end(), 0)); //std::cout << "started kdtree::search" << std::endl; while (!nodes.empty()) { HCIterator b, e; size_t i; std::tie(b,e,i) = nodes.front(); nodes.pop(); CoordinateComparison cmp(i, traits()); i = (i + 1) % traits().dimension(); HCIterator m = b + (e - b)/2; size_t m_idx = m - tree_.begin(); // ignore deleted points if ( delete_flags_[m_idx] == 0 ) { DistanceType dist = traits().distance(q, *m); // + weights_[m - tree_.begin()]; //std::cout << "Supplied to functor: m : "; //std::cout << "(" << (*(*m))[0] << ", " << (*(*m))[1] << ")"; //std::cout << " and q : "; //std::cout << "(" << (*q)[0] << ", " << (*q)[1] << ")" << std::endl; //std::cout << "dist^q + weight = " << dist << std::endl; //std::cout << "weight = " << weights_[m - tree_.begin()] << std::endl; //std::cout << "dist = " << traits().distance(q, *m) << std::endl; //std::cout << "dist^q = " << pow(traits().distance(q, *m), wassersteinPower) << std::endl; D = rf(*m, dist); } // we are really searching w.r.t L_\infty ball; could prune better with an L_2 ball Coordinate diff = cmp.diff(q, *m); // diff returns signed distance DistanceType diffToWasserPower = (diff > 0 ? 1.0 : -1.0) * fabs(diff); size_t lm = m + 1 + (e - (m+1))/2 - tree_.begin(); if ( e > m + 1 and subtree_n_elems[lm] > 0 ) { if (e > m + 1 && diffToWasserPower >= -D) { nodes.push(KDTreeNode(m+1, e, i)); } } size_t rm = b + (m - b) / 2 - tree_.begin(); if ( subtree_n_elems[rm] > 0 ) { if (b < m && diffToWasserPower <= D) { nodes.push(KDTreeNode(b, m, i)); } } } //std::cout << "exited kdtree::search" << std::endl; } template<class T> typename hera::bt::dnn::KDTree<T>::HandleDistance hera::bt::dnn::KDTree<T>::find(PointHandle q) const { hera::dnn::NNRecord<HandleDistance> nn; search(q, nn); return nn.result; } template<class T> typename hera::bt::dnn::KDTree<T>::Result hera::bt::dnn::KDTree<T>::findR(PointHandle q, DistanceType r) const { hera::dnn::rNNRecord<HandleDistance> rnn(r); search(q, rnn); //std::sort(rnn.result.begin(), rnn.result.end()); return rnn.result; } template<class T> typename hera::bt::dnn::KDTree<T>::Result hera::bt::dnn::KDTree<T>::findFirstR(PointHandle q, DistanceType r) const { hera::dnn::firstrNNRecord<HandleDistance> rnn(r); search(q, rnn); return rnn.result; } template<class T> typename hera::bt::dnn::KDTree<T>::Result hera::bt::dnn::KDTree<T>::findK(PointHandle q, size_t k) const { hera::dnn::kNNRecord<HandleDistance> knn(k); search(q, knn); // do we need this??? std::sort(knn.result.begin(), knn.result.end()); return knn.result; } template<class T> struct hera::bt::dnn::KDTree<T>::CoordinateComparison { CoordinateComparison(size_t i, const Traits& traits): i_(i), traits_(traits) {} bool operator()(PointHandle p1, PointHandle p2) const { return coordinate(p1) < coordinate(p2); } Coordinate diff(PointHandle p1, PointHandle p2) const { return coordinate(p1) - coordinate(p2); } Coordinate coordinate(PointHandle p) const { return traits_.coordinate(p, i_); } size_t axis() const { return i_; } private: size_t i_; const Traits& traits_; }; template<class T> void hera::bt::dnn::KDTree<T>::delete_point(const size_t idx) { // prevent double deletion assert(delete_flags_[idx] == 0); delete_flags_[idx] = 1; decrease_n_elems(idx); --num_points_; } template<class T> void hera::bt::dnn::KDTree<T>::delete_point(PointHandle p) { delete_point(indices_[p]); }
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, "Russian"); float a;//катет 1 float b; // катет 2 float S; // площа прямокутного трикутника cout << "перший катет= "; cin >> a; cout << "Другий катет= "; cin >> b; S = 1./2 * a * b; // обчислення площі трикутника cout << "Площа = " << S; return 0; }
#include <algorithm> #include <cmath> #include <cstdlib> #include <iostream> #include <vector> // #include <chuffed/circuit/FDNNF.h> #include <chuffed/globals/mddglobals.h> #include <chuffed/mdd/CFG.h> #include <chuffed/mdd/CYK.h> #include <chuffed/mdd/MDD.h> // #include <chuffed/globals/circglobals.h> // #include <chuffed/circuit/nnfprop.h> #include <chuffed/mdd/circ_fns.h> // Using the simplified model, with infinite under-costs, and unit over-costs. // This maps to hard coverage constraints, and minimizing the # of worked hours. #define DECOMP 1 #define USEMDD 2 #define USEGCC 4 #define DISTINCT_REST #if 0 template <class T> T circ_gcc(T fff, vec< vec<T> >& xs, IntRelType rel, const vec<int>& cards) { assert(cards.size() > 0); vec< vec<T> > vals(cards.size()); for(int ii = 0; ii < xs.size(); ii++) { assert(xs[ii].size() == cards.size()); for(int jj = 0; jj < cards.size(); jj++) { vals[jj].push(xs[ii][jj]); } } T ret = card(fff, vals[0], rel, cards[0]); for(int jj = 1; jj < cards.size(); jj++) { assert(vals[jj].size() == xs.size()); ret = ret&(card(fff,vals[jj],rel,cards[jj])); } return ret; } void mdd_gcc(vec<IntVar*>& vs, IntRelType rel, const vec<int>& cards) { MDDTable tab(vs.size()); vec< vec<MDD> > vars; for(int ii = 0; ii < vs.size(); ii++) { vars.push(); for(int jj = 0; jj < cards.size(); jj++) vars.last().push(tab.vareq(ii,jj)); } MDD ret(circ_gcc(tab.fff(), vars, rel, cards)); addMDD(vs, ret); } #endif // Code for additional option handling. static char* hasPrefix(char* str, const char* prefix) { int len = strlen(prefix); if (strncmp(str, prefix, len) == 0) { return str + len; } return nullptr; } #ifdef DISTINCT_REST enum GapT { G_R = 2, G_B = 1, G_L = 0, maxG = 3 }; #else enum GapT { G_R = 0, G_B = 0, G_L = 0, maxG = 1 }; #endif class ShiftSched : public Problem { public: int const staff; int const shifts; int const acts; int const dom; const vec<vec<int> > demand; vec<vec<IntVar*> > xv; IntVar* cost; ShiftSched(int _staff, int _shifts, int _acts, vec<vec<int> >& _demand, int mode) : staff(_staff), shifts(_shifts), acts(_acts), dom(acts + maxG), demand(_demand) { for (int ww = 0; ww < staff; ww++) { xv.push(); for (int ss = 0; ss < shifts; ss++) { xv[ww].push(newIntVar(0, dom - 1)); xv[ww][ss]->specialiseToEL(); } } // Build the grammar int first = 0; while (first < shifts) { for (int ii = 0; ii < acts; ii++) { if (demand[first][ii] != 0) { goto found_first; } } first++; } found_first: int last = first; for (int ss = first; ss < shifts; ss++) { for (int ii = 0; ii < acts; ii++) { if (demand[ss][ii] != 0) { last = ss; break; } } } CFG::CFG g(buildSchedG(acts, first, last)); #if 0 if(!(mode&USEMDD)) { // Construct variables for the circuit FDNNFTable tab; std::vector< std::vector<FDNNF> > seq; for(int ii = 0; ii < shifts; ii++) { seq.push_back( std::vector<FDNNF>() ); for(int kk = 0; kk < dom; kk++) { seq[ii].push_back(tab.vareq(ii, kk)); } } // Construct a circuit from the grammar. FDNNF gcirc(parseCYK(tab.fff(), seq, g)); if(mode&DECOMP) { for(int ww = 0; ww < staff; ww++) { // nnf_decomp(xv[ww], gcirc); nnf_decompGAC(xv[ww], gcirc); } } else { // Enforce the schedule for each worker. for(int ww = 0; ww < staff; ww++) addNNF(xv[ww], gcirc); } } else { #endif // Construct variables for the circuit MDDTable mdd_tab(shifts); std::vector<std::vector<MDD> > seq; for (int ii = 0; ii < shifts; ii++) { seq.emplace_back(); for (int kk = 0; kk < dom; kk++) { seq[ii].push_back(mdd_tab.vareq(ii, kk)); } } MDD gcirc(parseCYK(mdd_tab.fff(), seq, g)); // Enforce the schedule for each worker. MDDOpts opts; for (int ww = 0; ww < staff; ww++) { addMDD(xv[ww], gcirc, opts); } #if 0 } #endif for (int ww = 1; ww < staff; ww++) { lex(xv[ww - 1], xv[ww], false); } // Enforce coverage constraints. for (int ss = 0; ss < shifts; ss++) { /* if(mode&USEGCC) { // Allocation for the current shift. vec<IntVar*> sv; for(int ww = 0; ww < staff; ww++) sv.push(xv[ww][ss]); mdd_gcc(sv, IRT_GE, demand[ss]); } else { */ for (int act = 0; act < acts; act++) { vec<BoolView> bv; for (int ww = 0; ww < staff; ww++) { bv.push(xv[ww][ss]->getLit(act, LR_EQ)); } bool_linear_decomp(bv, IRT_GE, demand[ss][act]); } // } } // Define the objective function. vec<BoolView> rostered; for (int ss = 0; ss < shifts; ss++) { if (ss < first || ss > last) { continue; } for (int ww = 0; ww < staff; ww++) { rostered.push(xv[ww][ss]->getLit(acts - 1, LR_LE)); } } unsigned int cMin(0); for (int ss = 0; ss < shifts; ss++) { for (int aa = 0; aa < acts; aa++) { cMin += demand[ss][aa]; } } cost = newIntVar(cMin, (last - first + 1) * staff); bool_linear_decomp(rostered, IRT_LE, cost); #if 0 vec<IntVar*> rostered_int; for(int ss = 0; ss < shifts; ss++) { if(ss < first || ss > last) continue; for(int ww = 0; ww < staff; ww++) { IntVar* sv = newIntVar(0,1); bool2int(xv[ww][ss]->getLit(acts-1, LR_LE),sv); rostered_int.push(sv); } } int_linear(rostered_int, IRT_GE, cost); #endif vec<IntVar*> vs; for (int ss = 0; ss < shifts; ss++) { for (int ww = 0; ww < staff; ww++) { vs.push(xv[ww][ss]); } } branch(vs, VAR_INORDER, VAL_MAX); optimize(cost, OPT_MIN); // vs.push(cost); output_vars(vs); } static CFG::CFG buildSchedG(int n_acts, int first, int last) { unsigned int rest(n_acts + G_R); unsigned int brk(n_acts + G_B); unsigned int lunch(n_acts + G_L); CFG::CFG g(n_acts + maxG); CFG::Sym S(g.newVar()); g.setStart(S); CFG::Sym R(g.newVar()); CFG::Sym P(g.newVar()); CFG::Sym W(g.newVar()); CFG::Sym L(g.newVar()); CFG::Sym F(g.newVar()); CFG::Cond actLB(g.attach(new CFG::SpanLB(4))); CFG::Cond lunEQ(g.attach(new CFG::Span(4, 4))); CFG::Cond part(g.attach(new CFG::Span(13, 24))); CFG::Cond full(g.attach(new CFG::Span(30, 38))); CFG::Cond open(g.attach(new CFG::Start(first, last))); std::vector<CFG::Sym> activities; for (int ii = 0; ii < n_acts; ii++) { CFG::Sym act(g.newVar()); activities.push_back(act); g.prod(open(act), CFG::E() << ii << act); g.prod(open(act), CFG::E() << ii); g.prod(W, CFG::E() << actLB(act)); } g.prod(S, CFG::E() << R << part(P) << R); g.prod(S, CFG::E() << R << full(F) << R); g.prod(R, CFG::E() << rest << R); g.prod(R, CFG::E() << rest); g.prod(L, CFG::E() << lunch << L); g.prod(L, CFG::E() << lunch); g.prod(P, CFG::E() << W << brk << W); g.prod(F, CFG::E() << P << lunEQ(L) << P); return g; } void print(std::ostream& os) override { #if 1 for (int act = 0; act < acts; act++) { os << "["; for (int ss = 0; ss < shifts; ss++) { os << demand[ss][act]; } os << "]\n"; } #endif os << "Hours worked: " << (1.0 * cost->getVal() / 4) << "\n"; for (int ww = 0; ww < xv.size(); ww++) { os << "["; for (int ii = 0; ii < shifts; ii++) { // if(ii) // printf(", "); int val(xv[ww][ii]->getVal()); if (val < acts) { os << val; } else { switch (val - acts) { #ifdef DISTINCT_REST case G_R: os << "R"; break; case G_B: os << "B"; break; case G_L: os << "L"; break; #else case G_R: os << "R"; break; default: assert(0); break; #endif } } } os << "]\n"; } } }; void parseInst(std::istream& in, int& acts, int& shifts, vec<vec<int> >& demand) { in >> acts; in >> shifts; for (int ss = 0; ss < shifts; ss++) { demand.push(); for (int aa = 0; aa < acts; aa++) { double d; in >> d; demand.last().push((int)ceil(d)); } } } int main(int argc, char** argv) { int mode = 0; int jj = 1; char* value; for (int ii = 1; ii < argc; ii++) { value = hasPrefix(argv[ii], "-decomp="); if (value != nullptr) { if (strcmp(value, "true") == 0) { mode |= DECOMP; } continue; } value = hasPrefix(argv[ii], "-mdd="); if (value != nullptr) { if (strcmp(value, "true") == 0) { mode |= USEMDD; } continue; } value = hasPrefix(argv[ii], "-gcc="); if (value != nullptr) { if (strcmp(value, "true") == 0) { mode |= USEGCC; } continue; } argv[jj++] = argv[ii]; } argc = jj; parseOptions(argc, argv); // Arguments: // #staff // assert(argc == 2 || argc == 3); assert(argc == 2); int staff = 1; int acts = 1; int shifts = 96; staff = atoi(argv[1]); vec<vec<int> > demand; parseInst(std::cin, acts, shifts, demand); engine.solve(new ShiftSched(staff, shifts, acts, demand, mode)); return 0; }
// // // IMService.hpp // MyCppGame // // Created by 杜红 on 2017/1/22. // // #ifndef IMService_hpp #define IMService_hpp #include <stdio.h> #include "YIM.h" #include <string> using namespace std; struct Msg{ public: unsigned long long msgID = 0; //消息ID,自己发送的没有消息ID string sender =""; //发送者 bool bSelf = false ; //是否自己发送 unsigned int createTime = 0 ; //发送时间 bool bTxt = false ; //是否文本 string content = ""; //如果是文本,则是文本内容,如果是语音,则是语音检测出的文本 string voicePath =""; //语音的保存地址 int voiceLen = 0 ; //语音长度 }; class IMService : public IYIMLoginCallback, public IYIMMessageCallback, public IYIMChatRoomCallback, public IYIMDownloadCallback, public IYIMContactCallback, public IYIMLocationCallback, public IYIMNoticeCallback { public: static IMService * getInstance(); static IMService* _instance; virtual ~IMService(); // void start(); //登录回调 void OnLogin(YIMErrorcode errorcode, const XString& userID)override; //登出回调 void OnLogout(YIMErrorcode errorcode)override ; //被踢下线 void OnKickOff()override; void OnSendMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime )override ; //发送语音消息回调 void OnSendAudioMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, const XString& text, const XString& audioPath, unsigned int audioTime, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime) override; //收到消息 void OnRecvMessage( std::shared_ptr<IYIMMessage> message)override ; void OnQueryRoomHistoryMessage(YIMErrorcode errorcode, std::list<std::shared_ptr<IYIMMessage> > messageList)override; //语音上传后回调 void OnStopAudioSpeechStatus(YIMErrorcode errorcode, std::shared_ptr<IAudioSpeechInfo> audioSpeechInfo)override; //新消息通知(只有SetReceiveMessageSwitch设置为不自动接收消息,才会收到该回调) void OnReceiveMessageNotify(YIMChatType chatType, const XString& targetID)override; //获取消息历史纪录回调 void OnQueryHistoryMessage(YIMErrorcode errorcode,const XString& targetID, int remain, std::list<std::shared_ptr<IYIMMessage> > messageList)override ; //加入频道回调 void OnJoinChatRoom(YIMErrorcode errorcode,const XString& chatRoomID)override ; //离开频道回调 void OnLeaveChatRoom(YIMErrorcode errorcode, const XString& chatRoomID) override; //获取最近联系人回调 void OnGetRecentContacts(YIMErrorcode errorcode, std::list<XString>& contactList)override; //获取用户信息回调(用户信息为JSON格式) void OnGetUserInfo(YIMErrorcode errorcode, const XString& userID, const XString& userInfo)override; void OnDownload( YIMErrorcode errorcode, std::shared_ptr<IYIMMessage> msg, const XString& savePath )override; void OnDownloadByUrl( YIMErrorcode errorcode, const XString& strFromUrl, const XString& savePath )override; virtual void OnUserJoinChatRoom(const XString& chatRoomID, const XString& userID)override; //其他用户退出频道通知 virtual void OnUserLeaveChatRoom(const XString& chatRoomID, const XString& userID) override ; virtual void OnAccusationResultNotify(AccusationDealResult result, const XString& userID, unsigned int accusationTime)override; //语音文件保存的路径 string strTempDir; }; #endif /* IMService_hpp */
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; struct Cliente { string nombre; int gastos; int piezas; }; //Obtiene el precio de N piezas con cierto codigo int obtenerPrecio(int codigo, int piezas) { int precioBase = 0; switch (codigo) { case 1: precioBase = 5; break; case 2: precioBase = 20; break; case 3: precioBase = 15; break; case 4: precioBase = 10; break; case 5: precioBase = 12; break; } return precioBase * piezas; } bool comparaClientes(Cliente a, Cliente b) { return a.gastos > b.gastos; } /* Problema 3.3 Complejidad de tiempo: O(N log N) */ int main() { vector<Cliente> clientes; while (true) { string nombre; int codigo, cantidad; cin >> nombre >> codigo >> cantidad; if (nombre == "FIN" && codigo == 0 && cantidad == 0) { break; } bool clienteExistente = false; for (int i = 0; i < clientes.size(); i++) { if (clientes[i].nombre == nombre) { clienteExistente = true; clientes[i].gastos += obtenerPrecio(codigo, cantidad); clientes[i].piezas += cantidad; } } if (!clienteExistente) { Cliente nuevo; nuevo.nombre = nombre; nuevo.gastos = obtenerPrecio(codigo, cantidad); nuevo.piezas = cantidad; clientes.push_back(nuevo); } } sort(clientes.begin(), clientes.end(), comparaClientes); for (int i = 0; i < 3; i++) { cout << clientes[i].nombre << " " << clientes[i].gastos << " " << clientes[i].piezas << endl; } }
/** \file bluetooth.h \brief */ /* * (C) 2013 Uwe Lippmann * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (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/>. */ #ifndef BLUETOOTH_H #define BLUETOOTH_H #include <exception> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> #include <bluetooth/hci.h> #include <bluetooth/hci_lib.h> typedef struct { char addr[17]; char name[255]; } scanResult_t; class Bluetooth { public: Bluetooth(); Bluetooth(const char* address); ~Bluetooth(); void scan(int timeout); void connect(const char* btAddress); void disconnect(); void send(const char* command, int length); void receive(char* answer, int length); int getNxtSocket() const; int getResultCount() const; scanResult_t getResult(int index) const; private: int resultCount; scanResult_t* scanResult; int nxtSocket; }; #endif // BLUETOOTH_H
#include "List.h" //#include <string> //using namespace std; struct Student { int id; float score; Student(int _id, float _score) : id(_id), score(_score){} Student(){} friend bool operator !=(const Student &left, const Student &right); }; bool operator !=(const Student &left, const Student &right) { return (left.id == right.id && left.score == right.score)? false : true; } int main() { CList<Student> list; Student s1(1, 22); Student s2(2, 33); Student s3(3, 44); list.Append(s1); list.Append(s2); list.Append(s3); list.Insert(s1, 2); Student s = list[2]; list.Remove(s1); return 0; }
#include "bricks/imaging/colour.h" namespace Bricks { namespace Imaging { const ColourTypeMask::Enum PixelDescription::bitDepthMap[] = { ColourTypeMask::Unknown, ColourTypeMask::Intensity, ColourTypeMask::Palette, ColourTypeMask::Red, ColourTypeMask::Green, ColourTypeMask::Blue, ColourTypeMask::Alpha }; const PixelDescription PixelDescription::I8 = PixelDescription(8, ColourTypeMask::Intensity); const PixelDescription PixelDescription::IA8 = PixelDescription(8, ColourTypeMask::IntensityAlpha); const PixelDescription PixelDescription::RGB8 = PixelDescription(8, ColourTypeMask::RGB); const PixelDescription PixelDescription::RGBA8 = PixelDescription(8, ColourTypeMask::RGBA); } }
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #if defined(__GNUG__) #define _msize malloc_usable_size #endif #include <execinfo.h> #include <iostream> #include <tr1/unordered_map> #include <tr1/unordered_set> #include <boost/thread/recursive_mutex.hpp> #include <fstream> #include <map> #include <vector> #include "leak_detector.h" #include <signal.h> void LeakDumpHandle(int sig) { std::cout << "Leak dumping with signal(" << sig << ")" << std::endl; leakd::MemoryLeakDetector::inst().Dump(); } void InitLeakSignal() { leakd::MemoryLeakDetector::inst().Dump(); int leak_detect_sig = 16; if (SIG_ERR == signal(leak_detect_sig, LeakDumpHandle)) { std::cerr << "Cannot catch signal:" << leak_detect_sig << std::endl; } else { std::cout << "Init leak dump signal:" << leak_detect_sig << std::endl; } } extern "C" { void *__real_malloc(size_t sz); void *__wrap_malloc(size_t sz) { void *p = __real_malloc(sz); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, sz, cs); return p; } void __real_free(void *p); void __wrap_free(void *p) { leakd::MemoryLeakDetector::inst().Erase(p); __real_free(p); return; } char *__real_strdup(char* s); char *__wrap_strdup(char* s) { char *p = __real_strdup(s); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, malloc_usable_size(p), cs); return p; } void *__real_realloc(void *p, unsigned int newsize); void *__wrap_realloc(void *p, unsigned int newsize) { leakd::MemoryLeakDetector::inst().Erase(p); void *q = __real_realloc(p, newsize); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(q, newsize, cs); return q; } void *__real_calloc(size_t n, size_t size); void *__wrap_calloc(size_t n, size_t size) { void *p = __real_calloc(n, size); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, n*size, cs); return p; } void __real_cfree(void* p); void __wrap_cfree(void* p) { leakd::MemoryLeakDetector::inst().Erase(p); __real_cfree(p); return; } void* __real_memalign(size_t align, size_t s); void* __wrap_memalign(size_t align, size_t s) { void* p = __real_memalign(align, s); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, s, cs); return p; } void* __real_valloc(size_t size); void* __wrap_valloc(size_t size) { void* p = __real_valloc(size); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, size, cs); return p; } void* __real_pvalloc(size_t size); void* __wrap_pvalloc(size_t size) { void *p = __real_pvalloc(size); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, size, cs); return p; } } void* operator new(size_t sz) { void *p = __real_malloc(sz); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, sz, cs); return p; } void* operator new[] (size_t sz) { void *p = __real_malloc(sz); leakd::CallStack* cs = leakd::CallStackLookupTable::inst().Lookup(); leakd::MemoryLeakDetector::inst().Insert(p, sz, cs); return p; } void operator delete(void* p) { leakd::MemoryLeakDetector::inst().Erase(p); __real_free(p); return; } void operator delete[](void* p) { leakd::MemoryLeakDetector::inst().Erase(p); __real_free(p); return; }
//====================================================================== // Name: Game_Engine.cpp // Author: Will Blades // Function: Implements Game_Engine class //====================================================================== #include "Game_Engine.h" // Name: Engine() // Function: Default Constructor Engine::Engine() { snake = new Snake; game_shell = new Shell; //initialize screen screen = NULL; //Start SDL SDL_Init(SDL_INIT_EVERYTHING | SDL_INIT_NOPARACHUTE); // NO_PARACHUTE flag for MS VC++ //Set up screen screen = SDL_SetVideoMode(MAX_WIDTH, MAX_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); SDL_WM_SetCaption("Snake v0.1", "Snake v0.1"); //TTF_Init(); } // Name: Snake() // Function: Default Destructor Engine::~Engine() { delete snake; delete game_shell; //Quit SDL SDL_Quit(); //TTF_Quit(); } // Name: apply_surface // Function: Helper function for the constructor. Blits the texture on a rectangle to // the screen using SDL_BlitSurface void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination) { SDL_Rect offset; // give the offsets to the rectangle offset.x = x; offset.y = y; SDL_BlitSurface(source, NULL, destination, &offset); } // Name: Render(bool flipScreen) // Parameter(s): Flipscreen (boolean) // Function: Renders the HUD and textures to screen void Engine::Render(bool flipScreen) { // Fill background color first Uint32 backgroundcolor = 0xA9F5E1; SDL_FillRect(screen, nullptr, backgroundcolor); std::vector<axis>temp = snake->get_body(); axis tempfood = snake->get_food(); // Blit Snake on screen apply_surface(temp.at(0).xposition, temp.at(0).yposition, snake->headTexture, screen); for (int i = 1; i < (int)temp.size(); i++) apply_surface(temp.at(i).xposition, temp.at(i).yposition, snake->bodyTexture, screen); // Blit food apply_surface(tempfood.xposition, tempfood.yposition, snake->foodTexture, screen); // Apply HUD DrawScreen(); if (flipScreen) SDL_Flip(screen); } // Name: InitiateGame() // Function: Pre-game processing. To be expanded later void Engine::InitiateGame() { SDL_EventState(SDL_KEYDOWN, SDL_IGNORE); SDL_EventState(SDL_KEYDOWN, SDL_ENABLE); } // Name: InitiateGame() // Function: Render HUD on screen void Engine::DrawScreen() { SDL_Rect wall; Uint32 wallcolor = 0x1C1C1C; int wall_width = 5; // The upper horizontal part wall.x = 0; wall.y = 0; wall.w = MAX_WIDTH - wall_width; wall.h = wall_width; SDL_FillRect(screen, &wall, wallcolor); // The bottom horizontal part wall.y = MAX_WIDTH - wall_width; SDL_FillRect(screen, &wall, wallcolor); // The right vertical part wall.x = MAX_WIDTH - wall_width; wall.y = 0; wall.w = wall_width; wall.h = MAX_HEIGHT; SDL_FillRect(screen, &wall, wallcolor); // Draw the left vertical part wall.x = 0; wall.y = 0; wall.w = wall_width; wall.h = MAX_HEIGHT - wall_width; SDL_FillRect(screen, &wall, wallcolor); } // Name: Update() // Function: Keeps calling Move function unless the game is paused. // Update is evoked in each instance of the main game loop void Engine::Update() { if (!game_shell->is_Paused()) snake->Move(); } // Name: Update() // Parameter(s): Key ,Must be of standard SDLKey format // Function: Translates Directional keys into integers for the // snake's class direction variable storage int DetermineDirection(SDLKey key) { switch (key) { case SDLK_UP: return 1; break; case SDLK_DOWN: return 2; break; case SDLK_LEFT: return 3; break; case SDLK_RIGHT: return 4; break; /*default: std::cout << "Not a valid movement key \n"; exit(-1);*/ } } // Name: Start() // Function: Main good loop. Keep looping until gamerunning is false. // Gamerunning is false when collision is detected or when // the user presses ESC or clicks on the window's X button. void Engine::Start() { InitiateGame(); Render(); gamerunning = true; SDL_Event event; while (gamerunning) { game_shell->StartTime(); if (snake->DetectCollision()) gamerunning = false; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) gamerunning = false; else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) gamerunning = false; else snake->ChangeDirection(DetermineDirection(event.key.keysym.sym)); } if (snake->DetectCollision()) gamerunning = false; // Add to the snake body and initiate new food item if snake eats current // food if (snake->FoodDetected()) { snake->IncrementSnakeSize(); snake->NewFood(); game_shell->UpdateScore(); } } Update(); Render(); game_shell->TimeDelay(); } }
#include<bits/stdc++.h> using namespace std; int main() { long long int l1,r1,l2,r2,k; cin>>l1>>r1>>l2>>r2>>k; long long int ml=max(l1,l2); long long int mr=min(r1,r2); if(ml<=mr) { long long int ans=mr-ml+1; if(k>=ml&&k<=mr) { ans--; } cout<<ans; } else { cout<<0; } return 0; }
<template> <div> <img /> </div> </template><script> export default { el: '#example', data: { message: 'hello' }, computed: { reversedMessage: function () { return this.message.split('').reverse().join('') } } } </script><style> </style>
#include "hotelwindow.h" #include "ui_hotelwindow.h" #include "cadastro.h" #include "remover.h" HotelWindow::HotelWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::HotelWindow) { ui->setupUi(this); } HotelWindow::~HotelWindow() { delete ui; } void HotelWindow::on_pushButton_cadastro_clicked() { cadastro cadastrowindow; cadastrowindow.setModal(true); cadastrowindow.exec(); } void HotelWindow::on_pushButton_remover_clicked() { remover removerwindow; removerwindow.setModal(true); removerwindow.exec(); }
#ifndef _MAC_HOST_QUICK_MENU_H_ #define _MAC_HOST_QUICK_MENU_H_ #include "platforms/mac/quick_support/MacQuickMenu.h" #include "platforms/mac/embrowser/EmBrowserQuick.h" #include "modules/util/adt/opvector.h" class MacHostQuickMenu; class MacHostQuickMenuBar : public MacQuickMenu { public: virtual ~MacHostQuickMenuBar(); virtual void AddItem(BOOL seperator, const uni_char* item_name, OpWidgetImage* image, const uni_char* shortcut, MacQuickMenu *submenu, BOOL checked, BOOL selected, BOOL disabled, OpInputAction* input_action); virtual Boolean IsInternal() const { return false; } OpInputAction * FindAction(EmQuickMenuCommand command); void ActionExecuted(EmQuickMenuCommand command); void RebuildMenu(EmQuickMenuRef inMenu); void RebuildAllMenus(); void RemoveAllMenus(); #ifdef _MAC_DEBUG void PrintAllMenus(); #endif protected: MacHostQuickMenu* FindMenu(EmQuickMenuRef inMenu); MacHostQuickMenu* FindMenu(UInt16 inMenuID); private: OpAutoVector<MacHostQuickMenu> mSubmenus; }; class MacHostQuickMenu : public MacQuickMenu { friend class MacHostQuickMenuBar; public: MacHostQuickMenu(const uni_char* menu_name, const char *menu_type, INTPTR menu_value); virtual ~MacHostQuickMenu(); virtual void AddItem(BOOL seperator, const uni_char* item_name, OpWidgetImage* image, const uni_char* shortcut, MacQuickMenu *submenu, BOOL checked, BOOL selected, BOOL disabled, OpInputAction* input_action); virtual Boolean IsInternal() const { return false; } protected: EmQuickMenuRef GetEmMenuRef(); EmQuickMenuKind GetMenuKind() { return mMenuKind; } time_t GetModTime() { return mModtime; } void SetModTime(time_t t) { mModtime = t; } MacHostQuickMenu* FindMenu(UInt16 inMenuID); MacHostQuickMenu* FindMenu(EmQuickMenuRef inMenu); OpInputAction * GetAction(UInt16 actionID); void UpdateMenu(); const char* GetMenuName(); #ifdef _MAC_DEBUG void PrintAllMenus(); #endif private: static UInt16 sMenuCount; EmQuickMenuRef mEmMenuRef; OpVector<OpInputAction> mActions; OpAutoVector<MacHostQuickMenu> mSubmenus; UInt16 mMenuID; EmQuickMenuKind mMenuKind; OpString8 mMenuName; INTPTR mMenuValue; time_t mModtime; }; extern MacHostQuickMenuBar* gMenuBar; #endif // _MAC_HOST_QUICK_MENU_H_
#include "RandomSeeds.h" Seeds creatRandomSeeds(int xsize, int ysize, int NumPoints) { srand((int)time(0)); Seeds RandomSeeds; for (int k = 0; k < NumPoints; k++) { int x = random(xsize); int y = random(ysize); Pixel point(x, y); RandomSeeds.push_back(point); } return RandomSeeds; }
class bulk: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BULK_NAME; model = "\z\addons\dayz_communityassets\models\crate.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_crate.paa"; descriptionShort = $STR_EPOCH_BULK_DESC; }; class bulk_empty: bulk { displayName = $STR_EPOCH_BULK_DISP_EMPTY; descriptionShort = $STR_EPOCH_BULK_DESC_EMPTY; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_221; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSodaCoke",1}}; input[] = {{"bulk_empty",1},{"ItemSodaCoke",6}}; }; class Crafting1 { text = $STR_EPOCH_PLAYER_222; script = ";['Crafting1','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSodaPepsi",1}}; input[] = {{"bulk_empty",1},{"ItemSodaPepsi",6}}; }; class Crafting2 { text = $STR_EPOCH_PLAYER_223; script = ";['Crafting2','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_PartGenericHalf",1}}; input[] = {{"bulk_empty",1},{"PartGeneric",6}}; }; class Crafting3 { text = $STR_EPOCH_PLAYER_224; script = ";['Crafting3','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemTankTrapHalf",1}}; input[] = {{"bulk_empty",1},{"ItemTankTrap",6}}; }; class Crafting4 { text = $STR_EPOCH_PLAYER_225; script = ";['Crafting4','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemWireHalf",1}}; input[] = {{"bulk_empty",1},{"ItemWire",6}}; }; class Crafting5 { text = $STR_EPOCH_PLAYER_226; script = ";['Crafting5','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_FoodbaconCooked",1}}; input[] = {{"bulk_empty",1},{"FoodbaconCooked",6}}; }; class Crafting6 { text = $STR_EPOCH_PLAYER_332; script = ";['Crafting6','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSandbagHalf",1}}; input[] = {{"bulk_empty",1},{"ItemSandbag",6}}; }; }; }; //Edibles class bulk_ItemSodaCoke: bulk { displayName = $STR_EPOCH_BULK_DISP_SODACOKE_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_SODACOKE_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSodaCoke",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_221; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSodaCokeFull",1}}; input[] = {{"bulk_ItemSodaCoke",1},{"ItemSodaCoke",6}}; }; }; }; class bulk_ItemSodaCokeFull: bulk { displayName = $STR_EPOCH_BULK_DISP_SODACOKE_FULL; descriptionShort = $STR_EPOCH_BULK_DESC_SODACOKE_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSodaCoke",12,"magazine"}; }; }; }; class bulk_ItemSodaPepsi: bulk { displayName = $STR_EPOCH_BULK_DISP_SODAPEPSI_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_SODAPEPSI_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSodaPepsi",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_222; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSodaPepsiFull",1}}; input[] = {{"bulk_ItemSodaPepsi",1},{"ItemSodaPepsi",6}}; }; }; }; class bulk_ItemSodaPepsiFull: bulk { displayName = $STR_EPOCH_BULK_DISP_SODAPEPSI_FULL; descriptionShort = $STR_EPOCH_BULK_DESC_SODAPEPSI_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSodaPepsi",12,"magazine"}; }; }; }; class bulk_FoodbaconCooked: bulk { displayName = $STR_EPOCH_BULK_DISP_BACON_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_BACON_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodbaconCooked",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_227; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_FoodbaconCookedFull",1}}; input[] = {{"bulk_FoodbaconCooked",1},{"FoodbaconCooked",6}}; }; }; }; class bulk_FoodbaconCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_BACON_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_BACON_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodbaconCooked",12,"magazine"}; }; }; }; class bulk_equip_garlic_bulbFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_garlic_bulb_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_garlic_bulb_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_garlic_bulb",12,"magazine"}; }; }; }; class bulk_FishCookedSeaBassFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FishCookedSeaBass_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FishCookedSeaBass_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FishCookedSeaBass",12,"magazine"}; }; }; }; class bulk_FishCookedTroutFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FishCookedTrout_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FishCookedTrout_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FishCookedTrout",12,"magazine"}; }; }; }; class bulk_FishCookedTunaFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FishCookedTuna_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FishCookedTuna_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FishCookedTuna",12,"magazine"}; }; }; }; class bulk_FoodBeefCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodBeefCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodBeefCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodBeefCooked",12,"magazine"}; }; }; }; class bulk_FoodCarrotFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodCarrot_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodCarrot_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodCarrot",12,"magazine"}; }; }; }; class bulk_FoodChickenCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodChickenCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodChickenCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodChickenCooked",12,"magazine"}; }; }; }; class bulk_FoodDogCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodDogCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodDogCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodDogCooked",12,"magazine"}; }; }; }; class bulk_FoodGoatCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodGoatCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodGoatCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodGoatCooked",12,"magazine"}; }; }; }; class bulk_FoodMuttonCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodMuttonCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodMuttonCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodMuttonCooked",12,"magazine"}; }; }; }; class bulk_FoodPotatoRawFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodPotatoRaw_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodPotatoRaw_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodPotatoRaw",12,"magazine"}; }; }; }; class bulk_FoodPumpkinFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodPumpkin_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodPumpkin_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodPumpkin",12,"magazine"}; }; }; }; class bulk_FoodRabbitCookedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_FoodRabbitCooked_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_FoodRabbitCooked_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"FoodRabbitCooked",12,"magazine"}; }; }; }; //Building items class bulk_ItemSandbagHalf: bulk { displayName = $STR_EPOCH_BULK_DISP_SANDBAG_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_SANDBAG_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSandbag",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_332; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemSandbag",1}}; input[] = {{"bulk_ItemSandbag",1},{"ItemSandbag",6}}; }; }; }; class bulk_ItemSandbag: bulk { displayName = $STR_EPOCH_BULK_DISP_SANDBAG; descriptionShort = $STR_EPOCH_BULK_DESC_SANDBAG; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSandbag",12,"magazine"}; }; }; }; class bulk_ItemTankTrapHalf: bulk { displayName = $STR_EPOCH_BULK_DISP_TANKTRAP_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_TANKTRAP_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemTankTrap",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_224; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemTankTrap",1}}; input[] = {{"bulk_ItemTankTrapHalf",1},{"ItemTankTrap",6}}; }; }; }; class bulk_ItemTankTrap: bulk { displayName = $STR_EPOCH_BULK_DISP_TANKTRAP_FULL; descriptionShort = $STR_EPOCH_BULK_DESC_TANKTRAP_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemTankTrap",12,"magazine"}; }; }; }; class bulk_ItemWireHalf: bulk { displayName = $STR_EPOCH_BULK_DISP_WIREKIT_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_WIREKIT_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemWire",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_225; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_ItemWire",1}}; input[] = {{"bulk_ItemWireHalf",1},{"ItemWire",6}}; }; }; }; class bulk_ItemWire: bulk { displayName = $STR_EPOCH_BULK_DISP_WIREKIT_FULL; descriptionShort = $STR_EPOCH_BULK_DESC_WIREKIT_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemWire",12,"magazine"}; }; }; }; class bulk_PartGenericHalf: bulk { displayName = $STR_EPOCH_BULK_DISP_GENERIC_HALF; descriptionShort = $STR_EPOCH_BULK_DESC_GENERIC_HALF; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"PartGeneric",6,"magazine"}; }; class Crafting { text = $STR_EPOCH_PLAYER_223; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {"ItemToolbox"}; output[] = {{"bulk_PartGeneric",1}}; input[] = {{"bulk_PartGenericHalf",1},{"PartGeneric",6}}; }; }; }; class bulk_PartGeneric: bulk { displayName = $STR_EPOCH_BULK_DISP_GENERIC_FULL; descriptionShort = $STR_EPOCH_BULK_DESC_GENERIC_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"PartGeneric",12,"magazine"}; }; }; }; class bulk_ItemComboLockFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemComboLock_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemComboLock_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemComboLock",12,"magazine"}; }; }; }; //Misc class bulk_equip_aa_batteryFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_aa_battery_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_aa_battery_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_aa_battery",12,"magazine"}; }; }; }; class bulk_equip_d_batteryFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_d_battery_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_d_battery_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_d_battery",12,"magazine"}; }; }; }; class bulk_equip_duct_tapeFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_duct_tape_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_duct_tape_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_duct_tape",12,"magazine"}; }; }; }; class bulk_equip_feathersFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_feathers_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_feathers_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_feathers",12,"magazine"}; }; }; }; class bulk_equip_floppywireFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_floppywire_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_floppywire_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_floppywire",12,"magazine"}; }; }; }; class bulk_equip_nailsFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_nails_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_nails_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_nails",12,"magazine"}; }; }; }; class bulk_equip_pvc_boxFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_pvc_box_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_pvc_box_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_pvc_box",12,"magazine"}; }; }; }; class bulk_equip_ragFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_rag_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_rag_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_rag",12,"magazine"}; }; }; }; class bulk_equip_ropeFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_rope_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_rope_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_rope",12,"magazine"}; }; }; }; class bulk_equip_scrapelectronicsFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_scrapelectronics_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_scrapelectronics_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_scrapelectronics",12,"magazine"}; }; }; }; class bulk_equip_stringFull: bulk { displayName = $STR_EPOCH_BULK_DISP_equip_string_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_equip_string_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"equip_string",12,"magazine"}; }; }; }; class bulk_HandChemBlueFull: bulk { displayName = $STR_EPOCH_BULK_DISP_HandChemBlue_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_HandChemBlue_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"HandChemBlue",12,"magazine"}; }; }; }; class bulk_HandChemGreenFull: bulk { displayName = $STR_EPOCH_BULK_DISP_HandChemGreen_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_HandChemGreen_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"HandChemGreen",12,"magazine"}; }; }; }; class bulk_HandChemRedFull: bulk { displayName = $STR_EPOCH_BULK_DISP_HandChemRed_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_HandChemRed_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"HandChemRed",12,"magazine"}; }; }; }; class bulk_HandRoadFlareFull: bulk { displayName = $STR_EPOCH_BULK_DISP_HandRoadFlare_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_HandRoadFlare_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"HandRoadFlare",12,"magazine"}; }; }; }; class bulk_ItemC4ChargeFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemC4Charge_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemC4Charge_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemC4Charge",12,"magazine"}; }; }; }; class bulk_ItemDogTagFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemDogTag_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemDogTag_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemDogTag",12,"magazine"}; }; }; }; class bulk_ItemHotwireKitFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemHotwireKit_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemHotwireKit_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemHotwireKit",12,"magazine"}; }; }; }; class bulk_ItemKosmosSmokesFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemKosmosSmokes_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemKosmosSmokes_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemKosmosSmokes",12,"magazine"}; }; }; }; class bulk_ItemLightBulbFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemLightBulb_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemLightBulb_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemLightBulb",12,"magazine"}; }; }; }; class bulk_ItemMixOilFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemMixOil_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemMixOil_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemMixOil",12,"magazine"}; }; }; }; class bulk_ItemScrewsFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemScrews_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemScrews_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemScrews",12,"magazine"}; }; }; }; class bulk_PartGlassFull: bulk { displayName = $STR_EPOCH_BULK_DISP_PartGlass_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_PartGlass_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"PartGlass",12,"magazine"}; }; }; }; class bulk_PartWheelFull: bulk { displayName = $STR_EPOCH_BULK_DISP_PartWheel_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_PartWheel_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"PartWheel",12,"magazine"}; }; }; }; class bulk_PipeBombFull: bulk { displayName = $STR_EPOCH_BULK_DISP_PipeBomb_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_PipeBomb_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"PipeBomb",12,"magazine"}; }; }; }; //Planting class bulk_ItemFertilizerFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemFertilizer_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemFertilizer_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemFertilizer",12,"magazine"}; }; }; }; class bulk_ItemKiloBlackTeaFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemKiloBlackTea_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemKiloBlackTea_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemKiloBlackTea",12,"magazine"}; }; }; }; class bulk_ItemKiloHempFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemKiloHemp_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemKiloHemp_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemKiloHemp",12,"magazine"}; }; }; }; class bulk_ItemKiloTobaccoFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemKiloTobacco_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemKiloTobacco_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemKiloTobacco",12,"magazine"}; }; }; }; //Animal Craftables class bulk_ItemAnimalSkinFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemAnimalSkin_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemAnimalSkin_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemAnimalSkin",12,"magazine"}; }; }; }; class bulk_ItemSkinRabbitFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinRabbit_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinRabbit_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinRabbit",12,"magazine"}; }; }; }; class bulk_ItemSkinCowFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinCow_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinCow_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinCow",12,"magazine"}; }; }; }; class bulk_ItemSkinGoatFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinGoat_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinGoat_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinGoat",12,"magazine"}; }; }; }; class bulk_ItemSkinBoarFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinBoar_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinBoar_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinBoar",12,"magazine"}; }; }; }; class bulk_ItemSkinDogFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinDog_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinDog_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinDog",12,"magazine"}; }; }; }; class bulk_ItemSkinSheepFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemSkinSheep_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemSkinSheep_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemSkinSheep",12,"magazine"}; }; }; }; class bulk_ItemWoolFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemWool_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemWool_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemWool",12,"magazine"}; }; }; }; class bulk_ItemLeatherFull: bulk { displayName = $STR_EPOCH_BULK_DISP_ItemLeather_FULL; descriptionshort = $STR_EPOCH_BULK_DESC_ItemLeather_FULL; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"ItemLeather",12,"magazine"}; }; }; }; // Ammo class bulk_17Rnd_9x19_glock17: bulk { displayName = $STR_EPOCH_BULK_DISP_G17; descriptionShort = $STR_EPOCH_BULK_DESC_G17; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"17Rnd_9x19_glock17",12,"magazine"}; }; }; }; class bulk_15Rnd_9x19_M9SD: bulk { displayName = $STR_EPOCH_BULK_DISP_M9SD; descriptionShort = $STR_EPOCH_BULK_DESC_M9SD; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"15Rnd_9x19_M9SD",12,"magazine"}; }; }; }; class bulk_30Rnd_9x19_MP5SD: bulk { displayName = $STR_EPOCH_BULK_DISP_MP5SD; descriptionShort = $STR_EPOCH_BULK_DESC_MP5SD; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"30Rnd_9x19_MP5SD",12,"magazine"}; }; }; }; class bulk_30Rnd_556x45_StanagSD: bulk { displayName = $STR_EPOCH_BULK_DISP_STANAGSD; descriptionShort = $STR_EPOCH_BULK_DESC_STANAGSD; class ItemActions { class CreateMags { text = $STR_EPOCH_ACTIONS_OPEN; script = "spawn player_loadCrate;"; output[] = {"30Rnd_556x45_StanagSD",12,"magazine"}; }; }; };
#include "TagManager.h" TagManager::TagManager(World *world) { _world = world; } TagManager::~TagManager() { clear(); _entitiesByTag.clear(); } void TagManager::add(Entity *entity, std::string tag) { Entity *targetEntity = _entitiesByTag[tag]; if (targetEntity == NULL) { targetEntity = entity; } } void TagManager::add(int id, std::string tag) { add(_world->getEntity(id), tag); } void TagManager::remove(Entity *entity, std::string tag) { if (_entitiesByTag[tag] == entity) { _entitiesByTag[tag] = NULL; } } void TagManager::remove(int id, std::string tag) { remove(_world->getEntity(id), tag); } void TagManager::removeFromAll(Entity *entity) { std::map<std::string, Entity *>::iterator it; for (it = _entitiesByTag.begin(); it != _entitiesByTag.end(); it++) { if (it->second == entity) { it->second = NULL; } } } void TagManager::removeFromAll(int id) { removeFromAll(_world->getEntity(id)); } Entity *TagManager::getEntity(std::string tag) { return _entitiesByTag[tag]; } bool TagManager::hasTag(Entity *entity, std::string tag) { return _entitiesByTag[tag] == entity; } bool TagManager::hasTag(int id, std::string tag) { return hasTag(_world->getEntity(id), tag); } void TagManager::clear() { std::map<std::string, Entity *>::iterator it; for (it = _entitiesByTag.begin(); it != _entitiesByTag.end(); it++) { if (it->second != NULL) { it->second = NULL; } } }
#ifndef LAYOUTCONFIG_H #define LAYOUTCONFIG_H #include <qfile.h> #include <qdir.h> #include <qdatastream.h> #include <qwidget.h> #include <iostream> #include <qgroupbox.h> #include <qpushbutton.h> #include <map> #include <vector> #include "mainwindow.h" class MainWindow; extern QString callFuncNumber; using namespace std; class NewQPushButton : public QPushButton{ Q_OBJECT public: QString funNumber; NewQPushButton(QPushButton* parent) :QPushButton(parent){ /*funNumber = "ABCD"*/; this->setText(parent->text()); } void setFunNum(const QString& num); }; class LayoutConfig : public QWidget{ Q_OBJECT public: typedef map<QString, NewQPushButton*> btnType; //map<QString, QPushButton*> buttonGroup; vector<btnType*> buttonGroupList; vector<QGroupBox*> groupBoxList; MainWindow* mainWindow; MainWindow* m; private: QFile* in; QDir* dir; QString Filename; QString Location; QString btnName; QString funcNum; public: LayoutConfig(MainWindow* m); LayoutConfig(QString& st1, QString& str2); QString& getDir(){ return Filename; } QString& getFilename(){ return Location; } void setDir(QString& str){ Filename = str; } void setFilename(QString& str){ Location = str; } public slots: void ConfigNow(); QString showInfo(); private: void setButtonConnectInfo(const QString& str1, const QString& str2){ btnName = QString(str1); funcNum = QString(str2); } }; #endif
#include "GamePlayDemo.h" //#include "Timer.h" //#include "Team.h" //#include "TeamManager.h" #include "Ship.h" //#include "SensoryMemory.h" //#include "TargetSystem.h" //#include "Weapon.h" //#include "WeaponSystem.h" #include "Wall.h" //#include "MapSelection.h" //#include "cocos-ext.h" //#include "UIScene.h" //#include "UISceneManager.h" //#include "editor-support/cocostudio/CCSGUIReader.h" //#include "CocosGUIScene.h" //using namespace CocosDenshion; //#include "extensions/GUI/CCControlExtension/CCControlSlider.h" //#include "SimpleAudioEngine.h" static std::string tabString[] = { "Id", // 0 "X", // 1 "Y", // 2 "current state", // 3 "closest target id", // 4 "sensed number", // 5 "posClosestX", // 6 "posClosestY", // 7 "closest direction", // 8 "closest shootable", // 9 "cloesest tile", // 10 "dist to target ", // 11 "range weapon ", // 11 "distX", // 12 "distY", // 13 "shootable On X", "shootable on Y", "weapon name ", "target id ", "Message reeived ", "width ", "height ", "tile id ", "tile x", "tile y ", "cuurent time", "left tile id ", "right tile id ", "up tile id ", "down tile id " }; // The display information #define MAX_DISPLAY (sizeof(tabString) / sizeof(tabString[0])) // this the pos of the first label (health) static CCPoint PosLab1 (700,600); // the id for the label static int labId=1000; // -----ctor-------- GamePlayDemo::GamePlayDemo(): m_sNameTower ("Null"), m_bBuildEnabled(false), m_bBuildCanceled(false) { //auto listener1 = EventListenerTouchOneByOne::create(); //listener1->onTouchBegan = CC_CALLBACK_2(GamePlayDemo::onTouchBegan, this); //listener1->onTouchEnded = CC_CALLBACK_2(GamePlay::onTouchEnded, this); //listener1->onTouchMoved = CC_CALLBACK_2(GamePlay::onTouchMoved, this); // auto _mouseListener = EventListenerMouse::create(); // _mouseListener->onMouseMove = CC_CALLBACK_1(GamePlayDemo::onMouseMove, this); // //_mouseListener->onMouseUp = CC_CALLBACK_1(MouseTest::onMouseUp, this); // //_mouseListener->onMouseDown = CC_CALLBACK_1(MouseTest::onMouseDown, this); // //_mouseListener->onMouseScroll = CC_CALLBACK_1(MouseTest::onMouseScroll, this); // _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this); //_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); } //-----dtor------ GamePlayDemo::~GamePlayDemo() { } bool GamePlayDemo::onTouchBegan(CCTouch* touch, CCEvent *event) { return true; } // this function will spawn a projectile at the given position void GamePlayDemo::onTouchEnded(CCTouch* touch, CCEvent *event) { //if (!isPlaying()) // return ; // auto location = touch->getLocation(); // m_vMousePos = location; // if (m_bBuildEnabled && m_sNameTower != "Null") // { // m_lab1->setString(m_sNameTower+" built "); // addTower(m_iSelectedTile,location.x,location.y); // } //// auto map = /*static_cast<TMXTiledMap*>( getChildByTag(1) )*/getMap(); //// auto layer = map->getLayer("Layer 0"); ////layer->setTileGID(10,Vec2(0,0)); } void GamePlayDemo::onMouseMove(CCEvent *event) { } void GamePlayDemo::onTouchMoved(CCTouch *touch, CCEvent *event) { } void GamePlayDemo::Start() { // playing status if (isInactive() ) { setPlaying(); ////start music //// preload background music and effect //SimpleAudioEngine::getInstance()->preloadBackgroundMusic("Music/terran-1.mp3"); //SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.5); // SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/terran-1.mp3", false); ///*SimpleAudioEngine::getInstance()->preloadEffect( "Music/explode.wav" ); // SimpleAudioEngine::getInstance()->setEffectsVolume(0.5); //SimpleAudioEngine::getInstance()->playEffect("Music/explode.wav", false);*/ //auto visibleSize = Director::getInstance()->getVisibleSize(); // auto origin = Director::getInstance()->getVisibleOrigin(); //// create map //auto map = TMXTiledMap::create(/*"TileMap/map1.tmx"*/ MapSelection::getSelectedMap()); // Layer::addChild(map, 0, /*kTagTileMap*/1); // Director::getInstance()->setProjection(Director::Projection::_2D); // auto layer = map->getLayer("Layer 0"); // auto ss = layer->getLayerSize(); // setMap(map); // createMap(); // //// create the timer //Layer::addChild(Clock); //// adding ship //addAllShips(); //// create labels //createLabel(); ////// create the image view //m_Icon1 = Sprite::create("item/defense.png"); // //m_Icon1->setPosition(Vec2 (45,620)); //m_Icon1->setScale(1.5f,1.5f); //Layer::addChild(m_Icon1); //m_Icon2 = Sprite::create("item/attack.png"); //m_Icon2->setPosition(Vec2 (45,580)); //m_Icon2->setScale(1.25f,1.25f); //Layer::addChild(m_Icon2); //m_Icon3 = Sprite::create("item/mana.png"); //m_Icon3->setPosition(Vec2 (45,540)); //m_Icon3->setScale(1.25f,1.25f); //Layer::addChild(m_Icon3); //m_Icon4 = Sprite::create("item/level.png"); //m_Icon4->setPosition(Vec2 (45,500)); //m_Icon4->setScale(1.25f,1.25f); //Layer::addChild(m_Icon4); //m_Icon5 = Sprite::create("item/mineral.png"); //m_Icon5->setPosition(Vec2 (800,620)); //m_Icon5->setScale(1.25f,1.25f); //Layer::addChild(m_Icon5); //m_lab1 =LabelTTF::create("lab1", "Arial", 20); //m_lab2 =LabelTTF::create("lab2", "Arial", 20); //m_lab3 =LabelTTF::create("lab3", "Arial", 20); // m_lab4 =LabelTTF::create("lab4", "Arial", 20); //m_lab5 =LabelTTF::create("lab5", "Arial", 20); //m_lab1->setPosition(Vec2(m_Icon1->getPositionX() + 40,m_Icon1->getPositionY() )); //m_lab2->setPosition(Vec2(m_Icon2->getPositionX() + 40,m_Icon2->getPositionY() )); //m_lab3->setPosition(Vec2(m_Icon3->getPositionX() + 40,m_Icon3->getPositionY() )); //m_lab4->setPosition(Vec2(m_Icon4->getPositionX() + 40,m_Icon4->getPositionY() )); //m_lab5->setPosition(Vec2(m_Icon5->getPositionX() + 40,m_Icon5->getPositionY() )); //Layer::addChild(m_lab1); //Layer::addChild(m_lab2); // Layer::addChild(m_lab3); // Layer::addChild(m_lab4); // Layer::addChild(m_lab5); //m_Button6 = Button::create("item/Icon_Building.png", // "item/Icon_Building.png"); //m_Button6->setPosition(Vec2( 30,420)); //Layer::addChild(m_Button6); //m_Button6->setScale(0.2f); //m_Button6->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::PrepareBuild, this)); //m_Button7 = Button::create("item/Icon_Upgrade1.png", // "item/Icon_Upgrade1.png"); //m_Button7->setPosition(Vec2( 70,420)); //Layer::addChild(m_Button7); //m_Button7->setScale(0.2f); //m_Button8 = Button::create("item/Icon_Upgrade2.png", // "item/Icon_Upgrade2.png"); //m_Button8->setPosition(Vec2( 110,420)); //Layer::addChild(m_Button8); //m_Button8->setScale(0.25f); //CreateButtonTower(); //// menu for exit ////createMenuButton(); //// interface for menu //createMenuInterface(); //Sprite* t = m_pMap->getLayer("Layer 0")->getTileAt(Vec2(0,0)); //m_vStartingPosMap = t->getPosition(); //m_TileSize = t->getContentSize(); // //this->scheduleUpdate(); //} // //if (isExited()) //{ // setPlaying(); // reStart(); // this->scheduleUpdate(); // Clock->scheduleUpdate(); // // activate all butoons // activateButtons(); } } //-----------------createIcon-------------------- // create icons for damage,attack,etc.... //------------------------------------------------ void GamePlayDemo::createIcon() { //// create the image view /*m_Icon1 = Sprite::create("item/defense.png"); m_Icon1->setPosition(Vec2 (45,620)); m_Icon1->setScale(1.5f,1.5f); Layer::addChild(m_Icon1); m_Icon2 = Sprite::create("item/attack.png"); m_Icon2->setPosition(Vec2 (45,580)); m_Icon2->setScale(1.25f,1.25f); Layer::addChild(m_Icon2); m_Icon3 = Sprite::create("item/mana.png"); m_Icon3->setPosition(Vec2 (45,540)); m_Icon3->setScale(1.25f,1.25f); Layer::addChild(m_Icon3); m_Icon4 = Sprite::create("item/level.png"); m_Icon4->setPosition(Vec2 (45,500)); m_Icon4->setScale(1.25f,1.25f); Layer::addChild(m_Icon4); m_Icon5 = Sprite::create("item/mineral.png"); m_Icon5->setPosition(Vec2 (800,620)); m_Icon5->setScale(1.25f,1.25f); Layer::addChild(m_Icon5); m_lab1 =LabelTTF::create("lab1", "Arial", 20); m_lab2 =LabelTTF::create("lab2", "Arial", 20); m_lab3 =LabelTTF::create("lab3", "Arial", 20); m_lab4 =LabelTTF::create("lab4", "Arial", 20); m_lab5 =LabelTTF::create("lab5", "Arial", 20); m_lab1->setPosition(Vec2(m_Icon1->getPositionX() + 40,m_Icon1->getPositionY() )); m_lab2->setPosition(Vec2(m_Icon2->getPositionX() + 40,m_Icon2->getPositionY() )); m_lab3->setPosition(Vec2(m_Icon3->getPositionX() + 40,m_Icon3->getPositionY() )); m_lab4->setPosition(Vec2(m_Icon4->getPositionX() + 40,m_Icon4->getPositionY() )); m_lab5->setPosition(Vec2(m_Icon5->getPositionX() + 40,m_Icon5->getPositionY() )); Layer::addChild(m_lab1); Layer::addChild(m_lab2); Layer::addChild(m_lab3); Layer::addChild(m_lab4); Layer::addChild(m_lab5); m_Button6 = Button::create("item/Icon_Building.png", "item/Icon_Building.png"); m_Button6->setPosition(Vec2( 30,420)); Layer::addChild(m_Button6); m_Button6->setScale(0.2f); m_Button6->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::PrepareBuild, this)); m_Button7 = Button::create("item/Icon_Upgrade1.png", "item/Icon_Upgrade1.png"); m_Button7->setPosition(Vec2( 70,420)); Layer::addChild(m_Button7); m_Button7->setScale(0.2f); m_Button8 = Button::create("item/Icon_Upgrade2.png", "item/Icon_Upgrade2.png"); m_Button8->setPosition(Vec2( 110,420)); Layer::addChild(m_Button8); m_Button8->setScale(0.25f); */ } void GamePlayDemo::update(float fDelta) { ////m_Button6->setPositionX(m_Button6->getPositionX()+ 0.1); // //m_lab1->setString(std::to_string(m_ListWall.size())); //m_lab2->setString(std::to_string(Clock->getCurrentTime())); // //m_lab3->setString(std::to_string( (int) m_fNextTimeRestarting)); ////if (m_bDeleteAllShip) // //return ; //if (isInactive() || isExited() ) // return ; //if (isBeforeExiting()) //{ // if (Clock->getCurrentTime() > m_fNextTimeExiting) // { // setExited(); // static_cast<LayerMultiplex*>(_parent)->switchTo(0); // } // else // return ; //} //if (isRestarting() ) //{ // // update time for pause // //restart(); // // if (isReadyForRestart()) // { // reStart(); // // } // else // return ; //} //// do not update if the game has paused //if (isPaused()) // return ; ////updateWall(); //updateTower(); //updateProjectile(); //updateShip(); //updateLabel(); //if ( !SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying()) //{ // if (m_iCurrentMusic == 1) // SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/protoss-1.mp3", false); // // else if (m_iCurrentMusic == 2) // SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/terran-1.mp3", false); // else if (m_iCurrentMusic == 3) // SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/terran-2.mp3", false); // m_iCurrentMusic++; // if (m_iCurrentMusic > 3) // m_iCurrentMusic = 1; //} } //-----------create label------------- // for debug //------------------------------------ void GamePlayDemo::createLabel() { //// position precedente //Vec2 posPrec(0,0); //Vec2 posPrec1(0,0); //// create the value for player1 //std::string valPlayer1[]= //{ // "nothing", // "nothing", // "nothing", // "nothing", // "nothing", // "nothing", // "nothing", // "nothing", // "nothing", // std::to_string(9), // std::to_string(10), // std::to_string(11), // "By Player", // std::to_string(13), // 13 target id // std::to_string(14), // 14 sensed // std::to_string(15), // 15 posclossest x // std::to_string(16), // 16 pos cmosest y // std::to_string(17), // "null", // "null", // "null", // "null", // std::to_string(20), // std::to_string(22), // std::to_string(23), // std::to_string(24), // std::to_string(25), // std::to_string(26), // std::to_string(27), // std::to_string(28), // std::to_string(29), // std::to_string(30), // std::to_string(31), // std::to_string(32) //}; //for (int i =0; i< MAX_DISPLAY; i++) // m_player1val[i] = valPlayer1[i]; // //// the position of the first label for playeer 1 //posPrec =PosLab1; //for (int i =0; i< MAX_DISPLAY; i++) //{ // m_tabValue[i] = tabString[i]; // // auto lab = LabelTTF::create( tabString[i] , "Arial", 20); // // spaxing of 10 pixels // lab->setPosition( Vec2(posPrec.x,posPrec.y -i *20)); // Layer::addChild(lab); // lab->setTag(labId+i); //} //m_labTileX = LabelTTF::create( "tile " , "Arial", 20); //Layer::addChild(m_labTileX); //m_labTileX->setPosition(20,300); //m_labMouse = LabelTTF::create( "mouse " , "Arial", 20); //Layer::addChild(m_labMouse); //m_labMouse->setPosition(60,280); //m_labId = LabelTTF::create( "IdTile " , "Arial", 20); //Layer::addChild(m_labId); //m_labId->setPosition(20,260); //m_labWidth = LabelTTF::create( "size " , "Arial", 20); //Layer::addChild(m_labWidth); //m_labWidth->setPosition(20,240); // } //-------------- init timer for label-------------------- // this function create timer for label of buiding // //-------------------------------------------------------- void GamePlayDemo::initLabTimer() { /*m_pLabTimer1 = LabelTTF::create(std::to_string(TowerMarine::m_iBuildTime),"Arial", 15); m_pLabTimer2 = LabelTTF::create(std::to_string(TowerFireBat::m_iBuildTime),"Arial", 15); m_pLabTimer3 = LabelTTF::create(std::to_string(TowerMarauder::m_iBuildTime),"Arial", 15); m_pLabTimer4 = LabelTTF::create(std::to_string(TowerTank::m_iBuildTime),"Arial", 15); m_pLabTimer5 = LabelTTF::create(std::to_string(TowerThor::m_iBuildTime),"Arial", 15); m_pLabTimer1->setColor(Color3B::GREEN); m_pLabTimer2->setColor(Color3B::GREEN); m_pLabTimer3->setColor(Color3B::GREEN); m_pLabTimer4->setColor(Color3B::GREEN); m_pLabTimer5->setColor(Color3B::GREEN); m_pLabTimer1->setPosition(Vec2(16,380)); m_pLabTimer2->setPosition(Vec2(48,380)); m_pLabTimer3->setPosition(Vec2(80,380)); m_pLabTimer4->setPosition(Vec2(112,380)); m_pLabTimer5->setPosition(Vec2(144,380)); Layer::addChild(m_pLabTimer1); Layer::addChild(m_pLabTimer2); Layer::addChild(m_pLabTimer3); Layer::addChild(m_pLabTimer4); Layer::addChild(m_pLabTimer5); */ } //---------------updateTimeBeforeBuild---------------------- // this function is used to update timer for buiding //---------------------------------------------------------- void GamePlayDemo::updateTimeBeforeBuild(float dt) { TowerMarine::m_fTimeBeforeBuild-=dt; TowerMarauder::m_fTimeBeforeBuild-=dt; TowerFireBat::m_fTimeBeforeBuild-=dt; TowerTank::m_fTimeBeforeBuild-=dt; TowerThor::m_fTimeBeforeBuild-=dt; TowerHellion::m_fTimeBeforeBuild-=dt; if (TowerMarine::m_fTimeBeforeBuild <= 0) TowerMarine::m_fTimeBeforeBuild = 0 ; if (TowerMarauder::m_fTimeBeforeBuild <= 0) TowerMarauder::m_fTimeBeforeBuild = 0 ; if (TowerFireBat::m_fTimeBeforeBuild <= 0) TowerFireBat::m_fTimeBeforeBuild = 0 ; if (TowerTank::m_fTimeBeforeBuild <= 0) TowerTank::m_fTimeBeforeBuild = 0 ; if (TowerThor::m_fTimeBeforeBuild <= 0) TowerThor::m_fTimeBeforeBuild = 0 ; if (TowerHellion::m_fTimeBeforeBuild <= 0) TowerHellion::m_fTimeBeforeBuild = 0 ; } //------------------------------------------------------- // update the label timer by assigning the label to value //------------------------------------------------------- void GamePlayDemo::updateTimerLabel(float dt) { //if (m_pLabTimer1) // m_pLabTimer1->setString(std::to_string((int) TowerMarine::m_fTimeBeforeBuild )); //if (m_pLabTimer2) // m_pLabTimer2->setString(std::to_string((int) TowerFireBat::m_fTimeBeforeBuild )); //if (m_pLabTimer3) // m_pLabTimer3->setString(std::to_string((int) TowerMarauder::m_fTimeBeforeBuild )); //if (m_pLabTimer4) //m_pLabTimer4->setString(std::to_string((int) TowerTank::m_fTimeBeforeBuild )); //if (m_pLabTimer5) //m_pLabTimer5->setString(std::to_string((int) TowerThor::m_fTimeBeforeBuild )); ////if (m_pLabTimer1) ////m_pLabTimer1->setString(std::to_string((int) TowerMarine::m_fTimeBeforeBuild )); } //----------------update label-------- // //------------------------------------- void GamePlayDemo::updateLabel() { // if (m_ListShip.size() > 0) // { // Ship* m = m_ListShip.back(); // // m_player1val[0] =std::to_string(m->ID()); // m_player1val[1] =std::to_string(m->getPositionX()); // m_player1val[2] =std::to_string(m->getPositionY()); // // m_player1val[3] =m->GetFSM()->CurrentState()->getName(); // // if (m->GetTargetSys()->getClosestTarget() ) // { // BaseEntity* close = m->GetTargetSys()->getClosestTarget(); // m_player1val[4] = std::to_string(close->ID()); // m_player1val[6] = std::to_string(close->getPositionX()); // m_player1val[7] = std::to_string(close->getPositionY()); // m_player1val[8] = m->GetSensoryMem()->GetOpponentDir(close); // // m_player1val[9] = m->GetSensoryMem()->GetOpponentShootable(close); // m_player1val[10] = m->GetSensoryMem()->GetOpponentTile(close); // // // m_player1val[11] = std::to_string( close->getPosition().distance(m->getPosition()) ); // m_player1val[12] = std::to_string(m->GetWeaponSys()->GetCurrentWeapon()->GetIdealRange()); // // //dist x // float distX = fabs (close->getPositionX() - m->getPositionX()); // float distY = fabs (close->getPositionY() - m->getPositionY()); // m_player1val[13] = std::to_string( distX ); // // m_player1val[14] = std::to_string(distY); // // if (m->GetSensoryMem()->isOpponentShootableOnX(close)) // m_player1val[15] = "True"; // // else // m_player1val[15] = "False"; // // if (m->GetSensoryMem()->isOpponentShootableOnY(close)) // m_player1val[16] = "True"; // // else // m_player1val[16] = "False"; // } // // // m_player1val[5] = std::to_string(m->GetSensoryMem()->GetListOfRecentlySensedOpponents().size()); // m_player1val[17] = m->GetWeaponSys()->GetCurrentWeapon()->getName(); // // if (m->GetTargetSys()->GetTarget()) // { // BaseEntity* target = m->GetTargetSys()->GetTarget(); // m_player1val[18] = std::to_string(target->ID()); // } // // // m_player1val[19] = m->m_sMessageReceived; // // m_player1val[20]=std::to_string(m->getContentSize().width* m->getScaleX()); // // m_player1val[21]=std::to_string(m->getContentSize().height * m->getScaleY()); // // // render all target target // //m->GetSensoryMem()->RenderBoxesAroundRecentlySensed(); // // // render the closest with another color // //m->GetTargetSys()->renderClosestTarget(); // // // // concern the tile // // m_player1val[22]= std::to_string(m->getIdTile()); // // m_player1val[23]= std::to_string(m->getTileX()); // // m_player1val[24]= std::to_string(m->getTileY()); // // // m_player1val[25]= std::to_string(Clock->getCurrentTime() ); // // auto map = m_pMap; // auto layer = map->getLayer("Layer 0"); // auto s = layer->getLayerSize(); // // //layer->getTileAt(Vec2(m->getTileX() - 19,m->getTileY() - 9))->setColor(Color3B(0,0,0)); // // if (m->getLeftTile()) // m_player1val[26] = std::to_string(layer->getTileGIDAt( Vec2(m->getTileX() - 1 ,m->getTileY()) )); // // if (m->getRightTile()) // m_player1val[27] = std::to_string(layer->getTileGIDAt( Vec2(m->getTileX() + 1 ,m->getTileY()) )); // // if (m->getUpTile()) // m_player1val[28] = std::to_string(layer->getTileGIDAt( Vec2(m->getTileX() ,m->getTileY() - 1 ) )); // // if (m->getDownTile()) // m_player1val[29] = std::to_string(layer->getTileGIDAt( Vec2(m->getTileX() ,m->getTileY() + 1) )); // // // // if (m->getCurrentTile()) // // m->getCurrentTile()->setColor(Color3B(0,0,0)); // // /* m->renderLeftTile(); // m->renderRightTile(); // m->renderUpTile(); // m->renderDownTile(); //*/ // } // // // create the label // for (int i =0; i< MAX_DISPLAY; i++) // { // //m_tabValue[i] = tabString[i]; // auto label=static_cast<LabelTTF*>(getChildByTag(labId+ i)); // label->setString( m_tabValue[i] +" = "+ m_player1val[i]) ; // } // // m_labTileX->setString("tile { "+std::to_string(m_iTileX) +" ," +std::to_string(m_iTileY)+" }" ); // // m_labMouse->setString("mouse { "+std::to_string((int)m_vMousePos.x) +" ," +std::to_string((int)m_vMousePos.y)+" }" ); // // m_labId->setString("tile id " ); // // m_labWidth->setString("size { "+std::to_string((int)m_TileSize.x) +" ," +std::to_string((int)m_TileSize.y)+" }" ); // // m_lab5->setString(std::to_string(m_Teams[0]->Mineral())); } //----------------------------createButtonTower--------------------- // will create button for building tower //------------------------------------------------------------------ void GamePlayDemo::CreateButtonTower() { // m_Button1 = Button::create("Tower/Tower_Marine.png", // "Tower/Tower_Marine.png"); //m_Button1->setPosition(Vec2( 10,350)); //Layer::addChild(m_Button1); //m_Button1->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildMarineTower, this)); //m_Button2 = Button::create("Tower/Tower_FireBat.png", // "Tower/Tower_FireBat.png"); //m_Button2->setPosition(Vec2( 44,350)); //Layer::addChild(m_Button2); //m_Button2->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildFireTower, this)); //m_Button3 = Button::create("Tower/Tower_Marauder.png", // "Tower/Tower_Marauder.png"); //m_Button3->setPosition(Vec2( 78,350)); //Layer::addChild(m_Button3); //m_Button3->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildMarauderTower, this)); //m_Button4 = Button::create("Tower/Tower_Siege.png", // "Tower/Tower_Siege.png"); //m_Button4->setPosition(Vec2( 112,350)); //Layer::addChild(m_Button4); //m_Button4->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildTankTower, this)); //m_Button5 = Button::create("Tower/Tower_Thor.png", // "Tower/Tower_Thor.png"); //m_Button5->setPosition(Vec2( 146,350)); //Layer::addChild(m_Button5); //m_Button5->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildThorTower, this)); // //// BUTTON FOR HELLION //m_Button6 = Button::create("Tower/Tower_Hellion.png", // "Tower/Tower_Hellion.png"); //m_Button6->setPosition(Vec2( 10,317)); //Layer::addChild(m_Button6); //m_Button6->addTouchEventListener(CC_CALLBACK_2(GamePlayDemo::BuildHellionTower, this)); } //---------------------------------------PrepareBuild----------------------------- // //--------------------------------------------------------------------------------- void GamePlayDemo::PrepareBuild(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (m_bBuildEnabled) return ; switch (type) { case Widget::TouchEventType::BEGAN: m_bBuildEnabled = true; m_bBuildCanceled = false; m_lab1->setString("Preparing to build Tower"); break; }*/ } // cancel building void GamePlayDemo::CancelBuild(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (m_bBuildEnabled == false ) return ; m_bBuildEnabled = false; m_bBuildCanceled = true; m_lab1->setString("Cancel"); m_sNameTower = "Null";*/ } void GamePlayDemo::BuildMarineTower(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerMarine::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerMarine::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerMarine::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Marine Tower"; m_lab1->setString("Preparing to build Marine tower"); m_iSelectedTile = 37; break; } }*/ } void GamePlayDemo::BuildFireTower(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerFireBat::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerFireBat::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerFireBat::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Fire Tower"; m_lab1->setString(m_sNameTower); m_iSelectedTile = 49 ; break; } }*/ } void GamePlayDemo::BuildMarauderTower(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerMarauder::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerMarauder::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerMarauder::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Marauder Tower"; m_lab1->setString(m_sNameTower); m_iSelectedTile = 24 ; break; } }*/ } void GamePlayDemo::BuildTankTower(Ref *pSender/*, Widget::TouchEventType type*/) { /* if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerTank::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerTank::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerTank::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Tank Tower"; m_lab1->setString(m_sNameTower); m_iSelectedTile = 32; break; } }*/ } void GamePlayDemo::BuildThorTower(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerThor::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerThor::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerThor::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Thor Tower"; m_lab1->setString(m_sNameTower); m_iSelectedTile = 31 ; break; } }*/ } void GamePlayDemo::BuildHellionTower(Ref *pSender/*, Widget::TouchEventType type*/) { /*if (!m_bBuildEnabled || m_Teams[0]->Mineral() < TowerHellion::m_iGoldCost ) return ; if (Clock->getCurrentTime() > TowerMarine::m_fNextTimeBuilding ) { TowerHellion::m_fNextTimeBuilding = Clock->getCurrentTime() + TowerHellion::m_iBuildTime; switch (type) { case Widget::TouchEventType::BEGAN: m_sNameTower = "Hellion Tower"; m_lab1->setString(m_sNameTower); m_iSelectedTile = 50 ; break; } }*/ } // add all ship on the map void GamePlayDemo::addAllShips() { // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(600,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); //////// // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); ////////// // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,100),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,100),m_Teams[1]->ID()); // addShip("ShipAlien6",Vec2(500,110),m_Teams[1]->ID()); // addShip("ShipAlien6",Vec2(500,433),m_Teams[1]->ID()); //// // addShip("ShipAlien6",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien6",Vec2(250,110),m_Teams[1]->ID()); //// // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien3",Vec2(250,110),m_Teams[1]->ID()); //// // // // // mass lurker // // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); //// // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); ////// // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); //// // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // // // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); //// // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); // addShip("ShipAlien2",Vec2(250,110),m_Teams[1]->ID()); //// // } // will restart the game //void GamePlayDemo::onRestart(Ref *pSender/*, Widget::TouchEventType type*/) //{ //// //// auto layer = m_pMap->getLayer("Layer 0"); //// //// std::map<Vec2,int>::iterator it = m_pKeyTilesId.begin(); //// //// switch (type) //// { //// case Widget::TouchEventType::BEGAN: //// //// // inactivate buttons //// //// InactivateButtons(); //// //// // change status to restarting //// //// //// setRestarting(); //// //// //GamePlay::onExit(pSender,type); //// //// //m_bDeleteAllShip = false; //// //// m_bDeleteAllShip = true; //// deleteAll(); //// //// updateNextTimeRestart(); //// //GamePlay::onRestart(pSender,type); //// //// //reStart(); //// //// ////// ////// // must be called first ////// addTeam(); ////// ////// // layer->setTileGID(20,Vec2(0,0)); ////// // add the wall ////// /*layer->setTileGID(20,Vec2(0,0)); ////// if (layer->getTileAt(Vec2(0,0))) ////// layer->getTileAt(Vec2(0,0))->setPositionX(layer->getTileAt(Vec2(0,0))->getPositionX() + 170 ); //////*/ ////// //layer->getTileAt(Vec2(0,0)) ////// //createMap(); ////// ////// ////// // create the map bu using the key Value ////// // holding tilegdi and position ////// ////// ////// for (it ; it != m_pKeyTilesId.end(); it++) ////// { ////// layer->setTileGID(it->second,it->first); ////// if (m_bRestarted == false ) ////// { ////// // layer->getTileAt(it->first)->setPositionX(layer->getTileAt(it->first)->getPositionX() + 170 ); ////// ////// } ////// } ////// ////// m_bRestarted = true ; ////// ////// ////// // create the map ////// ////// createMap(); ////// ////// // adding ship ////// ////// ////// addAllShips(); //// //// break ; //// //// default : //// //// break; //// //// } // //} //void GamePlayDemo::onExit(Ref *pSender/*, Widget::TouchEventType type*/) //{ //// switch (type) //// { //// //// case Widget::TouchEventType::BEGAN: //// exit(); //// m_fNextTimeExiting = Clock->getCurrentTime() + m_fTimeRestarting ; //// InactivateButtons(); //// //setExited(); //// // m_bDeleteAllShip = true; //// //deleteAll(); //// //// break; //// //// default : //// //// break; //// } //// //static_cast<LayerMultiplex*>(_parent)->switchTo(0); //} void GamePlayDemo::reStart() { //SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/terran-1.mp3", false); //auto layer = m_pMap->getLayer("Layer 0"); // //std::map<Vec2,int>::iterator it = m_pKeyTilesId.begin(); // // must be called first // addTeam(); // // create the map by using the key Value // // holding tilegdi and position // for (it ; it != m_pKeyTilesId.end(); it++) // { // layer->setTileGID(it->second,it->first); // if (m_bRestarted == false ) // { // // layer->getTileAt(it->first)->setPositionX(layer->getTileAt(it->first)->getPositionX() + 170 ); // // } // } // m_bRestarted = true ; // // create the map // createMap(); // // adding ship // addAllShips(); // // change status to playing // setPlaying(); // // activate buttons // activateButtons(); // } void GamePlayDemo::Exit() { //setBeforeExiting(); //deleteAll(); //SimpleAudioEngine::getInstance()->playBackgroundMusic("Music/heroes3_main_menu.mp3"); //// switch to main menu //// wait before exiting // //static_cast<LayerMultiplex*>(_parent)->switchTo(0); }
#pragma once enum ParseType { COUNT_OCCURENCES, REPLACE_OCCURENCES };
/** * created: 2013-4-6 23:18 * filename: FKLogger * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include "../Include/FKLogger.h" #include "../Include/FKTime.h" #include <time.h> #include "../Include/Dump/FKDumpErrorBase.h" #include "../Include/FKBaseDefine.h" //------------------------------------------------------------------------ class stUpdatLogFileThread : public CThread { public: stUpdatLogFileThread():CThread(true,NULL){} ~stUpdatLogFileThread(){ save(); Resume(); Terminate(); Waitfor(); INFOLOCK(zLogger::m_loggers); zLogger::m_loggers.clear(); UNINFOLOCK(zLogger::m_loggers); } virtual int Run(void *pvParam); static bool save(); }; //------------------------------------------------------------------------ stUpdatLogFileThread UpdatLogFileThread; //------------------------------------------------------------------------ zLogger::zLogger(const std::string &name) { m_ShowLogFunc=NULL; m_nShowLvl=2; m_nWriteLvl=-1; m_nLogidx=0; m_ncurpos=0; m_nlogbytes=0x7fffffff; m_msgbuf[m_ncurpos]=0; m_basefilepath=""; m_name=""; if (name!=""){ m_basefilepath="./log/"; m_basefilepath += name; m_basefilepath += "/"; setName(name); } m_nZoneID=0; m_boFor360=false; AILOCKT(m_loggers); m_loggers.push_back(this); } //------------------------------------------------------------------------ zLogger::~zLogger(){ AILOCKT(m_loggers); m_loggers.erase(remove(m_loggers.begin(),m_loggers.end(),this),m_loggers.end()); m_ShowLogFunc=NULL; } //------------------------------------------------------------------------ void zLogger::ShowLog(zLevel& level,const char* logtime,const char* pszMsg){ FUNCTION_BEGIN; if (pszMsg && m_ShowLogFunc){ m_ShowLogFunc(level,logtime,(char *)pszMsg); } } //------------------------------------------------------------------------ const std::string & zLogger::getName(){ return m_name; } //------------------------------------------------------------------------ void zLogger::setName(const std::string & setName){ m_name=setName; } //------------------------------------------------------------------------ int zLogger::strlevltoint(const std::string & level) { if (stricmp("off",level.c_str())==0) return zLogger::eOFF; else if (stricmp("fatal",level.c_str())==0) return zLogger::eFATAL; else if (stricmp("alarm",level.c_str())==0) return zLogger::eALARM; else if (stricmp("error",level.c_str())==0) return zLogger::eERROR; else if (stricmp("iffy",level.c_str())==0) return zLogger::eIFFY; else if (stricmp("warn",level.c_str())==0 || stricmp("warning",level.c_str())==0) return zLogger::eWARN; else if (stricmp("trace",level.c_str())==0) return zLogger::eTRACE; else if (stricmp("info",level.c_str())==0) return zLogger::eINFO; else if (stricmp("gbug",level.c_str())==0) return zLogger::eGBUG; else if (stricmp("debug",level.c_str())==0) return zLogger::eDEBUG; else if (stricmp("all",level.c_str())==0 || stricmp("always",level.c_str())==0) return zLogger::eALL; else { return atoi(level.c_str()); } } //------------------------------------------------------------------------ void zLogger::setLevel(int writelevel,int showlvl) { FUNCTION_BEGIN; m_nWriteLvl=writelevel; m_nShowLvl=showlvl; } //------------------------------------------------------------------------ void zLogger::SetZoneID(int nZoneID) { if (nZoneID!=0) { m_nZoneID=nZoneID; } } //------------------------------------------------------------------------ void zLogger::SetBoFor360(bool boYesNo) { m_boFor360=boYesNo; } //------------------------------------------------------------------------ void zLogger::setLevel(const std::string & writelevel,const std::string & showlvl) { FUNCTION_BEGIN; m_nWriteLvl=strlevltoint(writelevel); m_nShowLvl=strlevltoint(showlvl); } //------------------------------------------------------------------------ void zLogger::fixlogpath(std::string &basepath) { char szSvridxPath[MAX_PATH]={0}; strcpy_s(szSvridxPath,sizeof(szSvridxPath),basepath.c_str()); int nPathLen=strlen(szSvridxPath); if (nPathLen>0) { replaceFrontlashPath(szSvridxPath); if (szSvridxPath[nPathLen-1]=='\\') { szSvridxPath[nPathLen-1]='\0'; nPathLen--; } basepath=szSvridxPath; } } //------------------------------------------------------------------------ bool zLogger::SetLocalFileBasePath(const std::string &basefilepath) { FUNCTION_BEGIN; m_nlogbytes=0x7fffffff; m_basefilepath=basefilepath; fixlogpath(m_basefilepath); UpdatLogFileThread.Start(false,NULL); return CheckLogPath(); } //------------------------------------------------------------------------ const int TEMPBUFSIZE=1024*10; //------------------------------------------------------------------------ #define _ZLOGGER_TIMEFORMAT_ "%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d" #define _ZLOGGER_TIMELEN_ 20 //------------------------------------------------------------------------ bool zLogger::logbylevel(zLevel& level,const char *tempmessage) { FUNCTION_BEGIN; if (tempmessage && (level.showlevel<=m_nShowLvl || level.writelevel<=m_nWriteLvl)){ char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "%.8s (%u:%d:%d) %s\r\n",level.name ,m_nLogidx,::GetCurrentProcessId(),::GetCurrentThreadId(),tempmessage); if (level.showlevel<=m_nShowLvl){ ShowLog(level,message,&message[_ZLOGGER_TIMELEN_]); } if (level.writelevel<=m_nWriteLvl){ message[_ZLOGGER_TIMELEN_-1]='\x20'; if (level.realtimewrite){ WriteLog(message,strlen(message)); }else{ AddMsg2buf(message,strlen(message)); } } return true; } return false; } //------------------------------------------------------------------------ bool zLogger::log(zLevel& level,const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (level.showlevel<=m_nShowLvl || level.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(level,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::realtimeLog(zLevel& level,const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (level.showlevel<=m_nShowLvl || m_nWriteLvl>=0)){ char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "%.8s (%u:%d:%d) %s\r\n",level.name ,m_nLogidx,::GetCurrentProcessId(),::GetCurrentThreadId(),tempmessage); if (level.showlevel<=m_nShowLvl){ ShowLog(level,message,&message[_ZLOGGER_TIMELEN_]); } if (m_nWriteLvl>=0){ message[_ZLOGGER_TIMELEN_-1]='\x20'; WriteLog(message,strlen(message)); } return true; } return false; } //------------------------------------------------------------------------ bool zLogger::forceLog(zLevel& level,const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (m_nShowLvl>=0 || m_nWriteLvl>=0)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "%.5s (force:%u:%d:%d) %s\r\n",level.name,m_nLogidx,::GetCurrentProcessId(),::GetCurrentThreadId(),tempmessage); if (m_nShowLvl>=0){ ShowLog(zFORCE,message,&message[_ZLOGGER_TIMELEN_]); } if (m_nWriteLvl>=0){ message[_ZLOGGER_TIMELEN_-1]='\x20'; if (level.realtimewrite){ WriteLog(message,strlen(message)); }else{ AddMsg2buf(message,strlen(message)); } } return true; } return false; } //------------------------------------------------------------------------ bool zLogger::debug(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zDEBUG.showlevel<=m_nShowLvl || zDEBUG.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zDEBUG,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::error(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zERROR.showlevel<=m_nShowLvl || zERROR.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zERROR,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::error_out(const char * pattern) { FUNCTION_BEGIN; if (pattern && (zERROR.showlevel<=m_nShowLvl || zERROR.writelevel<=m_nWriteLvl)) { logbylevel(zERROR,pattern); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::info(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zINFO.showlevel<=m_nShowLvl || zINFO.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zINFO,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::fatal(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zFATAL.showlevel<=m_nShowLvl || zFATAL.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zFATAL,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::warn(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zWARN.showlevel<=m_nShowLvl || zWARN.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zWARN,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::alarm(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zALARM.showlevel<=m_nShowLvl || zALARM.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zALARM,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::iffy(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zIFFY.showlevel<=m_nShowLvl || zIFFY.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zIFFY,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::trace(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zTRACE.showlevel<=m_nShowLvl || zTRACE.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zTRACE,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::gbug(const char * pattern, ...) { FUNCTION_BEGIN; if (pattern && (zGBUG.showlevel<=m_nShowLvl || zGBUG.writelevel<=m_nWriteLvl)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); logbylevel(zGBUG,tempmessage); return true; } return false; } //------------------------------------------------------------------------ bool zLogger::WriteLog(char* pmsg,int nlen) { FUNCTION_BEGIN; AddMsg2buf(pmsg,nlen); UpdatLogFile(); return true; } //------------------------------------------------------------------------ bool zLogger::CheckLogPath() { FUNCTION_BEGIN; if (m_nlogbytes>=(MSGBUF_MAX*2-1024)) { char filepath[MAX_PATH]={0}; strcpy_s(filepath,sizeof(filepath),m_basefilepath.c_str()); int nPathLen=strlen(filepath); if (nPathLen<=0){ return false;} replaceFrontlashPath(filepath); if (!(filepath[nPathLen-1]=='\\')){ filepath[nPathLen]='\\'; nPathLen++; } if (!m_boFor360) { time_t ti = time(NULL); tm* t = localtime(&ti); sprintf_s(&filepath[nPathLen],sizeof(filepath)-nPathLen,"%.4d%.2d%.2d\\\0",t->tm_year+1900, t->tm_mon+1, t->tm_mday); char szfile[MAX_PATH]={0}; sprintf_s(szfile,sizeof(szfile),"%s%.2d%.2d%.2d.log\0",filepath,t->tm_hour, t->tm_min,t->tm_sec); m_logout.SetFileName(szfile); FileSystem::createPath(filepath); m_nlogbytes=0; } else { time_t ti = time(NULL); tm* t = localtime(&ti); char szfile[MAX_PATH]={0}; sprintf_s(szfile,sizeof(szfile),"%s%s_S%d_%.2d%.2d%.2d.log\0",filepath,"xyol",m_nZoneID,t->tm_year+1900, t->tm_mon+1, t->tm_mday); char sztime[MAX_PATH]={0}; sprintf_s(sztime,sizeof(sztime),"%.2d%.2d%.2d",t->tm_year+1900, t->tm_mon+1, t->tm_mday); m_logout.Set360FileTime(sztime); m_logout.SetFileName(szfile); FileSystem::createPath(filepath); m_nlogbytes=0; } return true; }else if (!FileSystem::IsFileExist(m_logout.GetFileName())){ FileSystem::createPath(extractfilepath(m_logout.GetFileName())); } return false; } //------------------------------------------------------------------------ bool zLogger::UpdatLogFile() { FUNCTION_BEGIN; AILOCKP(n_logInpLock); if (m_ncurpos>0) { CheckLogPath(); m_nlogbytes += m_ncurpos; if (!m_boFor360) { m_logout.WriteString(m_msgbuf); } else { } InterlockedIncrement(&m_nLogidx); m_ncurpos=0; m_msgbuf[m_ncurpos]=0; return true; } return false; } //------------------------------------------------------------------------ bool zLogger::AddMsg2buf(char* pmsg,int nlen) { FUNCTION_BEGIN; if (nlen<1024*8) { AILOCKP(n_logInpLock); int n=m_ncurpos+nlen; if (n>=(MSGBUF_MAX-1024)) { UpdatLogFile(); n=m_ncurpos+nlen; if (n>=(MSGBUF_MAX-1024)) { char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "[ Error:ÈÕÖ¾»º³åÇø²»×ã(%u : %u : %u) ] %s\r\n",m_ncurpos,nlen,m_nlogbytes,pmsg); zLogger::zLevel tempFATAL("FATAL",zLogger::eFATAL,zLogger::eFATAL,true); ShowLog(tempFATAL,message,&message[_ZLOGGER_TIMELEN_]); message[_ZLOGGER_TIMELEN_-1]='\x20'; m_logout.WriteString(message); return false; } } memcpy(&m_msgbuf[m_ncurpos],pmsg,nlen); m_ncurpos+=nlen; m_msgbuf[m_ncurpos]=0; return true; } return false; } //------------------------------------------------------------------------ bool zLogger::save(){return stUpdatLogFileThread::save();} //------------------------------------------------------------------------ bool zLogger::lualog( zLevel& level, const char * pattern, ... ) { if (pattern && (m_nShowLvl>=0 || m_nWriteLvl>=0)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "%.5s (force:%u:%d:%d) %s\r\n",level.name,m_nLogidx,::GetCurrentProcessId(),::GetCurrentThreadId(),tempmessage); if (m_nWriteLvl>=0) { message[_ZLOGGER_TIMELEN_-1]='\x20'; WriteLog(message,strlen(message)); } return true; } return false; } //------------------------------------------------------------------------ bool zLogger::forceLogFile( zLevel& level,const char * pattern, ... ) { if (pattern && (m_nShowLvl>=0 || m_nWriteLvl>=0)) { char tempmessage[TEMPBUFSIZE]={0}; va_list ap; va_start(ap, pattern); _safe_vsnprintf(tempmessage, (sizeof(tempmessage)) - 32, pattern, ap); va_end(ap); char message[TEMPBUFSIZE]={0}; timetostr(time(NULL),message,_ZLOGGER_TIMELEN_,_ZLOGGER_TIMEFORMAT_); message[_ZLOGGER_TIMELEN_-1]=0; sprintf_s(&message[_ZLOGGER_TIMELEN_],sizeof(message)-32, "%.5s (force:%u:%d:%d) %s\r\n",level.name,m_nLogidx,::GetCurrentProcessId(),::GetCurrentThreadId(),tempmessage); if (m_nShowLvl>=0){ ShowLog(zFORCE,message,&message[_ZLOGGER_TIMELEN_]); } if (m_nWriteLvl>=0){ message[_ZLOGGER_TIMELEN_-1]='\x20'; if (level.realtimewrite){ WriteLog(message,strlen(message)); }else{ AddMsg2buf(message,strlen(message)); } } return true; } return false; } //------------------------------------------------------------------------ bool stUpdatLogFileThread::save() { CSyncVector<zLogger*> m_templist; INFOLOCK(zLogger::m_loggers); CSyncVector<zLogger*>::iterator it; for (it=zLogger::m_loggers.begin();it!= zLogger::m_loggers.end();it++){ if ((*it)!=NULL){ m_templist.push_back(*it);}; } UNINFOLOCK(zLogger::m_loggers); for (it=m_templist.begin();it!= m_templist.end();it++){ (*it)->UpdatLogFile(); } return true; } //------------------------------------------------------------------------ int stUpdatLogFileThread::Run(void *pvParam){ time_t dwRunTime=0; SetPriority(THREAD_PRIORITY_IDLE); CSyncVector<zLogger*> m_templist; while (!IsTerminated()){ INFOLOCK(zLogger::m_loggers); CSyncVector<zLogger*>::iterator it; if (zLogger::m_loggers.size()>0){ if (time(NULL)>dwRunTime){ dwRunTime=time(NULL)+3; for (it=zLogger::m_loggers.begin();it!= zLogger::m_loggers.end();it++){ if (_random_d(10)<=2){if ((*it)!=NULL){ m_templist.push_back(*it);};} } } } UNINFOLOCK(zLogger::m_loggers); if (m_templist.size()>0){ for (it=m_templist.begin();it!= m_templist.end();it++){ (*it)->UpdatLogFile(); } } m_templist.clear(); Sleep(1000); } save(); return 0; } //------------------------------------------------------------------------
// Author : chenwj // time : 2017/1/16 // Copyright :All rights reserved by chenwj @copyright 2017 ~ 2018. // // Use of this source code is governed by a BSD-style license // that can be found in the License file. //////////////////////////////////////////////////////////////////////// #include "coder.h" #include <arpa/inet.h> namespace net{ Coder::Coder() : buf_size_(0) , buf_(NULL) , buf_index_(-1) { } Coder::~Coder() { } // set Msg name void Coder::setMsgName(const string& name) { msg_name_ = name; } // set msg data (protobuf data) void Coder::setBody(const string& body) { body_ = body; } // encoding the data to buff void Coder::encoding() { uint32_t len = sizeof(uint32_t) // msg_len + msg_name_.length() // msg name + body_.length() // protobuf data (body) + sizeof(uint32_t); // check sum data_.resize(len + sizeof(uint32_t)); // total transport data length const char * buff = &*data_.begin(); u_int32_t index = 0; // len uint32_t header = htonl(len); memcpy((void*)buff, (void*)&header, sizeof(uint32_t)); index += sizeof(uint32_t); // msg len uint32_t msg_len = htonl(msg_name_.length()); memcpy((void*)(buff + index), &msg_len, sizeof(uint32_t)); index += sizeof(uint32_t); // msg name memcpy((void*)(buff + index), &*msg_name_.begin(), msg_name_.length()); index += msg_name_.length(); // protobuf data(body) memcpy((void*)(buff + index), &*body_.begin(), body_.length()); index += body_.length(); // check sum TODO:: only a test uint32_t check_sum = htonl(0); memcpy((void*)(buff + index), &check_sum, sizeof(check_sum)); } // get encoding data buffer const string & Coder::getData() { return data_; } // get Msg name string Coder::getMsgName() { return msg_name_; } string Coder::getBody() { return body_; } // decoding the data from buff void Coder::decoding(const char * buff, int size) { int index = 0; uint32_t len = 0; // msg_len memcpy(&len, buff, sizeof(uint32_t)); index += sizeof(uint32_t); uint32_t msg_len = ntohl(len); // msg name msg_name_.resize(msg_len); memcpy(&*msg_name_.begin(), (void*)(buff + index), msg_len); index += msg_len; // protobuf data(body) uint32_t body_len = size - sizeof(uint32_t) - msg_len - sizeof(uint32_t); body_.resize(body_len); memcpy(&*body_.begin(), (void*)(buff + index), body_len); index += body_len; uint32_t check_sum = 0; memcpy(&check_sum, (void*)(buff + index), sizeof(uint32_t)); } } // !namespace net
#include <iostream> using namespace std; int yearday(int year); int monthday(int month,int year); int main() { int date,tian,year,month,day; char da[9]; cin>>date>>tian; year=date/10000; month=(date-year*10000)/100; day=date%100; for (int i = 1; i < month; ++i) { tian=tian+monthday(i,year); } tian=tian+day-1; month=1; day=1; while(yearday(year)<=tian){ tian=tian-yearday(year); year++; } if(year>9999) {cout<<"out of limitation!"; return 0;} while(monthday(month,year)<=tian){ tian=tian-monthday(month,year); month++; } day=tian+day; da[7] = static_cast<char>(48 + day % 10); da[6] = static_cast<char>(48 + day / 10); da[5] = static_cast<char>(48 + month % 10); da[4] = static_cast<char>(48 + month / 10); da[3] = static_cast<char>(48 + year % 10); da[2] = static_cast<char>(48 + year % 100 / 10); da[1] = static_cast<char>(48 + year / 100 % 10); da[0] = static_cast<char>(48 + year / 100 / 10); da[8]='\0'; cout<<da; return 0; } int yearday(int year){ return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 366 : 365; } int monthday(int month,int year){ switch (month){ case 1:case 3:case 5:case 7:case 8:case 10: case 12:return 31; case 4:case 6:case 9:case 11:return 30; case 2: return yearday(year) == 365 ? 28 : 29; } }
#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> #include <sstream> 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; #define N 5555 #define M 11111 vector< pair<int, int> > g[N]; int w1[N], w2[N]; int n1, n2, m, pr[N], was[N]; int ex[M], ey[M], IT = 0; pair<int, int> p[N]; int lastit[N], lastans[N]; int trykuhn(int y) { if (pr[y] == -1) return w2[y]; if (lastit[y] == IT) return lastans[y]; lastit[y] = IT; lastans[y] = -1; int x = pr[y], maxx = -1; for (int i = 0; i < g[x].size(); ++i) if (g[x][i].second != y) maxx = max(maxx, trykuhn(g[x][i].second)); lastans[y] = maxx; return maxx; } void makekuhn(int x, int y) { if (pr[y] == -1) { pr[y] = x; return; } int py = pr[y]; for (int i = 0; i < g[py].size(); ++i) if (g[py][i].second != y) if (lastans[y] == lastans[g[py][i].second]) { pr[g[py][i].second] = py; pr[y] = x; makekuhn(py, g[py][i].second); return; } } bool kuhn(int x) { if (was[x] == IT) return false; was[x] = IT; int maxx = -1, maxy = 0; for (int i = 0; i < g[x].size(); ++i) { int y = g[x][i].second; int d = trykuhn(y); if (d > maxx) { maxx = d; maxy = y; } } if (maxx >= 0) { int y = maxy; makekuhn(x, y); pr[y] = x; return true; } return false; } int main() { freopen("matching.in", "r", stdin); freopen("matching.out", "w", stdout); scanf("%d%d%d", &n1, &n2, &m); for (int i = 1; i <= n1; ++i) { scanf("%d", &w1[i]); p[i - 1].second = i; p[i - 1].first = w1[i]; } for (int i = 1; i <= n2; ++i) { scanf("%d", &w2[i]); } for (int i = 0; i < m; ++i) { int x, y; scanf("%d%d", &x, &y); g[x].push_back(make_pair(-w2[y], y)); ex[i] = x; ey[i] = y; } for (int i = 1; i <= n1; ++i) { sort(g[i].begin(), g[i].end()); } sort(p, p + n1); memset(pr, -1, sizeof(pr)); for (int i = n1 - 1; i >= 0; --i) { ++IT; kuhn(p[i].second); } LL w = 0; int cnt = 0; for (int i = 1; i <= n2; ++i) if (pr[i] != -1) { ++cnt; w += w1[pr[i]] + w2[i]; } cout << w << endl; cout << cnt << endl; for (int i = 0; i < m; ++i) { if (pr[ey[i]] == ex[i]) { cout << i + 1 << " "; pr[ey[i]] = -1; } } puts(""); return 0; }
#include <stdio.h> int main(void) { printf("Я Оксана Боярко.\nСтудентка группы ЗПИ-ЗП73, кафедра АПЕПС, КПИ.\nВариант №3. \n"); return 0; }
// // Created by faris on 4/26/2020. // #ifndef FINALPROJECT_TSHAPE_H #define FINALPROJECT_TSHAPE_H #include <Box2D/Box2D.h> #include <vector> #include <cinder/gl/gl.h> #include <mylibrary/Shape.h> using namespace ci; class TShape : public Shape{ public: TShape(b2World* world, const vec2 &pos); b2Body* m_body; int Tid; }; #endif // FINALPROJECT_TSHAPE_H
#ifndef TIME_HPP #define TIME_HPP #include <iostream> float to_total_seconds(float minutes, float seconds, float ms); class Time { public: Time(); Time(float total_seconds); Time(int minutes, int seconds, int ms = 0); int get_minutes() const; int get_seconds() const; int get_ms() const; float get_total_seconds() const; private: int minutes; int seconds; int ms; float total_seconds; friend std::ostream& operator<<(std::ostream &os, const Time &ft); }; std::ostream& operator<<(std::ostream &os, const Time &ft); Time operator+(const Time &a, const Time &b); #endif
#include <stdio.h> #include "gcc-plugin.h" #include "tree.h" int plugin_is_GPL_compatible; static void dump_enum_type (tree enum_type, tree enum_name) { printf ("\"%s\":\n", IDENTIFIER_POINTER (enum_name)); /* Process all its enumerators. */ for (tree v = TYPE_VALUES (enum_type); v != NULL; v = TREE_CHAIN (v)) { /* Get its value if it's a convenient integer, give up otherwise. */ char buffer[128] = "\"<big integer>\""; if (tree_fits_shwi_p (TREE_VALUE (v))) { long l = tree_to_shwi (TREE_VALUE (v)); snprintf (buffer, 128, "%li", l); } printf (" \"%s\": %s\n", IDENTIFIER_POINTER (TREE_PURPOSE (v)), buffer); } } static void handle_finish_type (void *gcc_data, void *user_data) { (void) user_data; tree t = (tree) gcc_data; /* Skip everything that is not a named enumeration type. */ if (TREE_CODE (t) != ENUMERAL_TYPE || TYPE_NAME (t) == NULL) return; dump_enum_type (t, TYPE_NAME (t)); } static void handle_finish_decl (void *gcc_data, void *user_data) { (void) user_data; tree t = (tree) gcc_data; tree type = TREE_TYPE (t); /* Skip everything that is not a typedef for an enumeration type. */ if (TREE_CODE (t) != TYPE_DECL || TREE_CODE (type) != ENUMERAL_TYPE) return; dump_enum_type (type, DECL_NAME (t)); } int plugin_init (struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { const char *plugin_name = plugin_info->base_name; struct plugin_info pi = { "0.1", "Enum binder plugin" }; (void) version; register_callback (plugin_name, PLUGIN_INFO, NULL, &pi); register_callback (plugin_name, PLUGIN_FINISH_TYPE, &handle_finish_type, NULL); register_callback (plugin_name, PLUGIN_FINISH_DECL, &handle_finish_decl, NULL); return 0; }
// Copyright (C) 2012 - 2013 Mihai Preda #pragma once #include "value.h" #include "Vector.h" #include "Index.h" class GC; struct NameValue; class Map { Vector<Value> vals; Index index; Map(); void grow(); void setVectors(Vector<Value> *keys, Vector<Value> *vals); void setArrays(Value *keys, Value *vals, int size); Value remove(Value key); // returns previous value or NIL bool contains(Value key) { return index.getPos(key) >= 0; } public: static Map *alloc(GC *gc, unsigned sizeHint = 0); static Value makeMap(GC *gc, ...); static Value keysField(VM *vm, int op, void *data, Value *stack, int nArgs); ~Map(); int size() { return index.size(); } void traverse(GC *gc); Value indexGet(Value key); bool indexSet(Value key, Value val); Map *copy(GC *gc); void add(Value v); bool equals(Map *o); Value *keyBuf() { return index.getBuf(); } Value *valBuf() { return vals.buf(); } };
#include "Kosaraju.h" #include "Bellman_Ford.h" #include "Johnson.h" int main(int argc, char **argv){ demo_Kosaraju(); demo_Bellman_Ford(); demo_Johnson(); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { long long i,j,a,k,arr[1000],m; while(scanf("%lld",&a)!=EOF){ if(a==0) break; m=0; k=a; if(a<0){ printf("%lld = -1 x",a); a=a*-1; } else printf("%lld =",a); for(i=2;i<=sqrt(a);i++){ while(a%i==0){ arr[m]=i; m++; a=a/i; } } if(a>2){ arr[m]=a; m++; } for(j=0;j<m-1;j++){ printf(" %lld x",arr[j]); } printf(" %lld\n",arr[m-1]); } return 0; }
class USP_DZ : Colt1911 { scope = 2; displayName = $STR_DZ_WPN_USP_NAME; descriptionShort = $STR_DZ_WPN_USP_DESC; model = "\RH_de\RH_usp.p3d"; picture = "\RH_de\inv\usp.paa"; begin1[] = {"\RH_de\sound\usp.wss",0.794328,1,800}; soundBegin[] = {"begin1",1}; reloadMagazineSound[] = {"\RH_de\sound\usp_reload.wss",0.1,1,20}; magazines[] = {"15Rnd_45ACP_USP"}; class FlashLight { color[] = {0.9,0.9,0.7,0.9}; ambient[] = {0.1,0.1,0.1,1.0}; position = "flash dir"; direction = "flash"; angle = 30; scale[] = {1,1,0.5}; brightness = 0.1; }; class Attachments { Attachment_Sup45 = "USP_SD_DZ"; }; }; class USP_SD_DZ: USP_DZ { displayName = $STR_DZ_WPN_USPSD_NAME; descriptionShort = $STR_DZ_WPN_USPSD_DESC; model = "\RH_de\RH_uspsd.p3d"; picture = "\RH_de\inv\uspsd.paa"; begin1[] = {"\RH_de\sound\uspsd.wss",0.316228,1,200}; soundBegin[] = {"begin1",1}; reloadMagazineSound[] = {"\RH_de\sound\usp_reload.wss",0.031623,1,20}; magazines[] = {"15Rnd_45ACP_USPSD"}; class ItemActions { class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup45',_id,'USP_DZ'] call player_removeAttachment"; }; }; };
#include "Device.h" #include "SwapChain.h" #include "Keng/WindowSystem/IWindow.h" #include "Resource/Texture/DeviceTexture.h" #include "DepthStencil.h" #include "Keng/GraphicsCommon/WindowRenderTargetParameters.h" #include "RenderTarget/WindowRenderTarget.h" #include "EverydayTools/Exception/ThrowIfFailed.h" namespace keng::graphics::gpu { WindowRenderTarget::WindowRenderTarget(Device& device, const WindowRenderTargetParameters& params, window_system::IWindow& window) { m_device = &device; m_swapChain = SwapChainPtr::MakeInstance(device, params.swapChain, window); D3D11_BLEND_DESC desc{}; desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; WinAPI<char>::ThrowIfError(m_device->GetDevice()->CreateBlendState(&desc, m_blendState.Receive())); } void WindowRenderTarget::AssignToPipeline(const IDepthStencilPtr& depthStencil) { auto rtv = m_swapChain->GetCurrentTexture().GetView<ResourceViewType::RenderTarget>(); core::Ptr<TextureView<ResourceViewType::DepthStencil>> dsv; if (depthStencil) { auto castedDepthStencil = std::dynamic_pointer_cast<DepthStencil>(depthStencil); edt::ThrowIfFailed(castedDepthStencil, "Custom depth stencil implementation is not supported"); dsv = castedDepthStencil->GetView(); } m_device->SetRenderTarget(*rtv, dsv.Get()); m_device->GetContext()->OMSetBlendState(m_blendState.Get(), 0, 0xFFFFFFFF); } void WindowRenderTarget::Clear(const float(&flatColor)[4]) { auto rtv = m_swapChain->GetCurrentTexture().GetView<ResourceViewType::RenderTarget>(); m_device->GetContext()->ClearRenderTargetView(rtv->GetView(), flatColor); } void WindowRenderTarget::CopyFrom(const ITexture& abstract) { CallAndRethrowM + [&] { auto from = static_cast<const DeviceTexture&>(abstract); m_swapChain->CopyFromTexture(from); }; } void WindowRenderTarget::Present() { m_swapChain->Present(); } }
#include "Paddle.h" /* Constructor for the paddle. Initialize all parameters and update the model matrix */ Paddle::Paddle(std::string name, unsigned int width, unsigned int height, float x, float y, glm::vec3 color) : Square(name, color, glm::mat3(1), true) { this->width = width; this->height = height; this->position = glm::vec2(x, y); updateModelMatrix(); } /* Destructor for the paddle */ Paddle::~Paddle() { } /* Update the model matrix. Multiply the position and the scale matrix. */ void Paddle::updateModelMatrix() { glm::mat3 scaleMatrix = Transform2D::Scale((float)this->width, (float)this->height); glm::mat3 positionMatrix = Transform2D::Translate((float)this->position.x, (float)this->position.y); this->SetModelMatrix(positionMatrix * scaleMatrix); } /* Getter for width */ unsigned int Paddle::GetWidth() { return this->width; } /* Getter for height */ unsigned int Paddle::GetHeight() { return this->height; } /* Getter for size */ glm::vec2 Paddle::GetSize() { return glm::vec2(GetWidth(), GetHeight()); } /* Getter for position */ glm::vec2 Paddle::GetPosition() { return this->position; } /* Update the position of the paddle. The x coordinate is given by the position of the mouse on the screen. */ void Paddle::Update(glm::vec2 mousePosition) { position.x = mousePosition.x; updateModelMatrix(); }
/* * draughtpiece.cpp * The draught pieces to move on the gameboard. * * @author Yoan DUMAS * @versionn 1.0 * @date 18/12/2013 */ #include <QPainter> #include "draughtpiece.h" DraughtPiece::DraughtPiece(const position_t & inPosition, const color_t & inColor, const state_t & inState) : Piece(inPosition, inColor), state_(inState) {} DraughtPiece::DraughtPiece(const DraughtPiece & inDraughtpiece) : Piece( inDraughtpiece), state_(inDraughtpiece.getState()) {} DraughtPiece::~DraughtPiece() {} state_t DraughtPiece::getState() const { return state_; } void DraughtPiece::setState(const state_t & inState) { state_ = inState; } QPixmap * DraughtPiece::draw() const { QPixmap * image = new QPixmap(75, 75); QPainter painter(image); painter.setRenderHint(QPainter::Antialiasing, true); // Draw the background painter.setBrush(QBrush(Qt::white, Qt::SolidPattern)); painter.drawRect(0, 0, 75, 75); // Draw the Piece painter.setBrush(QBrush((getColor() == WHITE) ? Qt::white : Qt::black, Qt::SolidPattern)); painter.drawEllipse(5, 5, 65, 65); if(getState() == SUPER) { // Update the color QPen pen = painter.pen(); pen.setColor((getColor() == WHITE) ? Qt::black : Qt::white); painter.setPen(pen); // Write a S QFont font = painter.font(); font.setBold(true); font.setPointSize(24); painter.setFont(font); painter.drawText(30, 47, "S"); } painter.end(); return image; } bool DraughtPiece::isReachableIter(const int & direction, const int & orientation) const { position_t p = getPosition(); if(p.i + orientation >= 0 && p.i + orientation < DB_LENGTH && p.j + direction >= 0 && p.j + direction < DB_LENGTH) { return true; } return false; } std::vector<position_t> DraughtPiece::isReachable(const int & direction) const { std::vector<position_t> vect; position_t p = getPosition(), pToAdd; for( int orientation = -1 ; orientation < 2 ; orientation += 2) { if(isReachableIter(direction, orientation)) { pToAdd.i = p.i + orientation; pToAdd.j = p.j + direction; vect.push_back(pToAdd); } } return vect; } std::vector<position_t> DraughtPiece::getReachablePosition() const { std::vector<position_t> reachablePos, v; if(state_ == NORMAL) { int direction = (isBlack()) ? 1 : -1; // The direction top / bot v = isReachable(direction); reachablePos.insert(reachablePos.end(), v.begin(), v.end()); } else { // We don't care about the direction for( int direction = -1 ; direction < 2 ; direction += 2) { v = isReachable(direction); reachablePos.insert(reachablePos.end(), v.begin(), v.end()); } } return reachablePos; } int DraughtPiece::getValue() const { return (state_ == NORMAL) ? 1 : 2; } Piece* DraughtPiece::Clone() const { return new DraughtPiece(*this); }
#include <iostream> #include <fstream> #include <cstdlib> #include <ctime> #include "board_normal.h" #include "board_torus.h" #include "board_mirror.h" #include "game.h" using namespace hw2; using namespace std; // main declares game object and runs the game int main(int argc, char *argv[]){ game game; game.initializeGame(); game.runGame(); cout << "press enter to leave..." cin.get(); }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <skland/gui/shell-surface.hpp> #include <skland/gui/surface.hpp> #include <skland/gui/toplevel-shell-surface.hpp> #include <skland/gui/popup-shell-surface.hpp> #include "internal/display-registry.hpp" namespace skland { Surface *ShellSurface::Create(AbstractEventHandler *event_handler, const Margin &margin) { Surface *surface = new Surface(event_handler, margin); surface->role_.shell_surface = new ShellSurface(surface); return surface; } ShellSurface *ShellSurface::Get(const Surface *surface) { if (nullptr == surface->parent_) return surface->role_.shell_surface; return nullptr; } ShellSurface::ShellSurface(Surface *surface) : surface_(surface), parent_(nullptr) { DBG_ASSERT(surface_); role_.placeholder = nullptr; xdg_surface_.Setup(Display::Registry().xdg_shell(), surface_->wl_surface_); PushShellSurface(); } ShellSurface::~ShellSurface() { RemoveShellSurface(); if (nullptr == parent_) delete role_.toplevel_shell_surface; else delete role_.popup_shell_surface_; xdg_surface_.Destroy(); DBG_ASSERT(surface_->role_.shell_surface == this); surface_->role_.shell_surface = nullptr; } void ShellSurface::ResizeWindow(int width, int height) const { xdg_surface_.SetWindowGeometry(surface()->margin().l, surface()->margin().t, width, height); } void ShellSurface::PushShellSurface() { DBG_ASSERT(nullptr == surface_->parent_); DBG_ASSERT(nullptr == surface_->up_); DBG_ASSERT(nullptr == surface_->down_); DBG_ASSERT(Surface::kShellSurfaceCount >= 0); if (Surface::kTop) { Surface::kTop->up_ = surface_; surface_->down_ = Surface::kTop; Surface::kTop = surface_; } else { DBG_ASSERT(Surface::kShellSurfaceCount == 0); DBG_ASSERT(nullptr == Surface::kBottom); Surface::kBottom = surface_; Surface::kTop = surface_; } Surface::kShellSurfaceCount++; } void ShellSurface::RemoveShellSurface() { DBG_ASSERT(nullptr == surface_->parent_); if (surface_->up_) { surface_->up_->down_ = surface_->down_; } else { DBG_ASSERT(Surface::kTop == surface_); Surface::kTop = surface_->down_; } if (surface_->down_) { surface_->down_->up_ = surface_->up_; } else { DBG_ASSERT(Surface::kBottom == surface_); Surface::kBottom = surface_->up_; } surface_->up_ = nullptr; surface_->down_ = nullptr; Surface::kShellSurfaceCount--; DBG_ASSERT(Surface::kShellSurfaceCount >= 0); } }
#include "Primary.h" #include <wx/filedlg.h> #include <wx/msgdlg.h> #include <wx/listbox.h> #include <wx/clipbrd.h> using namespace sdindex; // Binding buttons to their functionality wxBEGIN_EVENT_TABLE(Primary, wxFrame) EVT_DIRPICKER_CHANGED(1, on_dir_changed) EVT_BUTTON(2, on_load_clicked) EVT_BUTTON(3, on_save_clicked) EVT_BUTTON(4, on_clear_clicked) EVT_TOGGLEBUTTON(5, on_case_clicked) EVT_TOGGLEBUTTON(6, on_ommit_numbers_clicked) EVT_TOGGLEBUTTON(7, on_ommit_special_clicked) EVT_TOGGLEBUTTON(8, on_subdirectories_clicked) EVT_TOGGLEBUTTON(10, on_extensions_clicked) EVT_TEXT_ENTER(12, on_enter_pressed) EVT_BUTTON(13, on_query_clicked) EVT_BUTTON(14, on_copy_clicked) wxEND_EVENT_TABLE() Primary::Primary() : wxFrame(nullptr, 0, "SDIndex", wxDefaultPosition, wxSize(980, 800)) { wxPoint start(15, 15); wxSize buttonsize(85, 30); int xgap = 15; int ygap = 30; wxSize dirSelectorSize(600, ygap); wxFont myf = get_font1(); wxFont cbf = get_font1(); wxFont itf = get_font1(); Bind(wxEVT_SIZE, &Primary::OnSize, this); cbf.SetStrikethrough(true); itf.SetPointSize(12); dirSelect = new wxDirPickerCtrl(this, 1, wxEmptyString, wxDirSelectorPromptStr, start, dirSelectorSize, wxDIRP_DEFAULT_STYLE); dirSelect->GetTextCtrl()->SetEditable(false); loadButton = new wxButton(this, 2, wxString("Load"), wxPoint(dirSelect->GetPosition().x + dirSelect->GetSize().x + xgap, start.y), buttonsize); saveFileButton = new wxButton(this, 3, wxString("Save"), wxPoint(loadButton->GetPosition().x + buttonsize.x + xgap, start.y), buttonsize); clearButton = new wxButton(this, 4, wxString("Clear"), wxPoint(saveFileButton->GetPosition().x + buttonsize.x + xgap, start.y), buttonsize); caseToggleButton = new wxToggleButton(this, 5, wxString("Case"), wxPoint(start.x, dirSelect->GetPosition().y + dirSelect->GetSize().y + ygap), buttonsize); ommitNumbersToggleButton = new wxToggleButton(this, 6, wxString("Numbers"), wxPoint(caseToggleButton->GetPosition().x + caseToggleButton->GetSize().x + xgap, caseToggleButton->GetPosition().y), buttonsize); ommitSymbolsToggleButton = new wxToggleButton(this, 7, wxString("Symbols"), wxPoint(ommitNumbersToggleButton->GetPosition().x + ommitNumbersToggleButton->GetSize().x + xgap, ommitNumbersToggleButton->GetPosition().y), buttonsize); subdirectoriesToggleButton = new wxToggleButton(this, 8, wxString("Subdirs"), wxPoint(ommitSymbolsToggleButton->GetPosition().x + ommitSymbolsToggleButton->GetSize().x + xgap, ommitSymbolsToggleButton->GetPosition().y), buttonsize); extensionsArea = new wxTextCtrl(this, 9, wxEmptyString, wxPoint(subdirectoriesToggleButton->GetPosition().x + subdirectoriesToggleButton->GetSize().x + xgap, subdirectoriesToggleButton->GetPosition().y), wxSize( dirSelectorSize.x - subdirectoriesToggleButton->GetPosition().x - subdirectoriesToggleButton->GetSize().x - xgap, dirSelectorSize.y)); extensionsToggleButton = new wxToggleButton(this, 10, wxString("Include"), wxPoint(wxPoint(loadButton->GetPosition().x, caseToggleButton->GetPosition().y)), wxSize(buttonsize));; instructions_text = new wxStaticText(this, 11, wxString("Select a directory to index"), wxPoint(saveFileButton->GetPosition().x, extensionsToggleButton->GetPosition().y), wxSize(buttonsize.x * 2 + xgap, buttonsize.y + ygap)); caseToggleButton->SetValue(!toLowercase); ommitNumbersToggleButton->SetValue(!ommitNumbers); ommitSymbolsToggleButton->SetValue(!ommitSpecialCharacters); subdirectoriesToggleButton->SetValue(indexSubdirectories); extensionsToggleButton->SetValue(extensionsInclude); queryArea = new wxTextCtrl(this, 12, wxEmptyString, wxPoint(start.x, caseToggleButton->GetPosition().y + caseToggleButton->GetSize().y + ygap), dirSelectorSize, wxTE_PROCESS_ENTER); queryButton = new wxButton(this, 13, wxString("Query"), wxPoint(queryArea->GetPosition().x + queryArea->GetSize().x + xgap, queryArea->GetPosition().y), buttonsize); copyToClipboardButton = new wxButton(this, 14, wxString("Copy"), wxPoint(queryButton->GetPosition().x + queryButton->GetSize().x + xgap, queryArea->GetPosition().y), buttonsize); resultsListArea = new wxListBox(this, 15, wxPoint(start.x, queryArea->GetPosition().y + queryArea->GetSize().y + ygap), wxSize(dirSelectorSize.x, 600)); optionsText = new wxStaticText(this, 16, wxString("Options"), wxPoint(dirSelect->GetPosition().x, dirSelect->GetPosition().y + dirSelect->GetSize().y + 5), wxSize(buttonsize.x, buttonsize.y - 5)); extensionsText = new wxStaticText(this, 17, wxString("Extensions"), wxPoint(extensionsArea->GetPosition().x, dirSelect->GetPosition().y + dirSelect->GetSize().y + 5), wxSize(buttonsize.x, buttonsize.y - 5)); searchText = new wxStaticText(this, 18, wxString("Search"), wxPoint(caseToggleButton->GetPosition().x, caseToggleButton->GetPosition().y + caseToggleButton->GetSize().y + 5), wxSize(buttonsize.x, buttonsize.y - 5)); resultsText = new wxStaticText(this, 19, wxString("Results"), wxPoint(queryArea->GetPosition().x, queryArea->GetPosition().y + queryArea->GetSize().y + 5), wxSize(buttonsize.x, buttonsize.y - 5)); dirSelect->SetFont(myf); loadButton->SetFont(myf); saveFileButton->SetFont(myf); clearButton->SetFont(myf); caseToggleButton->SetFont(myf); ommitNumbersToggleButton->SetFont(myf); ommitSymbolsToggleButton->SetFont(myf); subdirectoriesToggleButton->SetFont(myf); extensionsArea->SetFont(myf); extensionsToggleButton->SetFont(myf); instructions_text->SetFont(itf); queryArea->SetFont(myf); queryButton->SetFont(myf); copyToClipboardButton->SetFont(myf); resultsListArea->SetFont(myf); optionsText->SetFont(myf); extensionsText->SetFont(myf); searchText->SetFont(myf); resultsText->SetFont(myf); dirSelect->SetToolTip("Select a directory to index"); loadButton->SetToolTip("Load a previously saved index file"); saveFileButton->SetToolTip("Save index into a file"); clearButton->SetToolTip("Clears index and all fields"); caseToggleButton->SetToolTip("Choose whether to convert everything to lowercase"); ommitNumbersToggleButton->SetToolTip("Choose whether to ommit indexing numbers"); ommitSymbolsToggleButton->SetToolTip("Choose whether to ommit indexing symbols"); subdirectoriesToggleButton->SetToolTip("Select whether sub directories are indexed"); extensionsArea->SetToolTip("Type the extensions you want seperate with space \".txt .cpp\""); extensionsToggleButton->SetToolTip("Choose whether to include files with set extensions or exclude them"); instructions_text->SetToolTip("Shows whether index has been loaded or not"); queryArea->SetToolTip("Type what you want to search for"); queryButton->SetToolTip("Click to search"); copyToClipboardButton->SetToolTip("Copy a selected result to clipboard"); resultsListArea->SetToolTip("Search results"); if(toLowercase) caseToggleButton->SetFont(cbf); if(ommitNumbers) ommitNumbersToggleButton->SetFont(cbf); if(ommitSpecialCharacters) ommitSymbolsToggleButton->SetFont(cbf); if(!indexSubdirectories) subdirectoriesToggleButton->SetFont(cbf); if(!extensionsInclude)extensionsToggleButton->SetLabel("Exclude"); instructions_text->SetForegroundColour(wxColour(wxT("BLACK"))); } Primary::~Primary() {} wxFont sdindex::Primary::get_font1() { return wxFont(14, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false); } void Primary::on_dir_changed(wxFileDirPickerEvent& evt) { std::string directory; std::vector < std::string > filenames; if(!wxDirExists(dirSelect->GetPath()))return; directory = dirSelect->GetPath().ToStdString(); if(indexing) return; indexing = true; if(directory.empty()) { wxMessageDialog dlg(this, "Please select a directory"); dlg.ShowModal(); evt.Skip(); indexing = false; return; } instructions_text->SetLabel("Indexing..."); instructions_text->SetForegroundColour(wxColor(204, 102, 0)); FileParser::toLowercase = toLowercase; FileParser::ommitNumbers = ommitNumbers; FileParser::ommitSpecialCharacters = ommitSpecialCharacters; FileParser::allowExtensions = extensionsInclude; std::string extString = std::string(extensionsArea->GetLineText(0)); extensions = FileParser::split_string(extString, ' '); if(indexSubdirectories) { hasLoadedIndex = FileParser::index_directory_and_subdirectories(directory, hashtable, extensions); } else { hasLoadedIndex = FileParser::index_directory(directory, hashtable, extensions); } indexing = false; instructions_text->SetLabel("Index Loaded!"); instructions_text->SetForegroundColour(wxColor(0, 153, 0)); evt.Skip(); } void Primary::on_load_clicked(wxCommandEvent& evt) { std::string indexFileName; wxFileDialog openFileDialog(this, _("Load an Index file"), "", "", "*", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if(openFileDialog.ShowModal() == wxID_CANCEL) { evt.Skip(); return; } if(indexing) return; indexing = true; instructions_text->SetLabel("Loading index..."); instructions_text->SetForegroundColour(wxColor(204, 102, 0)); indexFileName = openFileDialog.GetPath().ToStdString(); if(!FileParser::load_index_file(indexFileName, hashtable)) { wxMessageDialog dlg(this, "Could not load file"); dlg.ShowModal(); evt.Skip(); indexing = false; return; } hasLoadedIndex = true; indexing = false; instructions_text->SetLabel("Index Loaded!"); instructions_text->SetForegroundColour(wxColor(0, 51, 0)); evt.Skip(); } void Primary::on_save_clicked(wxCommandEvent& evt) { if(!hasLoadedIndex) { wxMessageDialog dlg(this, "There is no index loaded"); dlg.ShowModal(); evt.Skip(); return; } std::string filename; wxFileDialog saveFileDialog(this, _("Save index file"), "", "", "*", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if(saveFileDialog.ShowModal() == wxID_CANCEL) { evt.Skip(); return; } filename = saveFileDialog.GetPath().ToStdString(); FileParser::write_index_file_to_drive(filename, hashtable); evt.Skip(); } void Primary::on_clear_clicked(wxCommandEvent& evt) { hashtable.clear(); queryArea->Clear(); resultsListArea->Clear(); dirSelect->SetPath(""); extensionsArea->Clear(); hasLoadedIndex = false; instructions_text->SetLabel("Index Cleared"); instructions_text->SetForegroundColour(wxColor(255, 255, 255)); evt.Skip(); } void Primary::on_case_clicked(wxCommandEvent& evt) { wxFont cbf = get_font1(); toLowercase = !toLowercase; if(toLowercase) { cbf.SetStrikethrough(true); } caseToggleButton->SetFont(cbf); evt.Skip(); } void Primary::on_ommit_numbers_clicked(wxCommandEvent& evt) { wxFont cbf = get_font1(); ommitNumbers = !ommitNumbers; if(ommitNumbers) { cbf.SetStrikethrough(true); } ommitNumbersToggleButton->SetFont(cbf); evt.Skip(); } void Primary::on_ommit_special_clicked(wxCommandEvent& evt) { wxFont cbf = get_font1(); ommitSpecialCharacters = !ommitSpecialCharacters; if(ommitSpecialCharacters) { cbf.SetStrikethrough(true); } ommitSymbolsToggleButton->SetFont(cbf); evt.Skip(); } void Primary::on_subdirectories_clicked(wxCommandEvent& evt) { wxFont cbf = get_font1(); indexSubdirectories = !indexSubdirectories; if(!indexSubdirectories) { cbf.SetStrikethrough(true); } subdirectoriesToggleButton->SetFont(cbf); evt.Skip(); } void Primary::on_extensions_clicked(wxCommandEvent& evt) { if(extensionsToggleButton->GetValue()) { extensionsToggleButton->SetLabel("Include"); extensionsInclude = true; } else { extensionsToggleButton->SetLabel("Exclude"); extensionsInclude = false; } evt.Skip(); } void Primary::on_query_clicked(wxCommandEvent& evt) { std::string query; std::vector < wxString > documents; if(!hasLoadedIndex) { wxMessageDialog dlg(this, "There is no index loaded"); dlg.ShowModal(); evt.Skip(); return; } if(!queryArea->IsModified()) { wxMessageDialog dlg(this, "Type something to search for first"); dlg.ShowModal(); evt.Skip(); return; } query = queryArea->GetLineText(0).ToStdString(); queryManager.convertToLowercase = toLowercase; queryManager.ommitNumbers = ommitNumbers; queryManager.ommitSpecialCharacters = ommitSpecialCharacters; std::vector<RankedDocument> rdv = queryManager.query_index(query); resultsListArea->Clear(); for(int i = 0; i < rdv.size(); i++) { wxString entry(std::to_string(i) + ". " + rdv[i].filename); resultsListArea->AppendString(entry); } //evt.Skip(); } void Primary::on_copy_clicked(wxCommandEvent& evt) { bool hasSelection = false; if(resultsListArea->GetCount() == 0) { wxMessageDialog dlg(this, "No selected result to copy"); dlg.ShowModal(); evt.Skip(); return; } if(wxTheClipboard->Open()) { for(unsigned int i = 0; i < resultsListArea->GetCount(); i++) { if(resultsListArea->IsSelected(i)) { wxTheClipboard->SetData( new wxTextDataObject(resultsListArea->GetString(i).AfterFirst(' '))); hasSelection = true; break; } } wxTheClipboard->Close(); } if(!hasSelection) { wxMessageDialog dlg(this, "Select something from the list"); dlg.ShowModal(); } evt.Skip(); } void Primary::on_enter_pressed(wxCommandEvent& evt) { on_query_clicked(evt); } void Primary::OnSize(wxSizeEvent& event) { int xgap = 15; dirSelect->SetSize(wxSize(this->GetSize().x - 345, dirSelect->GetSize().y)); loadButton->SetPosition( wxPoint(dirSelect->GetPosition().x + dirSelect->GetSize().x + xgap, loadButton->GetPosition().y)); saveFileButton->SetPosition( wxPoint(loadButton->GetPosition().x + loadButton->GetSize().x + xgap, saveFileButton->GetPosition().y)); clearButton->SetPosition( wxPoint(saveFileButton->GetPosition().x + saveFileButton->GetSize().x + xgap, clearButton->GetPosition().y)); extensionsArea->SetSize(wxSize(dirSelect->GetSize().x - subdirectoriesToggleButton->GetPosition().x - subdirectoriesToggleButton->GetSize().x, dirSelect->GetSize().y)); extensionsToggleButton->SetPosition(wxPoint(loadButton->GetPosition().x, caseToggleButton->GetPosition().y)); instructions_text->SetPosition(wxPoint(saveFileButton->GetPosition().x, extensionsToggleButton->GetPosition().y)); queryArea->SetSize(wxSize(dirSelect->GetSize())); queryButton->SetPosition( wxPoint(queryArea->GetPosition().x + queryArea->GetSize().x + xgap, queryButton->GetPosition().y)); copyToClipboardButton->SetPosition( wxPoint(queryButton->GetPosition().x + queryButton->GetSize().x + xgap, copyToClipboardButton->GetPosition().y)); resultsListArea->SetSize( wxSize(this->GetSize().x - 45, this->GetSize().y - resultsListArea->GetPosition().y - 55)); // Refreshes the window to remove artifacts from resizing Refresh(); }
/******************************************************************************* * * Workshop 6 example 1 * * 1) Create a function called printDblArray() that prints a given array of doubles * as a row of elements. Use comma (,) as a delimiter. Enclose the output seq in * curly brackets. * * 2) Create a function called calcAvg() that obtains on its input a c-style * array of double, calculates an average of array elements and returns it. * Put the function definition before main(). * ******************************************************************************/ #include <iostream> #include <string> //#include <cassert> // for assert macro using std::cout; void printDblArray(double arr[], ssize_t size) { cout << '{'; bool firstEl = true; for(size_t i = 0; i < size; ++i) { if(!firstEl) // all but the first cout << ", "; else firstEl = false; cout << arr[i]; } cout << '}'; } double calcAvg(double arr[], ssize_t size) { double avg = 0; for(size_t i = 0; i < size; ++i) avg += arr[i]; avg /= size; return avg; } int main() { using std::cout; using std::cin; cout << "Workshop 6 Example 1\n\n"; double e1[5] = {1, 2, 3, 4, 5.1 }; size_t e1Sz = sizeof(e1) / sizeof(e1[0]); double e1Avg = calcAvg(e1, e1Sz); // prints it cout << "Arr1: "; printDblArray(e1, e1Sz); cout << "; its avg = " << e1Avg; cout << "\n"; double e2[5] = {10.1, 2.1e2, 3.3e-1, 40.4}; // different forms of float consts size_t e2Sz = sizeof(e2) / sizeof(e2[0]); double e2Avg = calcAvg(e2, e2Sz); // prints it cout << "Arr2: "; printDblArray(e2, e2Sz); cout << "; its avg = " << e2Avg; // TODO: HW: here we have the same pattern for both arrays. // Refactor the program (create a function if needed) to generalize cases. cout << "\n\n"; return 0; }
#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Utilities/interface/EDPutToken.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectron.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockElementSuperClusterFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockElementSuperCluster.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "RecoParticleFlow/PFProducer/interface/PFEGammaFilters.h" #include "RecoParticleFlow/PFProducer/interface/PFAlgo.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "RecoParticleFlow/PFClusterTools/interface/PFEnergyCalibration.h" #include "RecoParticleFlow/PFClusterTools/interface/PFEnergyCalibrationHF.h" #include "RecoParticleFlow/PFClusterTools/interface/PFSCEnergyCalibration.h" #include "CondFormats/PhysicsToolsObjects/interface/PerformancePayloadFromTFormula.h" #include "CondFormats/DataRecord/interface/PFCalibrationRcd.h" #include "CondFormats/DataRecord/interface/GBRWrapperRcd.h" #include <sstream> #include <string> #include "TFile.h" /**\class PFProducer \brief Producer for particle flow reconstructed particles (PFCandidates) This producer makes use of PFAlgo, the particle flow algorithm. \author Colin Bernet \date July 2006 */ class PFProducer : public edm::stream::EDProducer<> { public: explicit PFProducer(const edm::ParameterSet&); void produce(edm::Event&, const edm::EventSetup&) override; void beginRun(const edm::Run &, const edm::EventSetup &) override; private: const edm::EDPutTokenT<reco::PFCandidateCollection> putToken_; edm::EDGetTokenT<reco::PFBlockCollection> inputTagBlocks_; edm::EDGetTokenT<reco::MuonCollection> inputTagMuons_; edm::EDGetTokenT<reco::VertexCollection> vertices_; edm::EDGetTokenT<reco::GsfElectronCollection> inputTagEgammaElectrons_; std::vector<edm::EDGetTokenT<reco::PFRecHitCollection> > inputTagCleanedHF_; std::string electronOutputCol_; std::string electronExtraOutputCol_; std::string photonExtraOutputCol_; // NEW EGamma Filters edm::EDGetTokenT<edm::ValueMap<reco::GsfElectronRef> >inputTagValueMapGedElectrons_; edm::EDGetTokenT<edm::ValueMap<reco::PhotonRef> > inputTagValueMapGedPhotons_; edm::EDGetTokenT<edm::View<reco::PFCandidate> > inputTagPFEGammaCandidates_; bool use_EGammaFilters_; std::unique_ptr<PFEGammaFilters> pfegamma_ = nullptr; //Use of HO clusters and links in PF Reconstruction bool useHO_; /// verbose ? bool verbose_; // Post muon cleaning ? bool postMuonCleaning_; // what about e/g electrons ? bool useEGammaElectrons_; // Use vertices for Neutral particles ? bool useVerticesForNeutral_; // Take PF cluster calibrations from Global Tag ? bool useCalibrationsFromDB_; std::string calibrationsLabel_; bool postHFCleaning_; // Name of the calibration functions to read from the database // std::vector<std::string> fToRead; /// particle flow algorithm PFAlgo pfAlgo_; }; DEFINE_FWK_MODULE(PFProducer); using namespace std; using namespace edm; PFProducer::PFProducer(const edm::ParameterSet& iConfig) : putToken_{produces<reco::PFCandidateCollection>()} , pfAlgo_(iConfig.getUntrackedParameter<bool>("debug",false)) { //--ab: get calibration factors for HF: auto thepfEnergyCalibrationHF = std::make_shared<PFEnergyCalibrationHF>( iConfig.getParameter<bool>("calibHF_use"), iConfig.getParameter<std::vector<double> >("calibHF_eta_step"), iConfig.getParameter<std::vector<double> >("calibHF_a_EMonly"), iConfig.getParameter<std::vector<double> >("calibHF_b_HADonly"), iConfig.getParameter<std::vector<double> >("calibHF_a_EMHAD"), iConfig.getParameter<std::vector<double> >("calibHF_b_EMHAD") ); //----------------- inputTagBlocks_ = consumes<reco::PFBlockCollection>(iConfig.getParameter<InputTag>("blocks")); //Post cleaning of the muons inputTagMuons_ = consumes<reco::MuonCollection>(iConfig.getParameter<InputTag>("muons")); postMuonCleaning_ = iConfig.getParameter<bool>("postMuonCleaning"); if( iConfig.existsAs<bool>("useEGammaFilters") ) { use_EGammaFilters_ = iConfig.getParameter<bool>("useEGammaFilters"); } else { use_EGammaFilters_ = false; } useEGammaElectrons_ = iConfig.getParameter<bool>("useEGammaElectrons"); if( useEGammaElectrons_) { inputTagEgammaElectrons_ = consumes<reco::GsfElectronCollection>(iConfig.getParameter<edm::InputTag>("egammaElectrons")); } electronOutputCol_ = iConfig.getParameter<std::string>("pf_electron_output_col"); std::vector<double> calibPFSCEle_Fbrem_barrel; std::vector<double> calibPFSCEle_Fbrem_endcap; std::vector<double> calibPFSCEle_barrel; std::vector<double> calibPFSCEle_endcap; calibPFSCEle_Fbrem_barrel = iConfig.getParameter<std::vector<double> >("calibPFSCEle_Fbrem_barrel"); calibPFSCEle_Fbrem_endcap = iConfig.getParameter<std::vector<double> >("calibPFSCEle_Fbrem_endcap"); calibPFSCEle_barrel = iConfig.getParameter<std::vector<double> >("calibPFSCEle_barrel"); calibPFSCEle_endcap = iConfig.getParameter<std::vector<double> >("calibPFSCEle_endcap"); std::shared_ptr<PFSCEnergyCalibration> thePFSCEnergyCalibration ( new PFSCEnergyCalibration(calibPFSCEle_Fbrem_barrel,calibPFSCEle_Fbrem_endcap, calibPFSCEle_barrel,calibPFSCEle_endcap )); // register products produces<reco::PFCandidateCollection>("CleanedHF"); produces<reco::PFCandidateCollection>("CleanedCosmicsMuons"); produces<reco::PFCandidateCollection>("CleanedTrackerAndGlobalMuons"); produces<reco::PFCandidateCollection>("CleanedFakeMuons"); produces<reco::PFCandidateCollection>("CleanedPunchThroughMuons"); produces<reco::PFCandidateCollection>("CleanedPunchThroughNeutralHadrons"); produces<reco::PFCandidateCollection>("AddedMuonsAndHadrons"); double nSigmaECAL = iConfig.getParameter<double>("pf_nsigma_ECAL"); double nSigmaHCAL = iConfig.getParameter<double>("pf_nsigma_HCAL"); string mvaWeightFileEleID = iConfig.getParameter<string>("pf_electronID_mvaWeightFile"); string path_mvaWeightFileEleID; //PFPhoton Configuration string path_mvaWeightFileConvID; string mvaWeightFileConvID; string path_mvaWeightFileGCorr; string path_mvaWeightFileLCorr; string path_X0_Map; string path_mvaWeightFileRes; // Reading new EGamma selection cuts bool useProtectionsForJetMET(false); // Reading new EGamma ubiased collections and value maps if(use_EGammaFilters_) { inputTagPFEGammaCandidates_ = consumes<edm::View<reco::PFCandidate> >((iConfig.getParameter<edm::InputTag>("PFEGammaCandidates"))); inputTagValueMapGedElectrons_ = consumes<edm::ValueMap<reco::GsfElectronRef>>(iConfig.getParameter<edm::InputTag>("GedElectronValueMap")); inputTagValueMapGedPhotons_ = consumes<edm::ValueMap<reco::PhotonRef> >(iConfig.getParameter<edm::InputTag>("GedPhotonValueMap")); useProtectionsForJetMET = iConfig.getParameter<bool>("useProtectionsForJetMET"); } //Secondary tracks and displaced vertices parameters bool rejectTracks_Bad = iConfig.getParameter<bool>("rejectTracks_Bad"); bool rejectTracks_Step45 = iConfig.getParameter<bool>("rejectTracks_Step45"); bool usePFNuclearInteractions = iConfig.getParameter<bool>("usePFNuclearInteractions"); bool usePFConversions = iConfig.getParameter<bool>("usePFConversions"); bool usePFDecays = iConfig.getParameter<bool>("usePFDecays"); double dptRel_DispVtx = iConfig.getParameter<double>("dptRel_DispVtx"); edm::ParameterSet iCfgCandConnector = iConfig.getParameter<edm::ParameterSet>("iCfgCandConnector"); // fToRead = iConfig.getUntrackedParameter<vector<string> >("toRead"); useCalibrationsFromDB_ = iConfig.getParameter<bool>("useCalibrationsFromDB"); if (useCalibrationsFromDB_) calibrationsLabel_ = iConfig.getParameter<std::string>("calibrationsLabel"); auto calibration = std::make_shared<PFEnergyCalibration>(); pfAlgo_.setParameters( nSigmaECAL, nSigmaHCAL, calibration, thepfEnergyCalibrationHF); // NEW EGamma Filters pfAlgo_.setEGammaParameters(use_EGammaFilters_, useProtectionsForJetMET); if(use_EGammaFilters_) pfegamma_ = std::make_unique<PFEGammaFilters>(iConfig); //Secondary tracks and displaced vertices parameters pfAlgo_.setDisplacedVerticesParameters(rejectTracks_Bad, rejectTracks_Step45, usePFNuclearInteractions, usePFConversions, usePFDecays, dptRel_DispVtx); if (usePFNuclearInteractions) pfAlgo_.setCandConnectorParameters( iCfgCandConnector ); // Set muon and fake track parameters pfAlgo_.setPFMuonAndFakeParameters(iConfig); pfAlgo_.setBadHcalTrackParams(iConfig); //Post cleaning of the HF postHFCleaning_ = iConfig.getParameter<bool>("postHFCleaning"); double minHFCleaningPt = iConfig.getParameter<double>("minHFCleaningPt"); double minSignificance = iConfig.getParameter<double>("minSignificance"); double maxSignificance = iConfig.getParameter<double>("maxSignificance"); double minSignificanceReduction = iConfig.getParameter<double>("minSignificanceReduction"); double maxDeltaPhiPt = iConfig.getParameter<double>("maxDeltaPhiPt"); double minDeltaMet = iConfig.getParameter<double>("minDeltaMet"); // Set post HF cleaning muon parameters pfAlgo_.setPostHFCleaningParameters(postHFCleaning_, minHFCleaningPt, minSignificance, maxSignificance, minSignificanceReduction, maxDeltaPhiPt, minDeltaMet); // Input tags for HF cleaned rechits std::vector<edm::InputTag> tags =iConfig.getParameter< std::vector<edm::InputTag> >("cleanedHF"); for (unsigned int i=0;i<tags.size();++i) inputTagCleanedHF_.push_back(consumes<reco::PFRecHitCollection>(tags[i])); //MIKE: Vertex Parameters vertices_ = consumes<reco::VertexCollection>(iConfig.getParameter<edm::InputTag>("vertexCollection")); useVerticesForNeutral_ = iConfig.getParameter<bool>("useVerticesForNeutral"); // Use HO clusters and links in the PF reconstruction useHO_= iConfig.getParameter<bool>("useHO"); pfAlgo_.setHOTag(useHO_); verbose_ = iConfig.getUntrackedParameter<bool>("verbose",false); } void PFProducer::beginRun(const edm::Run & run, const edm::EventSetup & es) { /* static map<string, PerformanceResult::ResultType> functType; functType["PFfa_BARREL"] = PerformanceResult::PFfa_BARREL; functType["PFfa_ENDCAP"] = PerformanceResult::PFfa_ENDCAP; functType["PFfb_BARREL"] = PerformanceResult::PFfb_BARREL; functType["PFfb_ENDCAP"] = PerformanceResult::PFfb_ENDCAP; functType["PFfc_BARREL"] = PerformanceResult::PFfc_BARREL; functType["PFfc_ENDCAP"] = PerformanceResult::PFfc_ENDCAP; functType["PFfaEta_BARREL"] = PerformanceResult::PFfaEta_BARREL; functType["PFfaEta_ENDCAP"] = PerformanceResult::PFfaEta_ENDCAP; functType["PFfbEta_BARREL"] = PerformanceResult::PFfbEta_BARREL; functType["PFfbEta_ENDCAP"] = PerformanceResult::PFfbEta_ENDCAP; */ if ( useCalibrationsFromDB_ ) { // read the PFCalibration functions from the global tags edm::ESHandle<PerformancePayload> perfH; es.get<PFCalibrationRcd>().get(calibrationsLabel_, perfH); PerformancePayloadFromTFormula const * pfCalibrations = static_cast< const PerformancePayloadFromTFormula *>(perfH.product()); pfAlgo_.thePFEnergyCalibration()->setCalibrationFunctions(pfCalibrations); } } void PFProducer::produce(Event& iEvent, const EventSetup& iSetup) { LogDebug("PFProducer")<<"START event: " <<iEvent.id().event() <<" in run "<<iEvent.id().run()<<endl; //Assign the PFAlgo Parameters pfAlgo_.setPFVertexParameters(useVerticesForNeutral_, iEvent.get(vertices_)); // get the collection of blocks auto blocks = iEvent.getHandle( inputTagBlocks_); assert( blocks.isValid() ); // get the collection of muons if ( postMuonCleaning_ ) pfAlgo_.setMuonHandle( iEvent.getHandle(inputTagMuons_) ); if(use_EGammaFilters_) pfAlgo_.setEGammaCollections( iEvent.get(inputTagPFEGammaCandidates_), iEvent.get(inputTagValueMapGedElectrons_), iEvent.get(inputTagValueMapGedPhotons_)); LogDebug("PFProducer")<<"particle flow is starting"<<endl; pfAlgo_.reconstructParticles( blocks, pfegamma_.get() ); if(verbose_) { ostringstream str; str<< pfAlgo_ <<endl; // cout << pfAlgo_ << endl; LogInfo("PFProducer") <<str.str()<<endl; } // Save cosmic cleaned muon candidates std::unique_ptr<reco::PFCandidateCollection> pCosmicsMuonCleanedCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferCleanedCosmicCandidates() ); // Save tracker/global cleaned muon candidates std::unique_ptr<reco::PFCandidateCollection> pTrackerAndGlobalCleanedMuonCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferCleanedTrackerAndGlobalCandidates() ); // Save fake cleaned muon candidates std::unique_ptr<reco::PFCandidateCollection> pFakeCleanedMuonCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferCleanedFakeCandidates() ); // Save punch-through cleaned muon candidates std::unique_ptr<reco::PFCandidateCollection> pPunchThroughMuonCleanedCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferPunchThroughCleanedMuonCandidates() ); // Save punch-through cleaned neutral hadron candidates std::unique_ptr<reco::PFCandidateCollection> pPunchThroughHadronCleanedCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferPunchThroughCleanedHadronCandidates() ); // Save added muon candidates std::unique_ptr<reco::PFCandidateCollection> pAddedMuonCandidateCollection( pfAlgo_.getPFMuonAlgo()->transferAddedMuonCandidates() ); // Check HF overcleaning reco::PFRecHitCollection hfCopy; for ( unsigned ihf=0; ihf<inputTagCleanedHF_.size(); ++ihf ) { Handle< reco::PFRecHitCollection > hfCleaned; bool foundHF = iEvent.getByToken( inputTagCleanedHF_[ihf], hfCleaned ); if (!foundHF) continue; for ( unsigned jhf=0; jhf<(*hfCleaned).size(); ++jhf ) { hfCopy.push_back( (*hfCleaned)[jhf] ); } } if (postHFCleaning_) pfAlgo_.checkCleaning( hfCopy ); // Save recovered HF candidates std::unique_ptr<reco::PFCandidateCollection> pCleanedCandidateCollection( pfAlgo_.transferCleanedCandidates() ); // Save the final PFCandidate collection reco::PFCandidateCollection pOutputCandidateCollection = pfAlgo_.transferCandidates(); LogDebug("PFProducer")<<"particle flow: putting products in the event"<<endl; if ( verbose_ ) std::cout <<"particle flow: putting products in the event. Here the full list"<<endl; int nC=0; for(auto const& cand : pOutputCandidateCollection) { nC++; if (verbose_ ) std::cout << nC << ")" << cand.particleId() << std::endl; } // Write in the event iEvent.emplace(putToken_,pOutputCandidateCollection); iEvent.put(std::move(pCleanedCandidateCollection),"CleanedHF"); if ( postMuonCleaning_ ) { iEvent.put(std::move(pCosmicsMuonCleanedCandidateCollection),"CleanedCosmicsMuons"); iEvent.put(std::move(pTrackerAndGlobalCleanedMuonCandidateCollection),"CleanedTrackerAndGlobalMuons"); iEvent.put(std::move(pFakeCleanedMuonCandidateCollection),"CleanedFakeMuons"); iEvent.put(std::move(pPunchThroughMuonCleanedCandidateCollection),"CleanedPunchThroughMuons"); iEvent.put(std::move(pPunchThroughHadronCleanedCandidateCollection),"CleanedPunchThroughNeutralHadrons"); iEvent.put(std::move(pAddedMuonCandidateCollection),"AddedMuonsAndHadrons"); } }
// Approach 1- Concatation: // new = "" // new += string[n-1] // n-- // return new==string // Space - O(n) // Time - O(n^2) , because new is also iterating itself in the loop. // Approach 2- Array/Vector: // new = [] // new.append(string[n-1]) // n-- // string s(new) // return s==string // new.join => converts array into string in python // Space - O(n) // Time - O(n) // Approach 3- Recursion: // return first==last && isPallindrome(mid); // Space will be O(1)?, No that's not the case with recursion,because of call stacks it uses, => 0(n) // It will be O(1), if it's a Tail Recursion(last line of the call), here there is no additional penalty. // Time - O(n) // BEST WAY // Approach 4- Pointers // We can maintain 2 pointers l and r, which points to first and last character of a string initally, then we can compare l & r, if it's equal then increment, // otherwise return false; // Space - O(1) // Time - O(n)
#include "SoundManager.hpp" #include <iostream> SoundManager::SoundManager() { std::map<SoundType, std::string> unloadedSounds; unloadedSounds.emplace(SoundType::BEEP, "assets/beep.ogg"); unloadedSounds.emplace(SoundType::PEEP, "assets/peep.ogg"); unloadedSounds.emplace(SoundType::PLOP, "assets/plop.ogg"); for (const auto& unloadedSound : unloadedSounds) { auto& soundType = std::get<0>(unloadedSound); sounds.emplace(soundType, std::make_pair(sf::Sound(), sf::SoundBuffer())); auto& soundBuffer = std::get<1>(sounds[soundType]); if (!soundBuffer.loadFromFile(unloadedSounds[soundType])) { continue; } auto& sound = std::get<0>(sounds[soundType]); sound.setBuffer(soundBuffer); } } void SoundManager::playSound(SoundType soundType) { auto& sound = std::get<0>(sounds[soundType]); sound.play(); }