blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
d592e22315f98f65f52093a3e5a53f0743e535e5
209790acca0bbcf14609ce6a5d629e2f6008bf8f
/Spring_Training/CCCC-GPLT/STL/F.cpp
07e7628bf4aec8fb49771a415fad2868660ecdf1
[]
no_license
JackieZhai/ICPC_Training
bf598188b7b78d5b529eb40d1e5cfa86c8fb9434
582400e33b68a753f8b4e92f50001141811f2127
refs/heads/master
2021-08-27T16:30:45.183200
2021-08-19T04:27:53
2021-08-19T04:27:53
128,522,278
1
0
null
null
null
null
GB18030
C++
false
false
2,471
cpp
#include <bits/stdc++.h> using namespace std; struct Node{ string fr, lo; int nu; friend bool operator < (const Node &a, const Node &b) { if(a.lo==b.lo) { if(a.fr==b.fr) return a.nu>b.nu; return a.fr>b.fr; } return a.lo>b.lo; } Node(string f, string l, int n):fr(f), lo(l), nu(n){} }; int N, M; int main() { ios::sync_with_stdio(false); cin>>N; while(N--) { cin>>M; priority_queue<Node> que, que2; for(int i=0; i<M; i++) { string buf1, buf2; cin>>buf1>>buf2; int buf; cin>>buf; que.push(Node(buf1, buf2, buf)); } while(que.size()) { Node n=que.top(); que.pop(); if(que.size()) { Node n2=que.top(); while(n2.fr==n.fr && n2.lo==n.lo) { que.pop(); n.nu+=n2.nu; if(que.size()) n2=que.top(); else break; } } que2.push(n); } string nowlo=""; Node n=que2.top(); while(que2.size()) { nowlo=n.lo; cout<<nowlo<<endl; while(nowlo==n.lo) { que2.pop(); cout<<" |----"<<n.fr<<"("<<n.nu<<")"<<endl; if(que2.size()) n=que2.top(); else break; } } if(N) cout<<endl; } return 0; } ///原来map在用iterator遍历的时候也是有字典序的 string s1,s2; int main() { typedef map<string,map<string,int> > mmp; typedef map<string,int> mp; mmp p; int t,n,num,flag = 0; cin>>t; while(t--){ p.clear(); cin>>n; while(n--){ cin>>s2>>s1>>num; p[s1][s2]+=num; } mmp::iterator iter1; mp::iterator iter2; for(iter1 = p.begin(); iter1!= p.end();iter1++){ cout<<iter1->first<<endl; for(iter2 = iter1->second.begin();iter2 != iter1->second.end();iter2++){ cout<<" |----"<<iter2->first<<"("<<iter2->second<<")"<<endl; } } if(t){ cout<<endl; } } return 0; }
[ "jackieturing@gmail.com" ]
jackieturing@gmail.com
f35529117e86fc5d90acb9df3d9b9e3e7f254a01
28e9e5cba227042acc62906d71ab9e4191c7728c
/code_rendu/src/Lab/SwarmBacterium.hpp
dac8388ec3b3a5b76da8ffb32ae1233693227974
[]
no_license
harpine/projetsv2020
8e1c27a84c1dfb4f235d0f2fcf531aea7ecbaca4
3c5c9399a7506cf05a8b7c670bbc4f940508f400
refs/heads/master
2022-09-16T02:11:22.648991
2020-05-24T17:34:34
2020-05-24T17:34:34
246,159,309
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
hpp
#ifndef SWARMBACTERIUM_HPP #define SWARMBACTERIUM_HPP #include "Bacterium.hpp" #include "Swarm.hpp" #include <SFML/Graphics.hpp> #include <Utility/DiffEqSolver.hpp> class SwarmBacterium: public Bacterium, public DiffEqFunction { public: //Constructeur et destructeur: SwarmBacterium(const Vec2d& poscenter, Swarm*& swarm); virtual ~SwarmBacterium() override; //Getters: virtual j::Value& getConfig() const override; //permet d'accéder aux configurations de Swarmbacterium Vec2d getSpeedVector() const; //renvoie la vitesse courante (direction * une valeur) //Autres méthodes: virtual void drawOn(sf::RenderTarget& target) const override; //permet de dessiner une bactérie virtual Bacterium* copie() override; //copie une bactérie virtual void move(sf::Time dt) override; //permet à une bactérie de se déplacer virtual Vec2d f(Vec2d position, Vec2d speed) const override; //modélise la force d'attraction des bactéries private: //Attributs Swarm* swarm_; }; #endif // SWARMBACTERIUM_HPP
[ "helena.binkova.uni@gmail.com" ]
helena.binkova.uni@gmail.com
622411a96228910c05612fb15f47fe6f64a5d6d8
9cc0cdfb379d3da31899e4d9cb260136b55df382
/src/examples/simple_quadratic_cone/simple_quadratic_cone.cpp
6fa50b52c13445596163124392135eb76f75ba3b
[ "BSD-2-Clause" ]
permissive
stringhamc/Optizelle
c066b50a116e55d13a6f9b88a9b25edcf9d8ac21
a826b7c4f6d66c31a01537d8b500ea2c0e9665c5
refs/heads/master
2021-01-18T16:34:26.892861
2015-12-06T15:44:39
2015-12-06T15:44:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,002
cpp
// Optimize a simple problem with an optimal solution of (2.5,2.5) #include <iostream> #include <iomanip> #include "optizelle/optizelle.h" #include "optizelle/vspaces.h" #include "optizelle/json.h" // Squares its input template <typename Real> Real sq(Real x){ return x*x; } // Define a simple objective where // // f(x,y)=(x-3)^2+(y-2)^2 // struct MyObj : public Optizelle::ScalarValuedFunction <double,Optizelle::Rm> { typedef double Real; typedef Optizelle::Rm <Real> X; // Evaluation double eval(const X::Vector& x) const { return sq(x[0]-Real(3.))+sq(x[1]-Real(2.)); } // Gradient void grad( const X::Vector& x, X::Vector& g ) const { g[0]=2*x[0]-6; g[1]=2*x[1]-4; } // Hessian-vector product void hessvec( const X::Vector& x, const X::Vector& dx, X::Vector& H_dx ) const { H_dx[0]= Real(2.)*dx[0]; H_dx[1]= Real(2.)*dx[1]; } }; // Define a simple SOCP inequality // // h(x,y) = [ y >= |x| ] // h(x,y) = (y,x) >=_Q 0 // struct MyIneq : public Optizelle::VectorValuedFunction <double,Optizelle::Rm,Optizelle::SQL> { typedef Optizelle::Rm <double> X; typedef Optizelle::SQL <double> Y; typedef double Real; // y=h(x) void eval( const X::Vector& x, Y::Vector& y ) const { y(1,1)=x[1]; y(1,2)=x[0]; } // y=h'(x)dx void p( const X::Vector& x, const X::Vector& dx, Y::Vector& y ) const { y(1,1)= dx[1]; y(1,2)= dx[0]; } // z=h'(x)*dy void ps( const X::Vector& x, const Y::Vector& dy, X::Vector& z ) const { z[0]= dy(1,2); z[1]= dy(1,1); } // z=(h''(x)dx)*dy void pps( const X::Vector& x, const X::Vector& dx, const Y::Vector& dy, X::Vector& z ) const { X::zero(z); } }; int main(int argc,char* argv[]){ // Create some type shortcuts typedef Optizelle::Rm <double> X; typedef Optizelle::SQL <double> Z; typedef X::Vector X_Vector; typedef Z::Vector Z_Vector; // Read in the name for the input file if(argc!=2) { std::cerr << "simple_quadratic_cone <parameters>" << std::endl; exit(EXIT_FAILURE); } std::string fname(argv[1]); // Generate an initial guess for the primal X_Vector x(2); x[0]=1.2; x[1]=3.1; // Generate an initial guess for the dual std::vector <Optizelle::Natural> sizes(1); sizes[0]=2; std::vector <Optizelle::Cone::t> types(1); types[0]=Optizelle::Cone::Quadratic; Z_Vector z(types,sizes); // Create an optimization state Optizelle::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL> ::State::t state(x,z); // Read the parameters from file Optizelle::json::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL> ::read(Optizelle::Messaging(),fname,state); // Create a bundle of functions Optizelle::InequalityConstrained<double,Optizelle::Rm,Optizelle::SQL> ::Functions::t fns; fns.f.reset(new MyObj); fns.h.reset(new MyIneq); // Solve the optimization problem Optizelle::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL> ::Algorithms::getMin(Optizelle::Messaging(),fns,state); // Print out the reason for convergence std::cout << "The algorithm converged due to: " << Optizelle::StoppingCondition::to_string(state.opt_stop) << std::endl; // Print out the final answer std::cout << std::setprecision(16) << std::scientific << "The optimal point is: (" << state.x[0] << ',' << state.x[1] << ')' << std::endl; // Write out the final answer to file Optizelle::json::InequalityConstrained <double,Optizelle::Rm,Optizelle::SQL> ::write_restart(Optizelle::Messaging(),"solution.json",state); // Successful termination return EXIT_SUCCESS; }
[ "joe@optimojoe.com" ]
joe@optimojoe.com
24fd8e7d84d625bc0a7c5142c200c4b7c270c280
33b2d2d14b34b03658f7954d136ec3dea68b86e0
/src/qt/qrcodedialog.cpp
6fb2221d957e5ce580cdd6dc9fdc8990e159828d
[ "MIT" ]
permissive
Jahare/Electric
3b33aa1747a6099cb8f5069d36664a1d59bc1e0c
cc67c12b78b7693a7150ef7fd12369038451cece
refs/heads/master
2021-08-23T17:51:05.378142
2014-03-04T22:35:13
2014-03-04T22:35:13
113,246,593
0
0
null
2017-12-06T00:00:36
2017-12-06T00:00:36
null
UTF-8
C++
false
false
4,311
cpp
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("mooncoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
[ "root@WebServer.HackShard.Com" ]
root@WebServer.HackShard.Com
d801bb7b4935f11ab424b1e032bb16cf0b1fa993
e2999855739caf786601dd9d49183cfd035dfb60
/examples/hamilton/ej2.cpp
bbd0c19141c91dffe2053aad4a2498a19c31926a
[ "Apache-2.0" ]
permissive
tec-csf/tc2017-t3-primavera-2020-GerAng1
88454686fa01e31aec05a858524065fa74866fae
49e70c48800062a8e7f1183a2db9233737bd1e35
refs/heads/master
2021-05-25T19:11:55.150847
2020-04-14T13:39:10
2020-04-14T13:39:10
253,885,783
0
0
null
null
null
null
UTF-8
C++
false
false
3,205
cpp
#include <algorithm> // std::find #include <iostream> // cin y cout #include <vector> #include "../../sources/Graph.hpp" /* Itera para regresar un apuntador al Vertex con menor coste. * Toma como criterios que el Vertex no esté en vector yaesta; * y que camino tiene el valor más bajo.*/ template <class V, class E> Vertex<V, E> * busca(const int &num_nodes, Vertex<V, E> * &v_curso, std::vector< Vertex<V, E> * >& yaesta, std::vector<int>& costos, int j) { if (j < num_nodes) { auto mejor_edge = v_curso->minEdge(yaesta, num_nodes); costos.push_back(mejor_edge->getInfo()); auto mejor_vertice = mejor_edge->getTarget(); yaesta.push_back(mejor_vertice); return mejor_vertice; } } int main(int argc, char const *argv[]) { std::cout << "\n\n\t\t-----INICIO PROGRAMA CICLO HAMILTONIANO-----\n\n" << std::endl; Graph<std::string, int> mapa("Ejemplo 2"); /* Crear vértices */ Vertex<std::string, int> * V0 = new Vertex<std::string, int>("V0"); Vertex<std::string, int> * V1 = new Vertex<std::string, int>("V1"); Vertex<std::string, int> * V2 = new Vertex<std::string, int>("V2"); Vertex<std::string, int> * V3 = new Vertex<std::string, int>("V3"); Vertex<std::string, int> * V4 = new Vertex<std::string, int>("V4"); Vertex<std::string, int> * V5 = new Vertex<std::string, int>("V5"); /* Adicionar vértices al grafo */ mapa.addVertex(V0); mapa.addVertex(V1); mapa.addVertex(V2); mapa.addVertex(V3); mapa.addVertex(V4); mapa.addVertex(V5); /* Adicionar aristas */ mapa.addEdge(V0, V1, 20); mapa.addEdge(V0, V2, 10); mapa.addEdge(V0, V5, 40); mapa.addEdge(V1, V3, 40); mapa.addEdge(V1, V5, 30); mapa.addEdge(V2, V4, 30); mapa.addEdge(V3, V4, 20); mapa.addEdge(V3, V5, 50); std::vector< Vertex<std::string, int> * > nodes = mapa.getNodes(); int num_nodes = nodes.size(); std::cout << "Nodos en grafo: " << num_nodes << std::endl; std::vector< Vertex<std::string, int> * > yaesta; std::vector<int> costos; Vertex<std::string, int> * v_curso = nodes[0]; yaesta.push_back(v_curso); std::cout << "Camino a tomar: " << std::endl; for (int j = 0; j <= nodes.size(); ++j) { std::cout << v_curso->getInfo() << std::endl; v_curso = busca(num_nodes, v_curso, yaesta, costos, j); if(v_curso == nodes[0] && yaesta.size() != num_nodes + 1) { std::cout << v_curso->getInfo() << std::endl; std::cout << "No se cumplió un circuito Hamiltoniano." << std::endl; break; } } std::cout << "Coste total: "; int total = 0; for (int i = 0; i < costos.size(); ++i) { if (i == 0) { std::cout << costos[i]; } else { std::cout << " + " << costos[i]; } total += costos[i]; } std::cout << " = " << total << '\n' << std::endl; char ans; std::cout << "¿Ver grafo? [Y/N]: "; std::cin >> ans; if (ans == 'Y' || ans == 'y') { std::cout << mapa << std::endl; } std::cout << "\n\n\t\t----PROGRAMA CICLO HAMILTONIANO FINALIZADO----\n" << std::endl; return 0; }
[ "ganglada.dlanda@outlook.com" ]
ganglada.dlanda@outlook.com
0a7f353369b13638c83f3275f26bbc55362751af
20a06d71f4308446ecf0d7d2a3ef1879279ba2c1
/src/qt/transactionview.h
30b0b48b23546987ea76ebd5e672a37d18472097
[ "MIT" ]
permissive
BTCGreen/BTC-Green---Cumulative-Update-01
3ee84ed15fe644cb2faa49de3c34bfbc15b6a8e9
39c783fad9b3e697970825ef28233d32e0b75cf0
refs/heads/main
2023-03-29T10:22:04.352030
2021-04-01T23:48:50
2021-04-01T23:48:50
353,640,271
0
0
null
null
null
null
UTF-8
C++
false
false
3,123
h
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2017-2019 The bitcoingreen developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_TRANSACTIONVIEW_H #define BITCOIN_QT_TRANSACTIONVIEW_H #include "guiutil.h" #include <QKeyEvent> #include <QWidget> #include <QAction> class TransactionFilterProxy; class WalletModel; QT_BEGIN_NAMESPACE class QComboBox; class QDateTimeEdit; class QFrame; class QItemSelectionModel; class QLineEdit; class QMenu; class QModelIndex; class QSignalMapper; class QTableView; QT_END_NAMESPACE /** Widget showing the transaction list for a wallet, including a filter row. Using the filter row, the user can view or export a subset of the transactions. */ class TransactionView : public QWidget { Q_OBJECT public: explicit TransactionView(QWidget* parent = 0); void setModel(WalletModel* model); // Date ranges for filter enum DateEnum { All, Today, ThisWeek, ThisMonth, LastMonth, ThisYear, Range }; enum ColumnWidths { STATUS_COLUMN_WIDTH = 23, WATCHONLY_COLUMN_WIDTH = 23, DATE_COLUMN_WIDTH = 120, TYPE_COLUMN_WIDTH = 240, AMOUNT_MINIMUM_COLUMN_WIDTH = 120, MINIMUM_COLUMN_WIDTH = 23 }; private: WalletModel* model; TransactionFilterProxy* transactionProxyModel; QTableView* transactionView; QComboBox* dateWidget; QComboBox* typeWidget; QComboBox* watchOnlyWidget; QLineEdit* addressWidget; QLineEdit* amountWidget; QAction* hideOrphansAction; QMenu* contextMenu; QSignalMapper* mapperThirdPartyTxUrls; QFrame* dateRangeWidget; QDateTimeEdit* dateFrom; QDateTimeEdit* dateTo; QWidget* createDateRangeWidget(); GUIUtil::TableViewLastColumnResizingFixer* columnResizingFixer; virtual void resizeEvent(QResizeEvent* event); bool eventFilter(QObject* obj, QEvent* event); private slots: void contextualMenu(const QPoint&); void dateRangeChanged(); void showDetails(); void copyAddress(); void editLabel(); void copyLabel(); void copyAmount(); void copyTxID(); void openThirdPartyTxUrl(QString url); void updateWatchOnlyColumn(bool fHaveWatchOnly); signals: void doubleClicked(const QModelIndex&); /** Fired when a message should be reported to the user */ void message(const QString& title, const QString& message, unsigned int style); /** Send computed sum back to wallet-view */ void trxAmount(QString amount); public slots: void chooseDate(int idx); void chooseType(int idx); void hideOrphans(bool fHide); void updateHideOrphans(bool fHide); void chooseWatchonly(int idx); void changedPrefix(const QString& prefix); void changedAmount(const QString& amount); void exportClicked(); void focusTransaction(const QModelIndex&); void computeSum(); }; #endif // BITCOIN_QT_TRANSACTIONVIEW_H
[ "81521327+BTCGreen@users.noreply.github.com" ]
81521327+BTCGreen@users.noreply.github.com
63f7de90de162415bb250e876f3e93fc50d5b303
51c035f61d4412c90fc44a0fb5b43cbd0f17761f
/Socket.cpp
b4a6d8ec774c5b57f0b21cb968c6125c4faf89b5
[]
no_license
OldSchoolTeam/GalconGameServer
a62b85d6493d25f34ba90906232cabbc218f27d7
78413dcd04fc3f2fe563f31a88414a4069f87484
refs/heads/master
2021-01-23T02:58:51.938016
2011-06-15T11:22:23
2011-06-15T11:22:23
1,832,012
4
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
#include "Socket.h" CSocket::CSocket(int i_id, QObject *parent) : QTcpSocket(parent) { m_id = i_id; } int CSocket::GetId() { return m_id; } void CSocket::SendMsg(QString i_msg) { QByteArray msg; QDataStream out(&msg, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); out << quint16(0) << i_msg.toUtf8(); out.device()->seek(0); out << quint16(msg.size()-sizeof(quint16)); write(msg); }
[ "ya.sashok@gmail.com" ]
ya.sashok@gmail.com
e508626a48c66b530c278f728d37388c7d481f37
2232c179ab4aafbac2e53475447a5494b26aa3fb
/src/solver/rdm/bc/WeakBC.hpp
4579c50c18e0cd9845b269faf2d348fe55651292
[]
no_license
martinv/pdekit
689986d252d13fb3ed0aa52a0f8f6edd8eef943c
37e127c81702f62f744c11cc2483869d8079f43e
refs/heads/master
2020-03-31T09:24:32.541648
2018-10-08T15:23:43
2018-10-08T15:23:43
152,095,058
1
0
null
null
null
null
UTF-8
C++
false
false
35,188
hpp
#ifndef RDM_Weak_Boundary_Condition_hpp #define RDM_Weak_Boundary_Condition_hpp #include "solver/rdm/bc/RDMBCBase.hpp" #include "solver/rdm/bc/RDMBCMetricData.hpp" namespace pdekit { namespace solver { namespace rdm { // Base class to implement boundary conditions // Physics ... physical model of given boundary condition // DIM ... space dimension of entity to which the boundary condition is // applied // Example: BoundaryCondition<Dim::_3D,Dim::_2D> would be a boundary condition // applied to a surface (2D entity) of a 3D mesh template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> class WeakBC : public RDMBCBase<MeshConfig, Physics, BcDim> { public: using rdm_bc_base = RDMBCBase<MeshConfig, Physics, BcDim>; using mesh_config = typename rdm_bc_base::mesh_config; using physics_type = typename rdm_bc_base::physics_type; using mesh_type = typename rdm_bc_base::mesh_type; using mesh_boundary = typename rdm_bc_base::mesh_boundary; using cell_dofs = typename rdm_bc_base::cell_dofs; using f_space = typename rdm_bc_base::f_space; protected: /// TYPEDEFS using geo_cell_metric_type = typename rdm_bc_base::geo_cell_metric_type; using sol_cell_metric_type = typename rdm_bc_base::sol_cell_metric_type; using flux_cell_metric_type = typename rdm_bc_base::flux_cell_metric_type; public: /// Default constructor WeakBC(); /// Constructor WeakBC(const std::string &name); /// Destructor ~WeakBC() override; /// Return the type of the boundary condition RDMBCType bc_type() const override; /// Set the function space (reference elements) void configure_mesh_data(const std::shared_ptr<const mesh_type> &mesh, const common::PtrHandle<const cell_dofs> geo_dofs, const common::PtrHandle<const cell_dofs> sol_dofs, const std::string &domain_name) override; /// Configure the solution function void configure_spaces(const SFunc sf_type, const PointSetID quad_type, const Uint quadrature_order) override; /// Apply the boundary condition void apply(RDTimeUpdate &time_update) override; /// Compute entries for global Jacobian (in implicit methods) using finite /// differencing void global_lsys_fin_diff_jacobian_entries( RDTimeUpdate &time_update, interpolation::SolutionCache &res_cache, interpolation::SolutionCache &res_cache_perturbed, std::vector<std::tuple<Uint, Uint, Real>> &mat_buffer, std::vector<std::tuple<Uint, Real>> &rhs_buffer) override; void global_lsys_rhs_entries(RDTimeUpdate &time_update, interpolation::SolutionCache &res_cache, std::vector<std::tuple<Uint, Real>> &rhs_buffer) override; protected: /// TYPES AND TYPEDEFS using const_dof_iterator = typename mesh::BoundaryFacets<MeshConfig, BcDim>::const_dof_iterator; using const_dof_iterator_typed = typename mesh::BoundaryFacets<MeshConfig, BcDim>::const_dof_iterator_typed; using sol_elem_range_typed = common::IteratorRange<const_dof_iterator_typed>; const std::vector<sol_elem_range_typed> &sol_ranges() const; using bc_metric_data_t = RDMBCMetricData<MeshConfig, Physics, BcDim>; /// METHODS bc_metric_data_t const &metric_data() const; /// Compute the nodal residuals on one cell void compute_on_element_weak(const Uint idx_in_metric, geo_cell_metric_type const &cell_geo_metric, sol_cell_metric_type const &cell_sol_metric, flux_cell_metric_type const &cell_flux_metric); /// DATA /// Corrective residual for each node /// Dimensions: [NEQ x nb_nodes] common::DataMap<mesh::PointSetTagExt, math::DenseDVec<Real>> m_bface_residual; /// Update coefficient for each node in boundary element common::DataMap<mesh::PointSetTagExt, math::DenseDVec<Real>> m_bface_elem_update_coeff; /// The weak correction ('residual') integrated over one facet typename Physics::Properties::FluxV m_total_facet_residual; /// Sum of partial ('nodal', dof-related) residuals. This /// should be equal to m_total_facet_residual. If not, /// we need to scale the nodal residuals to satisfy this condition /// Otherwise the BC would not be conservative typename Physics::Properties::FluxV m_sum_dof_residuals; private: /// Apply the boundary condition given cached data and metric /// This supposes that the the geometry/solution cache and metric in the /// data have been processed a-priori! void compute_residuals(RDMBCMetricData<MeshConfig, Physics, BcDim> const &data, const_dof_iterator_typed const &sol_iter_begin, const_dof_iterator_typed const &sol_iter_end, RDTimeUpdate &time_update, interpolation::SolutionCache &res_cache); /// Ranges of elements (for each element type separately) /// in the solution dof container std::vector<sol_elem_range_typed> m_sol_ranges; std::unique_ptr<bc_metric_data_t> m_metric_data; }; // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::WeakBC() : RDMBCBase<MeshConfig, Physics, BcDim>(), m_metric_data(nullptr) { } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::WeakBC(const std::string &name) : RDMBCBase<MeshConfig, Physics, BcDim>(name), m_metric_data(nullptr) { } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::~WeakBC() { } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> RDMBCType WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::bc_type() const { return BC_TYPE_WEAK; } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::configure_mesh_data( const std::shared_ptr<const mesh_type> &mesh, const common::PtrHandle<const cell_dofs> geo_dofs, const common::PtrHandle<const cell_dofs> sol_dofs, const std::string &domain_name) { // First call the method of the parent rdm_bc_base::configure_mesh_data(mesh, geo_dofs, sol_dofs, domain_name); mesh::BoundaryFacets<MeshConfig, BcDim> const &boundary = *(this->mesh()->all_boundaries().domain(this->domain_name())); using cell_dofs_type = typename result_of::dof_map_t<MeshConfig>; cell_dofs_type const &sol_cell_dofs = *this->sol_dofs(); boundary.all_bdry_dof_ranges(sol_cell_dofs, m_sol_ranges); for (const sol_elem_range_typed &sol_elem_range : m_sol_ranges) { const mesh::MeshEntity sol_cell = (*sol_elem_range.begin()).mesh_entity(); common::PtrHandle<math::DenseDVec<Real>> residual_vec = m_bface_residual.create( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); (*residual_vec).resize(sol_cell.nb_vert() * Physics::NEQ); common::PtrHandle<math::DenseDVec<Real>> elem_update_coeff = m_bface_elem_update_coeff.create( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); (*elem_update_coeff).resize(sol_cell.nb_vert()); (*elem_update_coeff).fill(0.0); } return; } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::configure_spaces(const SFunc sf_type, const PointSetID quad_type, const Uint quadrature_order) { // First call the method of the parent rdm_bc_base::configure_spaces(sf_type, quad_type, quadrature_order); const mesh::MeshBoundarySet<MeshConfig> &mesh_boundaries = this->mesh()->all_boundaries(); const mesh::BoundaryFacets<MeshConfig, BcDim> &boundary = *(mesh_boundaries.domain(this->domain_name())); if (!m_metric_data) { const mesh::CellTopologyView<MeshConfig> first_cell_geo_cell = *(*this->mesh()).cbegin_cells(); const Uint geo_cell_order = first_cell_geo_cell.pt_set_id().poly_order(); m_metric_data = std::unique_ptr<bc_metric_data_t>(new bc_metric_data_t()); m_metric_data->allocate_cache(geo_cell_order, *rdm_bc_base::geo_space(), *rdm_bc_base::sol_space(), boundary.nb_active_cells()); } } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::apply(RDTimeUpdate &time_update) { interpolation::VectorMeshFunction<Real> &solution = *(this->solution()); interpolation::VectorMeshFunction<Real> &residuals = *(this->residuals()); m_metric_data->m_geo_cache.flush(); m_metric_data->m_geo_metric.empty_buffer(); m_metric_data->fill_geo_cache((*this->mesh()), m_sol_ranges, (*rdm_bc_base::geo_space())); m_metric_data->m_geo_metric.evaluate(m_metric_data->m_geo_cache, interpolation::RebuildMetricIndex{true}); // typedef typename result_of::dof_map_t<MeshConfig> cell_dofs_type; using node_value_type = typename interpolation::VectorMeshFunction<Real>::entry_type; // typedef typename // interpolation::VectorMeshFunction<Real>::const_entry_type // const_node_value_type; m_metric_data->m_sol_metric.empty_buffer(); m_metric_data->m_sol_cache.flush(); m_metric_data->m_flux_metric.empty_buffer(); const_dof_iterator_typed sol_elem_it; // Fill solution cache for (sol_elem_range_typed const &sol_elem_range : m_sol_ranges) { for (sol_elem_it = sol_elem_range.begin(); sol_elem_it != sol_elem_range.end(); ++sol_elem_it) { const mesh::MeshEntity sol_cell = sol_elem_it->mesh_entity(); m_metric_data->m_sol_cache.push_back_to_buffer( sol_cell, solution, mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); } } // Evaluate solution metric m_metric_data->m_sol_metric.evaluate(m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, interpolation::ComputeMetricDerivs{true}, interpolation::RebuildMetricIndex{true}); m_metric_data->m_flux_metric.evaluate(m_metric_data->m_geo_cache, m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, m_metric_data->m_sol_metric, interpolation::RebuildMetricIndex{true}); // Loop over the computed metric data and evaluate boundary residuals Uint idx_in_metric = 0; const interpolation::ScalarMeshFunction<Real> &dual_nodal_volume = time_update.nodal_dual_volume(); // Fill solution cache for (sol_elem_range_typed const &sol_elem_range : m_sol_ranges) { // Don't use a reference here. The following does compile but segfaults // with clang: const mesh::MeshEntity &sol_cell = // *(sol_elem_range.begin()); Use this instead: const mesh::MeshEntity sol_cell = (*sol_elem_range.begin()).mesh_entity(); math::DenseDVec<Real> &bface_res = *(m_bface_residual.std_region_data( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u))); math::DenseDVec<Real> &bface_update_coeff_vector = *(m_bface_elem_update_coeff.std_region_data( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u))); for (sol_elem_it = sol_elem_range.begin(); sol_elem_it != sol_elem_range.end(); ++sol_elem_it) { const mesh::MeshEntity sol_cell = sol_elem_it->mesh_entity(); bface_res.fill(0.0); bface_update_coeff_vector.fill(0.0); geo_cell_metric_type const cell_geo_metric = m_metric_data->m_geo_metric.cellwise_values(idx_in_metric); sol_cell_metric_type const cell_sol_metric = m_metric_data->m_sol_metric.cellwise_values(idx_in_metric); flux_cell_metric_type const cell_flux_metric = m_metric_data->m_flux_metric.cellwise_values(idx_in_metric); // Compute corrective residual on one boundary element compute_on_element_weak(idx_in_metric, cell_geo_metric, cell_sol_metric, cell_flux_metric); /* const mesh::IncidencePair idx_in_parent = sol_elem_it.idx_in_parent(); const Real parent_cell_volume = time_update.cell_volume(idx_in_parent.cell_idx); for (Uint n = 0; n < bface_update_coeff_vector.size(); ++n) { bface_update_coeff_vector[n] *= parent_cell_volume; } */ for (Uint n = 0; n < sol_cell.nb_vert(); ++n) { node_value_type node_residual = residuals.value(sol_cell.vertex(n)); // (*rdm_bc_base::m_rd_time_update)[sol_cell.vertex(n)] += // bface_update_coeff_vector[n]; // time_update.accumulate_nodal_wave_speed(sol_cell.vertex(n), // bface_update_coeff_vector[n]); const Real nodal_volume = dual_nodal_volume[sol_cell.vertex(n)]; // IMPORTANT: THE DIMENSION OF UPDATE COEFFICIENT IS k+ = |S| * // lambda, WHERE lambda IS THE MAXIMUM EIGENVALUE // bface_update_coeff_vector[n] ONLY CONTAINS THE VALUES OF // lambda, HENCE THE WAVE SPEED, WHICH SHOULD HOLD [(k+)*|S|] // MUST BE COMPUTED AS (k+) * |S|^2 time_update.accumulate_nodal_wave_speed(sol_cell.vertex(n), nodal_volume * bface_update_coeff_vector[n]); // ON THE OTHER HAND, IN THE MAIN SOLVER, THE GOVERNING EQUATION // ISGIVEN BY du/dt = 1./|S| * RDM_res, WITH RDM_res BEING THE // RDS ACCUMULATED RESIDUALS. HENCE THE BOUNDARY FACE RESIDUALS // (bface_res[n,eq] MUST BE DIVIDED BY NODAL VOLUME const Real inv_nodal_volume = 1. / nodal_volume; for (Uint eq = 0; eq < Physics::NEQ; ++eq) { node_residual[eq] += inv_nodal_volume * bface_res[n * Physics::NEQ + eq]; } } idx_in_metric++; } // Loop over one type of boundary elements (solution space) } // Loop over boundary element ranges } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::compute_residuals( RDMBCMetricData<MeshConfig, Physics, BcDim> const &data, typename mesh::BoundaryFacets<MeshConfig, BcDim>::const_dof_iterator_typed const &sol_iter_begin, typename mesh::BoundaryFacets<MeshConfig, BcDim>::const_dof_iterator_typed const &sol_iter_end, RDTimeUpdate &time_update, interpolation::SolutionCache &res_cache) { // const_dof_iterator bcell_geo_iter = const_dof_iterator_typed bcell_sol_iter = sol_iter_begin; // Since we are iterating over boundary cells of the same type, the // 'bface_res' data will always be the same (resized to the same number of // local cell nodes) const mesh::MeshEntity sol_cell = bcell_sol_iter->mesh_entity(); math::DenseDVec<Real> &bface_res = *(m_bface_residual.std_region_data( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u))); // Since we are iterating over boundary cells of the same type, the // 'bface_update_coeff_vector' will always be the same (resized to the same // number of local cell nodes) math::DenseDVec<Real> &bface_update_coeff_vector = *(m_bface_elem_update_coeff.std_region_data( mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u))); const interpolation::ScalarMeshFunction<Real> &dual_nodal_volume = time_update.nodal_dual_volume(); // This is a loop over all boundaries in the SOLUTION space mesh Uint idx_in_metric = 0; for (; bcell_sol_iter != sol_iter_end; ++bcell_sol_iter) { const mesh::MeshEntity sol_cell = bcell_sol_iter->mesh_entity(); bface_res.fill(0.0); bface_update_coeff_vector.fill(0.0); geo_cell_metric_type const cell_geo_metric = data.m_geo_metric.cellwise_values(idx_in_metric); sol_cell_metric_type const cell_sol_metric = data.m_sol_metric.cellwise_values(idx_in_metric); flux_cell_metric_type const cell_flux_metric = data.m_flux_metric.cellwise_values(idx_in_metric); // Compute corrective residual on one boundary element // This call fills the data in 'bface_res' and // 'bface_update_coeff_vector' compute_on_element_weak(idx_in_metric, cell_geo_metric, cell_sol_metric, cell_flux_metric); for (Uint n = 0; n < sol_cell.nb_vert(); ++n) { // (*rdm_bc_base::m_rd_time_update)[sol_cell.vertex(n)] += // bface_update_coeff_vector[n]; // time_update.accumulate_nodal_wave_speed(sol_cell.vertex(n), // bface_update_coeff_vector[n]); const Real nodal_volume = dual_nodal_volume[sol_cell.vertex(n)]; // IMPORTANT: THE DIMENSION OF UPDATE COEFFICIENT IS k+ = |S| * // lambda, WHERE lambda IS THE MAXIMUM EIGENVALUE // bface_update_coeff_vector[n] ONLY CONTAINS THE VALUES OF lambda, // HENCE THE WAVE SPEED, WHICH SHOULD HOLD [(k+)*|S|] MUST BE // COMPUTED AS (k+) * |S|^2 // time_update.accumulate_nodal_wave_speed(sol_cell.vertex(n), nodal_volume * bface_update_coeff_vector[n]); // ON THE OTHER HAND, IN THE MAIN SOLVER, THE GOVERNING EQUATION IS // GIVEN BY du/dt = 1./|S| * RDM_res, WITH RDM_res BEING THE RDS // ACCUMULATED RESIDUALS. HENCE THE BOUNDARY FACE RESIDUALS // (bface_res[n,eq] MUST BE DIVIDED BY NODAL VOLUME const Real inv_nodal_volume = 1. / nodal_volume; for (Uint eq = 0; eq < Physics::NEQ; ++eq) { bface_res[n * Physics::NEQ + eq] *= inv_nodal_volume; } } res_cache.push_vec_to_buffer( sol_cell, bface_res, mesh::PointSetTagExt(sol_cell.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); idx_in_metric++; } // End of loop over boundary cells } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::global_lsys_fin_diff_jacobian_entries( RDTimeUpdate &time_update, interpolation::SolutionCache &residual_cache, interpolation::SolutionCache &residual_cache_perturbed, std::vector<std::tuple<Uint, Uint, Real>> &mat_buffer, std::vector<std::tuple<Uint, Real>> &rhs_buffer) { interpolation::VectorMeshFunction<Real> &solution = *(this->solution()); const_dof_iterator_typed sol_bdry_iter; m_metric_data->m_geo_cache.flush(); m_metric_data->m_sol_cache.flush(); residual_cache.flush(); const auto geo_sf_generator = rdm_bc_base::geo_space()->sf_generator(); const auto geo_quad_generator = rdm_bc_base::geo_space()->quad_generator(); for (sol_elem_range_typed const &bdry_elem_range : m_sol_ranges) { // ------------------------------------------ // Weak BC processing // Ia) Fill the geometry cache // Ib) Fill solution cache and optionally source cache // ------------------------------------------ for (sol_bdry_iter = bdry_elem_range.begin(); sol_bdry_iter != bdry_elem_range.end(); ++sol_bdry_iter) { const mesh::PointSetTag geo_cell_type = sol_bdry_iter->geo_pt_set_id(); const mesh::CellGeometry<MeshConfig::GDIM> geo_bdry_elem_coords = sol_bdry_iter->cell_geometry(); const mesh::MeshEntity sol_bdry_elem = sol_bdry_iter->mesh_entity(); const ElemShape cell_shape = geo_cell_type.elem_shape(); const Uint geo_order = geo_cell_type.poly_order(); const mesh::PointSetTagExt geo_pt_set_ext(geo_cell_type, P0, mesh::CellTransform::NO_TRANS, 0u); const mesh::sf::SFTag geo_sf = geo_sf_generator(cell_shape, geo_order); const mesh::PointSetTag geo_quad_set = geo_quad_generator(cell_shape, geo_order); const mesh::PointSetTagExt geo_quad_set_ext(geo_quad_set, P0, mesh::CellTransform::NO_TRANS, 0u); const mesh::DiscreteElemKey geo_key(geo_pt_set_ext, geo_sf, geo_quad_set_ext); m_metric_data->m_geo_cache.push_back_to_buffer(geo_bdry_elem_coords, geo_key); m_metric_data->m_sol_cache.push_back_to_buffer( sol_bdry_elem, solution, mesh::PointSetTagExt(sol_bdry_elem.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); } m_metric_data->m_geo_metric.empty_buffer(); m_metric_data->m_sol_metric.empty_buffer(); m_metric_data->m_geo_metric.evaluate(m_metric_data->m_geo_cache, interpolation::RebuildMetricIndex{true}); m_metric_data->m_sol_metric.evaluate(m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, interpolation::ComputeMetricDerivs{true}, interpolation::RebuildMetricIndex{true}); m_metric_data->m_flux_metric.empty_buffer(); m_metric_data->m_flux_metric.evaluate(m_metric_data->m_geo_cache, m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, m_metric_data->m_sol_metric, interpolation::RebuildMetricIndex{true}); // ------------------------------------------ // Weak BC processing // II) Evaluate metric terms // ------------------------------------------ compute_residuals(*m_metric_data, bdry_elem_range.begin(), bdry_elem_range.end(), time_update, residual_cache); // -------------------------------------------------- // Weak BC processing // III) Compute the residuals and store them in cache // -------------------------------------------------- Uint cell_idx_in_metric = 0u; for (sol_bdry_iter = bdry_elem_range.begin(); sol_bdry_iter != bdry_elem_range.end(); ++sol_bdry_iter) { const mesh::MeshEntity sol_bdry_elem = sol_bdry_iter->mesh_entity(); const math::DenseConstMatView<Real> elem_nodal_residuals = residual_cache.cell_values(cell_idx_in_metric); for (Uint n = 0; n < sol_bdry_elem.nb_vert(); ++n) { for (Uint eq = 0; eq < Physics::NEQ; ++eq) { const Uint dof_idx = sol_bdry_elem.vertex(n) * Physics::NEQ + eq; rhs_buffer.push_back(std::tuple<Uint, Real>(dof_idx, -elem_nodal_residuals(n, eq))); //(*m_rhs).add_value(dof_idx, -elem_nodal_residuals(n, eq), // 0); } } cell_idx_in_metric++; } // Loop over boundary elements of one type // --------------------------------------------------- // Weak BC processing // IV) Compute numerical Jacobians and accumulate them // to system matrix // --------------------------------------------------- const common::Range1D<Uint> elem_range(0, cell_idx_in_metric - 1); const mesh::MeshEntity first_bdry_elem = (*bdry_elem_range.begin()).mesh_entity(); const Uint nb_dof_per_elem = first_bdry_elem.nb_vert(); const mesh::PointSetTag cell_type_id = first_bdry_elem.pt_set_id(); for (Uint i_dof_in_elem = 0; i_dof_in_elem < nb_dof_per_elem; ++i_dof_in_elem) { for (Uint comp_u = 0; comp_u < Physics::NEQ; ++comp_u) { /* m_data->m_sol_cache.perturb_values( mesh::PointSetTagExt(cell_type_id, P0, mesh::CellTransform::DO_NOTHING, 0u), i_dof_in_elem, comp_u); */ m_metric_data->m_sol_cache.perturb_values(elem_range, i_dof_in_elem, comp_u); /* const math::DenseConstVecView<Real> unperturbed_node_in_cell = m_data->m_sol_cache.unperturbed_values( mesh::PointSetTagExt(cell_type_id, P0, mesh::CellTransform::DO_NOTHING, 0u)); */ const math::DenseConstVecView<Real> unperturbed_node_in_cell = m_metric_data->m_sol_cache.unperturbed_values(elem_range); m_metric_data->m_sol_metric.empty_buffer(); m_metric_data->m_sol_metric.evaluate( m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, interpolation::ComputeMetricDerivs{true}, interpolation::RebuildMetricIndex{true}); m_metric_data->m_flux_metric.empty_buffer(); m_metric_data->m_flux_metric.evaluate( m_metric_data->m_geo_cache, m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, m_metric_data->m_sol_metric, interpolation::RebuildMetricIndex{true}); residual_cache_perturbed.flush(); compute_residuals(*m_metric_data, bdry_elem_range.begin(), bdry_elem_range.end(), time_update, residual_cache_perturbed); cell_idx_in_metric = 0u; for (sol_bdry_iter = bdry_elem_range.begin(); sol_bdry_iter != bdry_elem_range.end(); ++sol_bdry_iter) { const mesh::MeshEntity sol_bdry_elem = sol_bdry_iter->mesh_entity(); const math::DenseConstMatView<Real> sol_nodal_values = m_metric_data->m_sol_cache.cell_values(cell_idx_in_metric); const math::DenseConstMatView<Real> elem_nodal_residuals = residual_cache.cell_values(cell_idx_in_metric); const math::DenseConstMatView<Real> elem_nodal_residuals_perturbed = residual_cache_perturbed.cell_values(cell_idx_in_metric); const Real inv_du = 1. / (sol_nodal_values(i_dof_in_elem, comp_u) - unperturbed_node_in_cell[cell_idx_in_metric]); // Compute finite difference derivatives of residuals with // respect to du (which is the perturbation of component // comp_u of solution in node i_dof_in_elem) for (Uint v = 0; v < sol_bdry_elem.nb_vert(); ++v) { for (Uint comp = 0; comp < Physics::NEQ; ++comp) { // For each component // When v == i_dof_in_elem, we are computing // derivatives of residuals corresponding to node v // with respect to components of u associated to v // (diagonal blocks) in the system matrix const Uint global_row_idx = Physics::NEQ * sol_bdry_elem.vertex(v) + comp; // if (!is_Dirichlet_node[global_row_idx]) // { const Uint global_col_idx = Physics::NEQ * sol_bdry_elem.vertex(i_dof_in_elem) + comp_u; const Real residual_finite_diff = inv_du * (elem_nodal_residuals_perturbed(v, comp) - elem_nodal_residuals(v, comp)); mat_buffer.push_back(std::tuple<Uint, Uint, Real>(global_row_idx, global_col_idx, residual_finite_diff)); } } cell_idx_in_metric++; } // Loop over boundary elements of one type /* m_data->m_sol_cache.remove_perturbation( mesh::PointSetTagExt(cell_type_id, P0, mesh::CellTransform::DO_NOTHING, 0u)); */ m_metric_data->m_sol_cache.remove_perturbation(elem_range); } // Loop over equations components } // Loop over local dofs in one element } // Loop over all element types present in one boundary } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::global_lsys_rhs_entries( RDTimeUpdate &time_update, interpolation::SolutionCache &res_cache, std::vector<std::tuple<Uint, Real>> &rhs_buffer) { interpolation::VectorMeshFunction<Real> &solution = *(this->solution()); const_dof_iterator_typed sol_bdry_iter; m_metric_data->m_geo_cache.flush(); m_metric_data->m_sol_cache.flush(); res_cache.flush(); const auto geo_sf_generator = rdm_bc_base::geo_space()->sf_generator(); const auto geo_quad_generator = rdm_bc_base::geo_space()->quad_generator(); for (sol_elem_range_typed const &bdry_elem_range : m_sol_ranges) { // ------------------------------------------ // Weak BC processing // Ia) Fill the geometry cache // Ib) Fill solution cache and optionally source cache // ------------------------------------------ for (sol_bdry_iter = bdry_elem_range.begin(); sol_bdry_iter != bdry_elem_range.end(); ++sol_bdry_iter) { const mesh::PointSetTag geo_cell_type = sol_bdry_iter->geo_pt_set_id(); const mesh::CellGeometry<MeshConfig::GDIM> geo_bdry_elem_coords = sol_bdry_iter->cell_geometry(); const mesh::MeshEntity sol_bdry_elem = sol_bdry_iter->mesh_entity(); const ElemShape cell_shape = geo_cell_type.elem_shape(); const Uint geo_order = geo_cell_type.poly_order(); const mesh::PointSetTagExt geo_pt_set_ext(geo_cell_type, P0, mesh::CellTransform::NO_TRANS, 0u); const mesh::sf::SFTag geo_sf = geo_sf_generator(cell_shape, geo_order); const mesh::PointSetTag geo_quad_set = geo_quad_generator(cell_shape, geo_order); const mesh::PointSetTagExt geo_quad_set_ext(geo_quad_set, P0, mesh::CellTransform::NO_TRANS, 0u); const mesh::DiscreteElemKey geo_key(geo_pt_set_ext, geo_sf, geo_quad_set_ext); m_metric_data->m_geo_cache.push_back_to_buffer(geo_bdry_elem_coords, geo_key); m_metric_data->m_sol_cache.push_back_to_buffer( sol_bdry_elem, solution, mesh::PointSetTagExt(sol_bdry_elem.pt_set_id(), P0, mesh::CellTransform::NO_TRANS, 0u)); } m_metric_data->m_geo_metric.empty_buffer(); m_metric_data->m_sol_metric.empty_buffer(); m_metric_data->m_geo_metric.evaluate(m_metric_data->m_geo_cache, interpolation::RebuildMetricIndex{true}); m_metric_data->m_sol_metric.evaluate(m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, interpolation::ComputeMetricDerivs{true}, interpolation::RebuildMetricIndex{true}); m_metric_data->m_flux_metric.empty_buffer(); m_metric_data->m_flux_metric.evaluate(m_metric_data->m_geo_cache, m_metric_data->m_geo_metric, m_metric_data->m_sol_cache, m_metric_data->m_sol_metric, interpolation::RebuildMetricIndex{true}); // ------------------------------------------ // Weak BC processing // II) Evaluate metric terms // ------------------------------------------ compute_residuals(*m_metric_data, bdry_elem_range.begin(), bdry_elem_range.end(), time_update, res_cache); // -------------------------------------------------- // Weak BC processing // III) Compute the residuals and store them in cache // -------------------------------------------------- Uint cell_idx_in_metric = 0u; for (sol_bdry_iter = bdry_elem_range.begin(); sol_bdry_iter != bdry_elem_range.end(); ++sol_bdry_iter) { const mesh::MeshEntity sol_bdry_elem = sol_bdry_iter->mesh_entity(); const math::DenseConstMatView<Real> elem_nodal_residuals = res_cache.cell_values(cell_idx_in_metric); for (Uint n = 0; n < sol_bdry_elem.nb_vert(); ++n) { for (Uint eq = 0; eq < Physics::NEQ; ++eq) { const Uint dof_idx = sol_bdry_elem.vertex(n) * Physics::NEQ + eq; // (*m_rhs).add_value(dof_idx, -elem_nodal_residuals(n, eq), // 0); rhs_buffer.push_back(std::tuple<Uint, Real>(dof_idx, -elem_nodal_residuals(n, eq))); } } cell_idx_in_metric++; } // Loop over boundary elements of one type } // Loop over all element types present in one boundary } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> const std::vector<typename WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::sol_elem_range_typed> &WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::sol_ranges() const { return m_sol_ranges; } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> typename WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::bc_metric_data_t const &WeakBC< MeshConfig, Physics, BcDim, ConcreteBC>::metric_data() const { return *m_metric_data; } // ---------------------------------------------------------------------------- template <typename MeshConfig, typename Physics, Uint BcDim, typename ConcreteBC> void WeakBC<MeshConfig, Physics, BcDim, ConcreteBC>::compute_on_element_weak( const Uint idx_in_metric, geo_cell_metric_type const &cell_geo_metric, sol_cell_metric_type const &cell_sol_metric, flux_cell_metric_type const &cell_flux_metric) { static_cast<ConcreteBC *>(this)->compute_on_element_weak(idx_in_metric, cell_geo_metric, cell_sol_metric, cell_flux_metric); math::DenseDVec<Real> &bface_res = *(m_bface_residual.std_region_data(cell_sol_metric.std_region_type())); // Rescale the residuals assigned to each dof/node so that the their sum // is equal to the total integrated residual over the boundary face. // This is necessary for bases that do not form partition of unity m_sum_dof_residuals.fill(0.0); const Uint nb_local_dof = cell_sol_metric.nb_dof_in_cell(); ; for (Uint n = 0; n < nb_local_dof; ++n) { for (Uint eq = 0; eq < Physics::NEQ; ++eq) { m_sum_dof_residuals[eq] += bface_res[n * Physics::NEQ + eq]; } } for (Uint eq = 0; eq < Physics::NEQ; ++eq) { if (std::abs(m_sum_dof_residuals[eq]) > 1.e-14) { const Real scale_factor = m_total_facet_residual[eq] / m_sum_dof_residuals[eq]; for (Uint n = 0; n < nb_local_dof; ++n) { bface_res[n * Physics::NEQ + eq] *= scale_factor; } } } } // ----------------------------------------------------------------------------- } // namespace rdm } // namespace solver } // namespace pdekit #endif
[ "martin.vymazal@gmail.com" ]
martin.vymazal@gmail.com
b9c4367f6127967b815a86527688bd4b08f27efe
3c44e638b331b356aaa9c661b56fc490a5df538c
/Plugins/RakNet/Source/RakNet/Private/GetTime.cpp
d9fe10db19117e8447be1855abfd1dc8705744e0
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
jashking/RN4UE4
31a408224542fb090614f7ca6438100c5f44f060
50b17bedfe6bb7c28aae9d30f9a43ca51894d86c
refs/heads/master
2021-01-19T12:47:43.071093
2017-04-21T05:42:15
2017-04-21T05:42:15
88,045,585
1
1
null
2017-04-12T11:44:48
2017-04-12T11:44:48
null
UTF-8
C++
false
false
4,703
cpp
/* * Copyright (c) 2014, Oculus VR, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /// \file /// #include "RakNetPrivatePCH.h" #if defined(_WIN32) #include "WindowsIncludes.h" #if !defined(WINDOWS_PHONE_8) // To call timeGetTime // on Code::Blocks, this needs to be libwinmm.a instead #pragma comment(lib, "Winmm.lib") #endif #endif #include "GetTime.h" #if defined(_WIN32) //DWORD mProcMask; //DWORD mSysMask; //HANDLE mThread; #else #include <sys/time.h> #include <unistd.h> RakNet::TimeUS initialTime; #endif static bool initialized=false; #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 #include "SimpleMutex.h" RakNet::TimeUS lastNormalizedReturnedValue=0; RakNet::TimeUS lastNormalizedInputValue=0; /// This constraints timer forward jumps to 1 second, and does not let it jump backwards /// See http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days /// This also has the effect where debugging a sending system won't treat the time spent halted past 1 second as elapsed network time RakNet::TimeUS NormalizeTime(RakNet::TimeUS timeIn) { RakNet::TimeUS diff, lastNormalizedReturnedValueCopy; static RakNet::SimpleMutex mutex; mutex.Lock(); if (timeIn>=lastNormalizedInputValue) { diff = timeIn-lastNormalizedInputValue; if (diff > GET_TIME_SPIKE_LIMIT) lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; else lastNormalizedReturnedValue+=diff; } else lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; lastNormalizedInputValue=timeIn; lastNormalizedReturnedValueCopy=lastNormalizedReturnedValue; mutex.Unlock(); return lastNormalizedReturnedValueCopy; } #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 RakNet::Time RakNet::GetTime( void ) { return (RakNet::Time)(GetTimeUS()/1000); } RakNet::TimeMS RakNet::GetTimeMS( void ) { return (RakNet::TimeMS)(GetTimeUS()/1000); } #if defined(_WIN32) RakNet::TimeUS GetTimeUS_Windows( void ) { if ( initialized == false) { initialized = true; // Save the current process #if !defined(_WIN32_WCE) // HANDLE mProc = GetCurrentProcess(); // Get the current Affinity #if _MSC_VER >= 1400 && defined (_M_X64) // GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask); #else // GetProcessAffinityMask(mProc, &mProcMask, &mSysMask); #endif // mThread = GetCurrentThread(); #endif // _WIN32_WCE } // 9/26/2010 In China running LuDaShi, QueryPerformanceFrequency has to be called every time because CPU clock speeds can be different RakNet::TimeUS curTime; LARGE_INTEGER PerfVal; LARGE_INTEGER yo1; QueryPerformanceFrequency( &yo1 ); QueryPerformanceCounter( &PerfVal ); __int64 quotient, remainder; quotient=((PerfVal.QuadPart) / yo1.QuadPart); remainder=((PerfVal.QuadPart) % yo1.QuadPart); curTime = (RakNet::TimeUS) quotient*(RakNet::TimeUS)1000000 + (remainder*(RakNet::TimeUS)1000000 / yo1.QuadPart); #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 return NormalizeTime(curTime); #else return curTime; #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 } #elif defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) RakNet::TimeUS GetTimeUS_Linux( void ) { timeval tp; if ( initialized == false) { gettimeofday( &tp, 0 ); initialized=true; // I do this because otherwise RakNet::Time in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion initialTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); } // GCC RakNet::TimeUS curTime; gettimeofday( &tp, 0 ); curTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 return NormalizeTime(curTime - initialTime); #else return curTime - initialTime; #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 } #endif RakNet::TimeUS RakNet::GetTimeUS( void ) { #if defined(_WIN32) return GetTimeUS_Windows(); #else return GetTimeUS_Linux(); #endif } bool RakNet::GreaterThan(RakNet::Time a, RakNet::Time b) { // a > b? const RakNet::Time halfSpan =(RakNet::Time) (((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2); return b!=a && b-a>halfSpan; } bool RakNet::LessThan(RakNet::Time a, RakNet::Time b) { // a < b? const RakNet::Time halfSpan = ((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2; return b!=a && b-a<halfSpan; }
[ "yujen.dev@gmail.com" ]
yujen.dev@gmail.com
6fa16ec662d9200c6a862729802ccc9c5efe07e1
ffd1a3ce6ab76cfadd35d4a9198529904fe4bcd2
/example/basic.cpp
ddf8ebead9e99ecd2bf4b09da888af5449e3b96c
[]
no_license
xinyang-go/gcpp
adeb6334ced81a018b655194463e51cdb242a440
6e62a2f3eecfe00932e1310806eeb1559ec46dfb
refs/heads/main
2023-03-13T02:15:57.818657
2021-02-18T16:00:56
2021-02-18T16:00:56
340,101,734
3
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
// // Created by xinyang on 2021/2/18. // #include <gcpp/gcpp.hpp> #include <iostream> struct A { gcpp::gc_ptr<A> p_a; ~A() { std::cout << "A destroy!" << std::endl; } }; int main() { { auto a1 = gcpp::gc_new<A>(); auto a2 = gcpp::gc_new<A>(); a1->p_a = a2; a2->p_a = a1; } std::cout << "main stop!" << std::endl; // optional: 线程结束时会自动GC当前线程。 gcpp::gc_collect(); return 0; }
[ "txy15436@gmail.com" ]
txy15436@gmail.com
514bead86a82075e9c985bea44e0eb4cc2f34f4e
e50d5d22ba46f17097d5dc86d12ec9d247929468
/python/kwiver/vital/algo/uv_unwrap_mesh.cxx
277ba789a387c1b87ee784e7825af98835de800a
[ "BSD-3-Clause" ]
permissive
nrsyed/kwiver
488a0495b8c3b523f6639669aff73931373d4ca4
990a93b637af06129a842be38b88908df358761b
refs/heads/master
2023-02-25T20:22:10.813154
2021-01-21T16:51:23
2021-01-21T16:51:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,320
cxx
/*ckwg +29 * Copyright 2020 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <python/kwiver/vital/algo/trampoline/uv_unwrap_mesh_trampoline.txx> #include <python/kwiver/vital/algo/uv_unwrap_mesh.h> #include <pybind11/pybind11.h> namespace kwiver { namespace vital { namespace python { namespace py = pybind11; void uv_unwrap_mesh(py::module &m) { py::class_< kwiver::vital::algo::uv_unwrap_mesh, std::shared_ptr<kwiver::vital::algo::uv_unwrap_mesh>, kwiver::vital::algorithm_def<kwiver::vital::algo::uv_unwrap_mesh>, uv_unwrap_mesh_trampoline<> >(m, "UVUnwrapMesh") .def(py::init()) .def_static("static_type_name", &kwiver::vital::algo::uv_unwrap_mesh::static_type_name) .def("unwrap", &kwiver::vital::algo::uv_unwrap_mesh::unwrap); } } } }
[ "john.parent@kitware.com" ]
john.parent@kitware.com
4b957a5e3b6ea749c1dfa217f15eefb39e3c50ee
82770c7bc5e2f27a48b8c370b0bab2ee41f24d86
/graph-tool/src/graph/community/graph_community.hh
d0728fd90a80a507cb4f043539f823f6f375e0c8
[ "Apache-2.0", "GPL-3.0-only", "LicenseRef-scancode-philippe-de-muyter", "GPL-3.0-or-later" ]
permissive
johankaito/fufuka
77ddb841f27f6ce8036d7b38cb51dc62e85b2679
32a96ecf98ce305c2206c38443e58fdec88c788d
refs/heads/master
2022-07-20T00:51:55.922063
2015-08-21T20:56:48
2015-08-21T20:56:48
39,845,849
2
0
Apache-2.0
2022-06-29T23:30:11
2015-07-28T16:39:54
Python
UTF-8
C++
false
false
17,368
hh
// graph-tool -- a general graph modification and manipulation thingy // // Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de> // // 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 GRAPH_COMMUNITY_HH #define GRAPH_COMMUNITY_HH #include <unordered_set> #include <tuple> #include <iostream> #include <fstream> #include <iomanip> #define BOOST_DISABLE_ASSERTS #include "boost/multi_array.hpp" #include "graph_util.hh" #include "graph_properties.hh" #include "random.hh" namespace graph_tool { using namespace std; using namespace boost; using std::unordered_map; using std::unordered_set; // computes the community structure through a spin glass system with // simulated annealing template <template <class G, class CommunityMap> class NNKS> struct get_communities { template <class Graph, class VertexIndex, class WeightMap, class CommunityMap> void operator()(const Graph& g, VertexIndex vertex_index, WeightMap weights, CommunityMap s, double gamma, size_t n_iter, pair<double, double> Tinterval, size_t n_spins, rng_t& rng, pair<bool, string> verbose) const { typedef typename graph_traits<Graph>::vertex_descriptor vertex_t; typedef typename property_traits<WeightMap>::key_type weight_key_t; auto random = std::bind(std::uniform_real_distribution<>(), std::ref(rng)); stringstream out_str; ofstream out_file; if (verbose.second != "") { out_file.open(verbose.second.c_str()); if (!out_file.is_open()) throw IOException("error opening file " + verbose.second + " for writing"); out_file.exceptions (ifstream::eofbit | ifstream::failbit | ifstream::badbit); } double Tmin = Tinterval.first; double Tmax = Tinterval.second; unordered_map<size_t, size_t> Ns; // spin histogram CommunityMap temp_s(vertex_index, num_vertices(g)); // init spins from [0,N-1] and global info uniform_int_distribution<size_t> sample_spin(0, n_spins-1); typename graph_traits<Graph>::vertex_iterator vi,vi_end; for (tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) { s[*vi] = temp_s[*vi] = sample_spin(rng); Ns[s[*vi]]++; } NNKS<Graph,CommunityMap> Nnnks(g, s); // this will retrieve the expected // number of neighbours with given // spin, as a function of degree // define cooling rate so that temperature starts at Tmax at temp_count // == 0 and reaches Tmin at temp_count == n_iter - 1 if (Tmin < numeric_limits<double>::epsilon()) Tmin = numeric_limits<double>::epsilon(); double cooling_rate = -(log(Tmin)-log(Tmax))/(n_iter-1); // start the annealing for (size_t temp_count = 0; temp_count < n_iter; ++temp_count) { double T = Tmax*exp(-cooling_rate*temp_count); double E = 0; vector<std::tuple<size_t, size_t, size_t> > updates; // sample a new spin for every vertex int NV = num_vertices(g),i; #pragma omp parallel for default(shared) private(i)\ reduction(+:E) schedule(runtime) if (NV > 100) for (i = 0; i < NV; ++i) { vertex_t v = vertex(i, g); if (v == graph_traits<Graph>::null_vertex()) continue; size_t new_s; { #pragma omp critical new_s = sample_spin(rng); } unordered_map<size_t, double> ns; // number of neighbours with a // given spin 's' (weighted) // neighborhood spins info typename graph_traits<Graph>::out_edge_iterator e, e_end; for (tie(e,e_end) = out_edges(v,g); e != e_end; ++e) { vertex_t t = target(*e, g); if (t != v) ns[s[t]] += get(weights, weight_key_t(*e)); } size_t k = out_degree_no_loops(v, g); double curr_e = gamma*Nnnks(k,s[v]) - ns[s[v]]; double new_e = gamma*Nnnks(k,new_s) - ns[new_s]; double r; { #pragma omp critical r = random(); } if (new_e < curr_e || r < exp(-(new_e - curr_e)/T)) { temp_s[v] = new_s; curr_e = new_e; { #pragma omp critical updates.push_back(std::make_tuple(k, size_t(s[v]), new_s)); Ns[s[v]]--; Ns[new_s]++; } } else { temp_s[v] = s[v]; } E += curr_e; } swap(s, temp_s); for (typeof(updates.begin()) iter = updates.begin(); iter != updates.end(); ++iter) Nnnks.Update(std::get<0>(*iter), std::get<1>(*iter), std::get<2>(*iter)); if (verbose.first) { for (size_t j = 0; j < out_str.str().length(); ++j) cout << "\b"; out_str.str(""); size_t ns = 0; for (typeof(Ns.begin()) iter = Ns.begin(); iter != Ns.end(); ++iter) if (iter->second > 0) ns++; out_str << setw(lexical_cast<string>(n_iter).size()) << temp_count << " of " << n_iter << " (" << setw(2) << (temp_count+1)*100/n_iter << "%) " << "temperature: " << setw(14) << setprecision(10) << T << " spins: " << ns << " energy: " << E; cout << out_str.str() << flush; } if (verbose.second != "") { try { size_t ns = 0; for (typeof(Ns.begin()) iter = Ns.begin(); iter != Ns.end(); ++iter) if (iter->second > 0) ns++; out_file << temp_count << "\t" << setprecision(10) << T << "\t" << ns << "\t" << E << endl; } catch (ifstream::failure e) { throw IOException("error writing to file " + verbose.second + ": " + e.what()); } } } if (n_iter % 2 != 0) { int NV = num_vertices(g), i; #pragma omp parallel for default(shared) private(i)\ schedule(runtime) if (NV > 100) for (i = 0; i < NV; ++i) { vertex_t v = vertex(i, g); if (v == graph_traits<Graph>::null_vertex()) continue; temp_s[v] = s[v]; } } // rename spins, starting from zero unordered_map<size_t,size_t> spins; for (tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) { if (spins.find(s[*vi]) == spins.end()) spins[s[*vi]] = spins.size() - 1; s[*vi] = spins[s[*vi]]; } } }; template <class Graph, class CommunityMap> class NNKSErdosReyni { public: NNKSErdosReyni(const Graph &g, CommunityMap s) { size_t N = 0; double _avg_k = 0.0; typename graph_traits<Graph>::vertex_iterator v,v_end; for (tie(v,v_end) = vertices(g); v != v_end; ++v) { size_t k = out_degree_no_loops(*v,g); _avg_k += k; N++; _Ns[s[*v]]++; } _p = _avg_k/(N*N); } void Update(size_t, size_t old_s, size_t s) { _Ns[old_s]--; if (_Ns[old_s] == 0) _Ns.erase(old_s); _Ns[s]++; } double operator()(size_t, size_t s) const { size_t ns = 0; typeof(_Ns.begin()) iter = _Ns.find(s); if (iter != _Ns.end()) ns = iter->second; return _p*ns; } private: double _p; unordered_map<size_t,size_t> _Ns; }; template <class Graph, class CommunityMap> class NNKSUncorr { public: NNKSUncorr(const Graph &g, CommunityMap s): _g(g), _K(0) { typename graph_traits<Graph>::vertex_iterator v,v_end; for (tie(v,v_end) = vertices(_g); v != v_end; ++v) { size_t k = out_degree_no_loops(*v, _g); _K += k; _Ks[s[*v]] += k; } } void Update(size_t k, size_t old_s, size_t s) { _Ks[old_s] -= k; if (_Ks[old_s] == 0) _Ks.erase(old_s); _Ks[s] += k; } double operator()(size_t k, size_t s) const { size_t ks = 0; typeof(_Ks.begin()) iter = _Ks.find(s); if (iter != _Ks.end()) ks = iter->second; return k*ks/double(_K); } private: const Graph& _g; size_t _K; unordered_map<size_t,size_t> _Ks; }; template <class Graph, class CommunityMap> class NNKSCorr { public: NNKSCorr(const Graph &g, CommunityMap s): _g(g) { unordered_set<size_t> spins; typename graph_traits<Graph>::vertex_iterator v,v_end; for (tie(v,v_end) = vertices(_g); v != v_end; ++v) { size_t k = out_degree_no_loops(*v, _g); _Nk[k]++; _Nks[k][s[*v]]++; spins.insert(s[*v]); } size_t E = 0; typename graph_traits<Graph>::edge_iterator e,e_end; for (tie(e,e_end) = edges(_g); e != e_end; ++e) { typename graph_traits<Graph>::vertex_descriptor src, tgt; src = source(*e,g); tgt = target(*e,g); if (src != tgt) { size_t k1 = out_degree_no_loops(src, g); size_t k2 = out_degree_no_loops(tgt, g); _Pkk[k1][k2]++; _Pkk[k2][k1]++; E++; } } for (typeof(_Pkk.begin()) iter1 = _Pkk.begin(); iter1 != _Pkk.end(); ++iter1) { double sum = 0; for (typeof(iter1->second.begin()) iter2 = iter1->second.begin(); iter2 != iter1->second.end(); ++iter2) sum += iter2->second; for (typeof(iter1->second.begin()) iter2 = iter1->second.begin(); iter2 != iter1->second.end(); ++iter2) iter2->second /= sum; } for (typeof(_Nk.begin()) k_iter = _Nk.begin(); k_iter != _Nk.end(); ++k_iter) { size_t k1 = k_iter->first; _degs.push_back(k1); for (typeof(spins.begin()) s_iter = spins.begin(); s_iter != spins.end(); ++s_iter) for (typeof(_Nk.begin()) k_iter2 = _Nk.begin(); k_iter2 != _Nk.end(); ++k_iter2) { size_t k2 = k_iter2->first; if (_Nks[k2].find(*s_iter) != _Nks[k2].end()) _NNks[k1][*s_iter] += k1*_Pkk[k1][k2] * _Nks[k2][*s_iter]/double(_Nk[k2]); } } } void Update(size_t k, size_t old_s, size_t s) { int i, NK = _degs.size(); #pragma omp parallel for default(shared) private(i) schedule(runtime) if (NK > 100) for (i = 0; i < NK; ++i) { size_t k1 = _degs[i], k2 = k; if (_Pkk.find(k1) == _Pkk.end()) continue; if (_Pkk.find(k1)->second.find(k2) == _Pkk.find(k1)->second.end()) continue; unordered_map<size_t,double>& NNks_k1 = _NNks[k1]; double Pk1k2 = _Pkk[k1][k2]; unordered_map<size_t,size_t>& Nksk2 = _Nks[k2]; double Nk2 = _Nk[k2]; NNks_k1[old_s] -= k1*Pk1k2 * Nksk2[old_s]/Nk2; if (NNks_k1[old_s] == 0.0) NNks_k1.erase(old_s); if (Nksk2.find(s) != Nksk2.end()) NNks_k1[s] -= k1*Pk1k2 * Nksk2[s]/Nk2; if (NNks_k1[s] == 0.0) NNks_k1.erase(s); } _Nks[k][old_s]--; if (_Nks[k][old_s] == 0) _Nks[k].erase(old_s); _Nks[k][s]++; #pragma omp parallel for default(shared) private(i) schedule(runtime) if (NK > 100) for (i = 0; i < NK; ++i) { size_t k1 = _degs[i], k2 = k; if (_Pkk.find(k1) == _Pkk.end()) continue; if (_Pkk.find(k1)->second.find(k2) == _Pkk.find(k1)->second.end()) continue; unordered_map<size_t,double>& NNks_k1 = _NNks[k1]; double Pk1k2 = _Pkk[k1][k2]; unordered_map<size_t,size_t>& Nksk2 = _Nks[k2]; double Nk2 = _Nk[k2]; NNks_k1[old_s] += k1*Pk1k2 * Nksk2[old_s]/Nk2; if (NNks_k1[old_s] == 0.0) NNks_k1.erase(old_s); NNks_k1[s] += k1*Pk1k2 * Nksk2[s]/Nk2; } } double operator()(size_t k, size_t s) const { const unordered_map<size_t,double>& nnks = _NNks.find(k)->second; const typeof(nnks.begin()) iter = nnks.find(s); if (iter != nnks.end()) return iter->second; return 0.0; } private: const Graph& _g; vector<size_t> _degs; unordered_map<size_t,size_t> _Nk; unordered_map<size_t,unordered_map<size_t,double> > _Pkk; unordered_map<size_t,unordered_map<size_t,size_t> > _Nks; unordered_map<size_t,unordered_map<size_t,double> > _NNks; }; enum comm_corr_t { ERDOS_REYNI, UNCORRELATED, CORRELATED }; struct get_communities_selector { get_communities_selector(comm_corr_t corr, GraphInterface::vertex_index_map_t index) : _corr(corr), _index(index) {} comm_corr_t _corr; GraphInterface::vertex_index_map_t _index; template <class Graph, class WeightMap, class CommunityMap> void operator()(const Graph& g, WeightMap weights, CommunityMap s, double gamma, size_t n_iter, pair<double, double> Tinterval, size_t Nspins, rng_t& rng, pair<bool, string> verbose) const { switch (_corr) { case ERDOS_REYNI: get_communities<NNKSErdosReyni>()(g, _index, weights, s, gamma, n_iter, Tinterval, Nspins, rng, verbose); break; case UNCORRELATED: get_communities<NNKSUncorr>()(g, _index, weights, s, gamma, n_iter, Tinterval, Nspins, rng, verbose); break; case CORRELATED: get_communities<NNKSCorr>()(g, _index, weights, s, gamma, n_iter, Tinterval, Nspins, rng, verbose); break; } } }; // get Newman's modularity of a given community partition struct get_modularity { template <class Graph, class WeightMap, class CommunityMap> void operator()(const Graph& g, WeightMap weights, CommunityMap b, double& Q) const { vector<double> er, err; double W = 0; typename graph_traits<Graph>::edge_iterator e, e_end; for (tie(e, e_end) = edges(g); e != e_end; ++e) { size_t r = get(b, source(*e,g)); size_t s = get(b, target(*e,g)); double w = get(weights, *e); W += 2 * w; if (er.size() <= r) er.resize(r + 1); er[r] += w; if (er.size() <= s) er.resize(s + 1); er[s] += w; if (r == s) { if (err.size() <= r) err.resize(r + 1); err[r] += 2 * w; } } Q = 0; for (size_t r = 0; r < er.size(); ++r) { if (err.size() <= r) err.resize(r + 1); Q += err[r] - (er[r] * er[r]) / W; } Q /= W; } }; } // graph_tool namespace #endif //GRAPH_COMMUNITY_HH
[ "john.g.keto@gmail.com" ]
john.g.keto@gmail.com
6b10b35b17bfb88d2a2b97363294f177d7c3779d
ec770bb5a9d30110ddec41584f6b5098b382abe6
/store/common/backend/lockserver.cc
5c9edfcdb55cddc11c2c1eeefb01a2d9429aef1e
[]
no_license
xygroup/tapir
90b26ff72d0c409f8829bf6640d5c54d29262956
6d5fd429809cb6968abdcd7daab723a518ede4ba
refs/heads/master
2020-06-14T03:09:18.040717
2016-08-10T00:37:57
2016-08-10T00:37:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,297
cc
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- /*********************************************************************** * * spanstore/lockserver.cc: * Simple multi-reader, single-writer lock server * **********************************************************************/ #include "lockserver.h" using namespace std; LockServer::LockServer() { readers = 0; writers = 0; } LockServer::~LockServer() { } bool LockServer::Waiter::checkTimeout(const struct timeval &now) { if (now.tv_sec > waitTime.tv_sec) { return true; } else { ASSERT(now.tv_usec > waitTime.tv_usec && now.tv_sec == waitTime.tv_sec); if (now.tv_usec - waitTime.tv_usec > LOCK_WAIT_TIMEOUT) return true; } return false; } void LockServer::Lock::waitForLock(uint64_t requester, bool write) { if (waiters.find(requester) != waiters.end()) { // Already waiting return; } Debug("[%lu] Adding me to the queue ...", requester); // Otherwise waiters[requester] = Waiter(write); waitQ.push(requester); } bool LockServer::Lock::tryAcquireLock(uint64_t requester, bool write) { if (waitQ.size() == 0) { return true; } Debug("[%lu] Trying to get lock for %d", requester, (int)write); struct timeval now; uint64_t w = waitQ.front(); gettimeofday(&now, NULL); // prune old requests out of the wait queue while (waiters[w].checkTimeout(now)) { waiters.erase(w); waitQ.pop(); // if everyone else was old ... if (waitQ.size() == 0) { return true; } w = waitQ.front(); ASSERT(waiters.find(w) != waiters.end()); } if (waitQ.front() == requester) { // this lock is being reserved for the requester waitQ.pop(); ASSERT(waiters.find(requester) != waiters.end()); ASSERT(waiters[requester].write == write); waiters.erase(requester); return true; } else { // otherwise, add me to the list waitForLock(requester, write); return false; } } bool LockServer::Lock::isWriteNext() { if (waitQ.size() == 0) return false; struct timeval now; uint64_t w = waitQ.front(); gettimeofday(&now, NULL); // prune old requests out of the wait queue while (waiters[w].checkTimeout(now)) { waiters.erase(w); waitQ.pop(); // if everyone else was old ... if (waitQ.size() == 0) { return false; } w = waitQ.front(); ASSERT(waiters.find(w) != waiters.end()); } ASSERT(waiters.find(waitQ.front()) != waiters.end()); return waiters[waitQ.front()].write; } bool LockServer::lockForRead(const string &lock, uint64_t requester) { Lock &l = locks[lock]; Debug("Lock for Read: %s [%lu %lu %lu %lu]", lock.c_str(), readers, writers, l.holders.size(), l.waiters.size()); switch (l.state) { case UNLOCKED: // if you are next in the queue if (l.tryAcquireLock(requester, false)) { Debug("[%lu] I have acquired the read lock!", requester); l.state = LOCKED_FOR_READ; ASSERT(l.holders.size() == 0); l.holders.insert(requester); readers++; return true; } return false; case LOCKED_FOR_READ: // if you already hold this lock if (l.holders.find(requester) != l.holders.end()) { return true; } // There is a write waiting, let's give up the lock if (l.isWriteNext()) { Debug("[%lu] Waiting on lock because there is a pending write request", requester); l.waitForLock(requester, false); return false; } l.holders.insert(requester); readers++; return true; case LOCKED_FOR_WRITE: case LOCKED_FOR_READ_WRITE: if (l.holders.count(requester) > 0) { l.state = LOCKED_FOR_READ_WRITE; readers++; return true; } ASSERT(l.holders.size() == 1); Debug("Locked for write, held by %lu", *(l.holders.begin())); l.waitForLock(requester, false); return false; } NOT_REACHABLE(); return false; } bool LockServer::lockForWrite(const string &lock, uint64_t requester) { Lock &l = locks[lock]; Debug("Lock for Write: %s [%lu %lu %lu %lu]", lock.c_str(), readers, writers, l.holders.size(), l.waiters.size()); switch (l.state) { case UNLOCKED: // Got it! if (l.tryAcquireLock(requester, true)) { Debug("[%lu] I have acquired the write lock!", requester); l.state = LOCKED_FOR_WRITE; ASSERT(l.holders.size() == 0); l.holders.insert(requester); writers++; return true; } return false; case LOCKED_FOR_READ: if (l.holders.size() == 1 && l.holders.count(requester) > 0) { // if there is one holder of this read lock and it is the // requester, then upgrade the lock l.state = LOCKED_FOR_READ_WRITE; writers++; return true; } Debug("Locked for read by%s%lu other people", l.holders.count(requester) > 0 ? "you" : "", l.holders.size()); l.waitForLock(requester, true); return false; case LOCKED_FOR_WRITE: case LOCKED_FOR_READ_WRITE: ASSERT(l.holders.size() == 1); if (l.holders.count(requester) > 0) { return true; } Debug("Held by %lu for %s", *(l.holders.begin()), (l.state == LOCKED_FOR_WRITE) ? "write" : "read-write" ); l.waitForLock(requester, true); return false; } NOT_REACHABLE(); return false; } void LockServer::releaseForRead(const string &lock, uint64_t holder) { if (locks.find(lock) == locks.end()) { return; } Lock &l = locks[lock]; if (l.holders.count(holder) == 0) { Warning("[%ld] Releasing unheld read lock: %s", holder, lock.c_str()); return; } switch (l.state) { case UNLOCKED: case LOCKED_FOR_WRITE: return; case LOCKED_FOR_READ: readers--; if (l.holders.erase(holder) < 1) { Warning("[%ld] Releasing unheld read lock: %s", holder, lock.c_str()); } if (l.holders.empty()) { l.state = UNLOCKED; } return; case LOCKED_FOR_READ_WRITE: readers--; l.state = LOCKED_FOR_WRITE; return; } } void LockServer::releaseForWrite(const string &lock, uint64_t holder) { if (locks.find(lock) == locks.end()) { return; } Lock &l = locks[lock]; if (l.holders.count(holder) == 0) { Warning("[%ld] Releasing unheld write lock: %s", holder, lock.c_str()); return; } switch (l.state) { case UNLOCKED: case LOCKED_FOR_READ: return; case LOCKED_FOR_WRITE: writers--; l.holders.erase(holder); ASSERT(l.holders.size() == 0); l.state = UNLOCKED; return; case LOCKED_FOR_READ_WRITE: writers--; l.state = LOCKED_FOR_READ; ASSERT(l.holders.size() == 1); return; } }
[ "iyzhang@cs.washington.edu" ]
iyzhang@cs.washington.edu
6b965226713b7686cbe50896a87a12f023725d16
9da42e04bdaebdf0193a78749a80c4e7bf76a6cc
/third_party/gecko-2/win32/include/nsIXTFPrivate.h
904b1a4dc23a2fe48db4ae018fb5170134c0fc59
[ "Apache-2.0" ]
permissive
bwp/SeleniumWebDriver
9d49e6069881845e9c23fb5211a7e1b8959e2dcf
58221fbe59fcbbde9d9a033a95d45d576b422747
refs/heads/master
2021-01-22T21:32:50.541163
2012-11-09T16:19:48
2012-11-09T16:19:48
6,602,097
1
0
null
null
null
null
UTF-8
C++
false
false
2,375
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/content/xtf/public/nsIXTFPrivate.idl */ #ifndef __gen_nsIXTFPrivate_h__ #define __gen_nsIXTFPrivate_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIXTFPrivate */ #define NS_IXTFPRIVATE_IID_STR "13ef3d54-1dd1-4a5c-a8d5-a04a327fb9b6" #define NS_IXTFPRIVATE_IID \ {0x13ef3d54, 0x1dd1, 0x4a5c, \ { 0xa8, 0xd5, 0xa0, 0x4a, 0x32, 0x7f, 0xb9, 0xb6 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIXTFPrivate : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXTFPRIVATE_IID) /* readonly attribute nsISupports inner; */ NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIXTFPrivate, NS_IXTFPRIVATE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIXTFPRIVATE \ NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIXTFPRIVATE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) { return _to GetInner(aInner); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIXTFPRIVATE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetInner(nsISupports **aInner) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInner(aInner); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsXTFPrivate : public nsIXTFPrivate { public: NS_DECL_ISUPPORTS NS_DECL_NSIXTFPRIVATE nsXTFPrivate(); private: ~nsXTFPrivate(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsXTFPrivate, nsIXTFPrivate) nsXTFPrivate::nsXTFPrivate() { /* member initializers and constructor code */ } nsXTFPrivate::~nsXTFPrivate() { /* destructor code */ } /* readonly attribute nsISupports inner; */ NS_IMETHODIMP nsXTFPrivate::GetInner(nsISupports **aInner) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIXTFPrivate_h__ */
[ "haleokekahuna@gmail.com" ]
haleokekahuna@gmail.com
243b62579df517e66e0eb656e0072fb2c37f62a0
832fdaee7ab49f6bc18f005173695fd926e38f24
/FindDriver.cpp
e136304889060dc6b9bd59367f75fec42207d669
[ "Apache-2.0", "MIT" ]
permissive
ChristophHaag/OSVR-Vive
8012e7483d2ef82bda640ebb06b5e92498d9012b
9a0dea88968f6d02b0ec65c8064fe4d615aad266
refs/heads/master
2021-01-11T14:18:48.363196
2016-12-02T17:29:43
2016-12-02T17:29:43
81,337,676
1
0
null
2017-02-08T14:22:59
2017-02-08T14:22:59
null
UTF-8
C++
false
false
9,998
cpp
/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Razer Inc. // // 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. // Internal Includes #include "FindDriver.h" // Library/third-party includes #include <boost/iostreams/stream.hpp> #include <json/reader.h> #include <json/value.h> #include <osvr/Util/Finally.h> #include <osvr/Util/PlatformConfig.h> // Standard includes #include <fstream> // std::ifstream #include <iostream> #include <limits.h> #include <vector> #if defined(OSVR_USING_FILESYSTEM_HEADER) #include <filesystem> #elif defined(OSVR_USING_BOOST_FILESYSTEM) #include <boost/filesystem.hpp> #endif #if defined(OSVR_WINDOWS) #include <shlobj.h> #else #include <cstdlib> // for getenv #endif #undef VIVELOADER_VERBOSE using osvr::util::finally; namespace osvr { namespace vive { #if defined(OSVR_WINDOWS) static const auto PLATFORM_DIRNAME_BASE = "win"; static const auto DRIVER_EXTENSION = ".dll"; static const auto TOOL_EXTENSION = ".exe"; static const auto PATH_SEP = "\\"; #elif defined(OSVR_MACOSX) /// @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X static const auto PLATFORM_DIRNAME_BASE = "osx"; static const auto DRIVER_EXTENSION = ".dylib"; static const auto TOOL_EXTENSION = ""; static const auto PATH_SEP = "/"; #elif defined(OSVR_LINUX) static const auto PLATFORM_DIRNAME_BASE = "linux"; static const auto DRIVER_EXTENSION = ".so"; static const auto TOOL_EXTENSION = ""; static const auto PATH_SEP = "/"; #else #error "Sorry, Valve does not produce a SteamVR runtime for your platform." #endif #if defined(OSVR_USING_FILESYSTEM_TR2) using std::tr2::sys::path; using std::tr2::sys::wpath; using std::tr2::sys::exists; #elif defined(OSVR_USING_FILESYSTEM_EXPERIMENTAL) using std::experimental::filesystem::path; #ifdef _WIN32 /// Some Windows functions deal in wide strings, easier to just let it cope /// with it. using wpath = path; #endif using std::experimental::filesystem::exists; #elif defined(OSVR_USING_BOOST_FILESYSTEM) using boost::filesystem::path; using boost::filesystem::exists; #endif #ifdef OSVR_MACOSX inline std::string getPlatformBitSuffix() { // they use universal binaries but stick them in "32" return "32"; } #else inline std::string getPlatformBitSuffix() { return std::to_string(sizeof(void *) * CHAR_BIT); } #endif inline std::string getPlatformDirname() { return PLATFORM_DIRNAME_BASE + getPlatformBitSuffix(); } inline void parsePathConfigFile(std::istream &is, Json::Value &ret) { Json::Reader reader; if (!reader.parse(is, ret)) { std::cerr << "Error parsing file containing path configuration - " "have you run SteamVR yet?" << std::endl; std::cerr << reader.getFormattedErrorMessages() << std::endl; } } #if defined(OSVR_WINDOWS) inline Json::Value getPathConfig() { PWSTR outString = nullptr; Json::Value ret; // It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+ // stuff too. auto hr = SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString); if (!SUCCEEDED(hr)) { std::cerr << "Could not get local app data directory!" << std::endl; return ret; } // Free the string returned when we're all done. auto freeString = [&] { CoTaskMemFree(outString); }; // Build the path to the file. auto vrPaths = wpath(outString) / wpath(L"openvr") / wpath(L"openvrpaths.vrpath"); std::ifstream is(vrPaths.string()); if (!is) { std::wcerr << L"Could not open file containing path configuration " L"- have you run SteamVR yet? " << vrPaths << L"\n"; return ret; } parsePathConfigFile(is, ret); return ret; } #elif defined(OSVR_MACOSX) || defined(OSVR_LINUX) inline Json::Value getPathConfig() { auto home = std::getenv("HOME"); path homePath = (nullptr == home ? path{"~"} /*that's weird, should have been in environment...*/ : path{home}); auto vrPaths = homePath / path{".openvr"} / path{"openvrpaths.vrpath"}; std::ifstream is(vrPaths.string()); Json::Value ret; if (!is) { std::cerr << "Could not open file containing path configuration " "- have you run SteamVR yet? " << vrPaths << "\n"; return ret; } parsePathConfigFile(is, ret); return ret; } #endif inline std::vector<std::string> getSteamVRRoots(Json::Value const &json) { std::vector<std::string> ret; auto &runtimes = json["runtime"]; if (!runtimes.isArray()) { return ret; } for (auto &runtime : runtimes) { ret.emplace_back(runtime.asString()); } return ret; } inline std::vector<std::string> getSteamVRRoots() { return getSteamVRRoots(getPathConfig()); } inline void computeDriverRootAndFilePath(DriverLocationInfo &info, std::string const &driver) { auto p = path{info.steamVrRoot}; p /= "drivers"; p /= driver; p /= "bin"; p /= getPlatformDirname(); info.driverRoot = p.string(); p /= ("driver_" + driver + DRIVER_EXTENSION); info.driverFile = p.string(); } /// Underlying implementation - hand it the preloaded json. inline DriverLocationInfo findDriver(Json::Value const &json, std::string const &driver) { DriverLocationInfo info; auto &runtimes = json["runtime"]; if (!runtimes.isArray()) { return info; } for (auto &root : runtimes) { info.steamVrRoot = root.asString(); info.driverName = driver; computeDriverRootAndFilePath(info, driver); #ifdef VIVELOADER_VERBOSE std::cout << "Will try to load driver from:\n" << info.driverFile << std::endl; if (exists(path{info.driverRoot})) { std::cout << "Driver root exists" << std::endl; } if (exists(path{info.driverFile})) { std::cout << "Driver file exists" << std::endl; } #endif if (exists(path{info.driverRoot}) && exists(path{info.driverFile})) { info.found = true; return info; } } info = DriverLocationInfo{}; return info; } DriverLocationInfo findDriver(std::string const &driver) { return findDriver(getPathConfig(), driver); } std::string getToolLocation(std::string const &toolName, std::string const &steamVrRoot) { std::vector<std::string> searchPath; if (!steamVrRoot.empty()) { searchPath = {steamVrRoot}; } else { searchPath = getSteamVRRoots(); } for (auto &root : searchPath) { auto p = path{root}; p /= "bin"; p /= getPlatformDirname(); p /= (toolName + TOOL_EXTENSION); if (exists(p)) { return p.string(); } } return std::string{}; } /// Underlying implementation - hand it the preloaded json. inline ConfigDirs findConfigDirs(Json::Value const &json, std::string const &driver) { ConfigDirs ret; auto const &configLocations = json["config"]; if (!configLocations.isArray()) { return ret; } for (auto &configDir : configLocations) { auto configPath = path{configDir.asString()}; if (!exists(configPath)) { continue; } ret.rootConfigDir = configPath.string(); ret.driverConfigDir = (configPath / path{driver}).string(); ret.valid = true; return ret; } ret = ConfigDirs{}; return ret; } ConfigDirs findConfigDirs(std::string const & /*steamVrRoot*/, std::string const &driver) { return findConfigDirs(getPathConfig(), driver); } LocationInfo findLocationInfoForDriver(std::string const &driver) { auto json = getPathConfig(); LocationInfo ret; auto config = findConfigDirs(json, driver); if (config.valid) { ret.configFound = true; ret.rootConfigDir = config.rootConfigDir; ret.driverConfigDir = config.driverConfigDir; } auto driverLoc = findDriver(json, driver); if (driverLoc.found) { ret.driverFound = true; ret.steamVrRoot = driverLoc.steamVrRoot; ret.driverRoot = driverLoc.driverRoot; ret.driverName = driverLoc.driverName; ret.driverFile = driverLoc.driverFile; } ret.found = (driverLoc.found && config.valid); return ret; } } // namespace vive } // namespace osvr
[ "ryan@sensics.com" ]
ryan@sensics.com
50e7b9590b4f649cc54a4748256a23d44d6e6704
d9f9200a941640799ee39f7ffdd0d3455443ba4b
/Raytra1.5/Point.cc
18ed72cdd90c0c14904bf441fd4776d034233154
[]
no_license
paoptu023/COMS4160
058fb80f3319c85ada56d9024b409147bdd2770a
d7c43fadd6630fcad8e5c059268e28ab6fdc713b
refs/heads/master
2021-06-07T16:23:58.424551
2016-11-14T20:30:16
2016-11-14T20:30:16
52,846,831
1
0
null
null
null
null
UTF-8
C++
false
false
1,082
cc
// // Point.cc // Raytra // // Created by Qi Wang on 2/6/16. // Copyright © 2016 Wang Qi. All rights reserved. // #include "Point.h" Point & Point::operator =(const Point &p){ _xyz[0] = p[0]; _xyz[1] = p[1]; _xyz[2] = p[2]; return *this; } Point Point::operator +(const Vector &v) const{ return Point(_xyz[0] + v[0], _xyz[1] + v[1], _xyz[2] + v[2]); } Point Point::operator +(const Point &p) const{ return Point(_xyz[0] + p[0], _xyz[1] + p[1], _xyz[2] + p[2]); } Point & Point::operator +=(const Vector &v){ _xyz[0] += v[0]; _xyz[1] += v[1]; _xyz[2] += v[2]; return *this; } Point Point::operator -(const Vector &v) const{ return move(Point(_xyz[0] - v[0], _xyz[1] - v[1], _xyz[2] - v[2])); } Point & Point::operator -=(const Vector &v){ _xyz[0] -= v[0]; _xyz[1] -= v[1]; _xyz[2] -= v[2]; return *this; } Point Point::operator /(const int k) const{ return Point(_xyz[0] / k, _xyz[1] / k, _xyz[2] / k); } void Point::print(){ cout << "Point: " << _xyz[0] << " " << _xyz[1] << " " << _xyz[2] << endl; }
[ "wang.qi@columbia.edu" ]
wang.qi@columbia.edu
3e0161781b92590d777bccd47459db2cd7f3d0a0
ceff13ff947c4850b6c7814ca486440215157873
/applications/Pasha/PreGraph/AlshaComms.cpp
7771c06c9fc8e98bf11c66dab55421f4a1f82475
[]
no_license
LingxiWu/DBGAcc
b2718be17fb1c39bc6ff3e2390a2c9507aac91d3
6a235b0fcf7926c4d3f5dadea4c66a325c0f023b
refs/heads/master
2023-03-15T20:01:42.439470
2021-02-08T09:57:45
2021-02-08T09:57:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,641
cpp
#include "AlshaComms.h" #include "AlshaParams.h" #include <mpi.h> MPI_Request AlshaComms::msgRequest = MPI_REQUEST_NULL; uint8_t* AlshaComms::RX_BUFFER = NULL; NumType AlshaComms::txPackets = 0; NumType AlshaComms::rxPackets = 0; void AlshaComms::init() { RX_BUFFER = (uint8_t*)AlshaUtils::memAlloc(RX_BUFFER_SIZE); } void AlshaComms::destroy() { AlshaUtils::memFree(RX_BUFFER); } void AlshaComms::startup() { assert(msgRequest == MPI_REQUEST_NULL); MPI_Irecv(RX_BUFFER, RX_BUFFER_SIZE, MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &msgRequest); } void AlshaComms::sendCommand(int procId, uint32_t command, uint64_t descriptor, int tag) { if(procId < 0) return; AlshaMessageControl msg(command, descriptor); mpiSend(procId, &msg, tag); } void AlshaComms::bcastCommand(int root, uint32_t command, uint64_t descriptor, int tag) { if(root < 0 || AlshaParams::numProcs == 1) return; AlshaMessageControl msg(command, descriptor); //broadcast the command mpiBcast(root, &msg, tag); } void AlshaComms::sendMessage(int procId, AlshaMessage* msg, int tag) { if(procId < 0) return; AlshaUtils::memVerify(msg); mpiSend(procId, msg, tag); } void AlshaComms::mpiSend(int procId, AlshaMessage* msg, int tag) { if(procId < 0) return; unsigned int totalSize = msg->getTransmitSize(); uint8_t* buffer = (uint8_t*)AlshaUtils::memAlloc(totalSize); //serialize the message unsigned int offset = msg->serialize(buffer); assert(offset == totalSize); //send the message to the destination process MPI_Send(buffer, totalSize, MPI_BYTE, procId, tag, MPI_COMM_WORLD); AlshaUtils::memFree(buffer); txPackets++; } void AlshaComms::mpiBcast(int root, AlshaMessage* msg, int tag) { if(root < 0 || AlshaParams::numProcs == 1) return; unsigned int totalSize = msg->getTransmitSize(); uint8_t* buffer = (uint8_t*)AlshaUtils::memAlloc(totalSize); //serialize the message unsigned int offset = msg->serialize(buffer); assert(offset == totalSize); //broadcasting the message int reqIndex = 0; MPI_Request* requests = (MPI_Request*)AlshaUtils::memAlloc(sizeof(MPI_Request) * AlshaParams::numProcs); for(int procId = 0; procId < AlshaParams::numProcs; ++procId){ if(procId == root) continue; MPI_Send_init(buffer, totalSize, MPI_BYTE, procId, tag, MPI_COMM_WORLD, &requests[reqIndex]); ++reqIndex; } MPI_Startall(reqIndex, requests); MPI_Waitall(reqIndex, requests, MPI_STATUSES_IGNORE); txPackets += reqIndex; AlshaUtils::memFree(requests); AlshaUtils::memFree(buffer); } bool AlshaComms::checkCompletion() { //perform reduction NumType diff = txPackets - rxPackets; NumType sumDiff; MPI_Allreduce(&diff, &sumDiff, 1, MPI_LONG_LONG, MPI_SUM, MPI_COMM_WORLD); if(sumDiff == 0){ txPackets = rxPackets = 0; } //cout << txPackets << " " << rxPackets << " " << sumDiff << endl; return (sumDiff == 0); } bool AlshaComms::checkMessage() { int flag; MPI_Status status; MPI_Request_get_status(msgRequest, &flag, &status); if(!flag){ MPI_Request_get_status(msgRequest, &flag, &status); } return (flag == 1) ? true : false; } bool AlshaComms::recvMessage(uint8_t*& buffer, unsigned int& bufferSize, MPI_Status& status) { int flag; MPI_Test(&msgRequest, &flag, &status); assert(flag == 1); int size; MPI_Get_count(&status, MPI_BYTE, &size); bufferSize = size; buffer = (uint8_t*)AlshaUtils::memAlloc(bufferSize); memcpy(buffer, RX_BUFFER, bufferSize); assert(msgRequest == MPI_REQUEST_NULL); MPI_Irecv(RX_BUFFER, RX_BUFFER_SIZE, MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &msgRequest); rxPackets++; return true; }
[ "mul023@ucsd.edu" ]
mul023@ucsd.edu
ee30ec8ec6e7894c16fc218910a88d717859e4de
db84bf6382c21920c3649b184f20ea48f54c3048
/legendgeometry/legendgeometry/LGND_FiberCore.hh
05032c4875c39c79f5e6c5419413b670fb970f39
[]
no_license
liebercanis/MaGeLAr
85c540e3b4c5a48edea9bc0520c9d1a1dcbae73c
aa30b01f3c9c0f5de0f040d05681d358860a31b3
refs/heads/master
2020-09-20T12:48:38.106634
2020-03-06T18:43:19
2020-03-06T18:43:19
224,483,424
2
0
null
null
null
null
UTF-8
C++
false
false
3,240
hh
//---------------------------------------------------------------------------// //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// // // // // // MaGe Simulation // // // // This code implementation is the intellectual property of the // // MAJORANA and Gerda Collaborations. It is based on Geant4, an // // intellectual property of the RD44 GEANT4 collaboration. // // // // ********************* // // // // Neither the authors of this software system, nor their employing // // institutes, nor the agencies providing financial support for this // // work make any representation or warranty, express or implied, // // regarding this software system or assume any liability for its use. // // By copying, distributing or modifying the Program (or any work based // // on on the Program) you indicate your acceptance of this statement, // // and all its terms. // // // //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// //---------------------------------------------------------------------------// /** * $Id: MGheadertemplate.hh,v 1.1 2004-12-09 08:58:35 pandola Exp $ * * CLASS DECLARATION: LGND_FiberCore.hh * *---------------------------------------------------------------------------// * * DESCRIPTION: * */ // Begin description of class here /** * *Geometry code for the string tie rods * * */ // End class description // /** * SPECIAL NOTES: * */ // // --------------------------------------------------------------------------// /** * AUTHOR: Neil McFadden * CONTACT: nmcfadde@unm.edu * FIRST SUBMISSION: * * REVISION: * */ // --------------------------------------------------------------------------// #ifndef _LGND_FIBERCORE_HH #define _LGND_FIBERCORE_HH //---------------------------------------------------------------------------// #include "legendgeometry/LGND_Part.hh" class G4LogicalVolume; using namespace std; //---------------------------------------------------------------------------// class LGND_FiberCore: public LGND_Part { public: LGND_FiberCore(G4String, G4String, G4double,G4String); LGND_FiberCore(G4String, G4String, G4double); LGND_FiberCore(G4String, G4String); LGND_FiberCore(const LGND_FiberCore &); ~LGND_FiberCore(); G4LogicalVolume* BuildLogicalVolume(); void SetLength(G4double length) {fLength = length*CLHEP::mm;} G4String GetShape(){return fShape;} G4double GetRadius(){return fRadius;} private: G4double fLength; G4String fShape = "square"; G4double fRadius; }; // #endif
[ "mgold@unm.edu" ]
mgold@unm.edu
4cc31b4a61195b1fef68b1138231bb9aea2c31da
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14174/function14174_schedule_9/function14174_schedule_9.cpp
18605de3c16a602760b0adfe18b6c023619ce9c3
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,477
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14174_schedule_9"); constant c0("c0", 256), c1("c1", 1024), c2("c2", 256); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"); input input00("input00", {i0, i1}, p_int32); input input01("input01", {i0, i2}, p_int32); input input02("input02", {i2}, p_int32); input input03("input03", {i1, i2}, p_int32); input input04("input04", {i1, i2}, p_int32); computation comp0("comp0", {i0, i1, i2}, input00(i0, i1) * input01(i0, i2) - input02(i2) + input03(i1, i2) * input04(i1, i2)); comp0.tile(i1, i2, 64, 64, i01, i02, i03, i04); comp0.parallelize(i0); buffer buf00("buf00", {256, 1024}, p_int32, a_input); buffer buf01("buf01", {256, 256}, p_int32, a_input); buffer buf02("buf02", {256}, p_int32, a_input); buffer buf03("buf03", {1024, 256}, p_int32, a_input); buffer buf04("buf04", {1024, 256}, p_int32, a_input); buffer buf0("buf0", {256, 1024, 256}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); input02.store_in(&buf02); input03.store_in(&buf03); input04.store_in(&buf04); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf0}, "../data/programs/function14174/function14174_schedule_9/function14174_schedule_9.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
657aa7bdee9d5bac7e5a324c843d029f4d58bed5
762faf2ecadaa88d7b1f4c24ac5243651711628d
/PDFPageItemDelegate.cpp
d0b63afe2488b6822df22b3a9c6111665454ea87
[]
no_license
TheRikke/pdfmart
2dbf2801a0a9639c669f5c0260867a67f0172572
9bad9ae9a09af7746dd2e64faf549ee31228fe21
refs/heads/master
2020-04-02T04:44:12.272926
2016-06-22T20:17:19
2016-06-22T20:17:19
61,746,519
1
0
null
null
null
null
UTF-8
C++
false
false
2,436
cpp
#include "PDFPageItemDelegate.h" #include "PageList.h" #include <poppler-qt5.h> #include <QPainter> #include <QCache> #include <QScreen> #include <QApplication> #include <QDebug> Q_DECLARE_METATYPE(Poppler::Document*) namespace { const int MAX_CACHED_IMAGES = 500; } PDFPageItemDelegate::PDFPageItemDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } void PDFPageItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { static QCache< ImageKey, QImage > imageCache(MAX_CACHED_IMAGES); int documentNumber = index.row(); int pageNumber = index.column(); const QAbstractItemModel *itemModel = index.model(); QVariant data = itemModel->data(index, Qt::UserRole); if(data.isValid()) { QSize position(data.toSize()); documentNumber = position.width(); pageNumber = position.height(); } QVector<Poppler::Document*> documents = itemModel->property("SourceDocuments").value< QVector<Poppler::Document*> >(); qDebug("Paint doc %d page %d into %d, %d (row, column)", documentNumber, pageNumber, index.row(), index.column()); if(documentNumber < documents.size()) { Poppler::Document *document = documents.at(documentNumber); if(pageNumber < document->numPages()) { ImageKey key(document, pageNumber); QImage *newPage = imageCache.object(key); if(!newPage) { QScreen* screen = QApplication::screens().first(); Poppler::Page *page = document->page(pageNumber); newPage = new QImage(page->renderToImage(static_cast<const int>(screen->logicalDotsPerInchX()), static_cast<const int>(screen->logicalDotsPerInchY()))); qDebug("Cache miss for page %d in doc %p (DPI %f, W: %d, H: %d)", pageNumber, document, screen->logicalDotsPerInch(), page->pageSize().width(), page->pageSize().height()); delete page; imageCache.insert(key, newPage); } painter->drawImage(option.rect, *newPage); } } } QSize PDFPageItemDelegate::sizeHint(const QStyleOptionViewItem &/*option*/, const QModelIndex &index) const { QSize result; if(index.isValid()) { result = index.model()->property("SizeHint").value< QSize>(); qDebug() << "Size hint " << result; } else { qDebug() << "Invalid index"; } return result; }
[ "rikky@web.de" ]
rikky@web.de
d2b60ba08eb365f12a4789ea8f6b3a006f33653c
e7d860d7596459166c16cfe36ec28c2d6fc1f263
/src/multi_threaded_session.cpp
daf9201f1e23f69ae2bd975558253b0d86f5e658
[ "Apache-2.0" ]
permissive
staticlibs/staticlib_http
5aa47ff6b2d687691d7dac7b0a51edb17a285c24
254120a142d3aa4c669a62a21b7d13949cf1814d
refs/heads/master
2023-03-10T06:31:37.066617
2021-03-03T17:55:36
2021-03-03T17:55:36
46,565,017
1
0
null
null
null
null
UTF-8
C++
false
false
9,184
cpp
/* * Copyright 2017, alex at staticlibs.net * * 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. */ /* * File: multi_threaded_session.cpp * Author: alex * * Created on March 25, 2017, 6:20 PM */ #include "staticlib/http/multi_threaded_session.hpp" #include <chrono> #include <condition_variable> #include <map> #include <memory> #include <mutex> #include <thread> #include "curl/curl.h" #include "staticlib/concurrent.hpp" #include "staticlib/io.hpp" #include "staticlib/pimpl/forward_macros.hpp" #include "session_impl.hpp" #include "curl_headers.hpp" #include "curl_utils.hpp" #include "resource_params.hpp" #include "multi_threaded_resource.hpp" #include "running_request_pipe.hpp" #include "running_request.hpp" namespace staticlib { namespace http { class multi_threaded_session::impl : public session::impl { sl::concurrent::mpmc_blocking_queue<request_ticket> tickets; std::atomic<bool> new_tickets_arrived; std::map<int64_t, std::unique_ptr<running_request>> requests; std::shared_ptr<sl::concurrent::condition_latch> pause_latch; std::thread worker; std::atomic<bool> running; public: impl(session_options opts) : session::impl(opts), tickets(opts.requests_queue_max_size), new_tickets_arrived(false), pause_latch(std::make_shared<sl::concurrent::condition_latch>([this] { return this->check_pause_condition(); })), running(true) { worker = std::thread([this] { this->worker_proc(); }); } ~impl() STATICLIB_NOEXCEPT { running.store(false, std::memory_order_release); pause_latch->notify_one(); tickets.unblock(); worker.join(); } resource open_url(multi_threaded_session&, const std::string& url, std::unique_ptr<std::istream> post_data, request_options opts) { if ("" == opts.method) { opts.method = "POST"; } // note: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63736 auto pipe = std::make_shared<running_request_pipe>(opts, pause_latch); auto enqueued = tickets.emplace(url, opts, std::move(post_data), pipe); if (!enqueued) throw http_exception(TRACEMSG( "Requests queue is full, size: [" + sl::support::to_string(tickets.size()) + "]")); new_tickets_arrived.exchange(true, std::memory_order_acq_rel); pause_latch->notify_one(); auto params = resource_params(url, std::move(pipe)); return multi_threaded_resource(increment_resource_id(), opts, std::move(params)); } // not exposed bool check_pause_condition() { // unpause when possible size_t num_paused = unpause_enqueued_requests(); // check more tickets if (new_tickets_arrived.load(std::memory_order_acquire)) { new_tickets_arrived.store(false, std::memory_order_release); tickets.poll([this](request_ticket && ti) { this->enqueue_request(std::move(ti)); }); } if (requests.size() > num_paused) { // consumers are active, let's proceed return true; } // check we are still running return !running.load(std::memory_order_acquire); } private: void worker_proc() { while (running.load(std::memory_order_acquire)) { // wait on queue request_ticket ticket; auto got_ticket = tickets.take(ticket); if (!got_ticket) { // destruction in progress break; } enqueue_request(std::move(ticket)); // spin while has active transfers while (requests.size() > 0) { // receive data bool perform_success = curl_perform(); if (!perform_success) { break; } // pop completed bool pop_success = pop_completed_requests(); if (!pop_success) { break; } // check there are running requests if (0 == requests.size()) break; // wait if all requests paused pause_latch->await(); } } requests.clear(); } bool curl_perform() { // timeout long timeo = -1; CURLMcode err_timeout = curl_multi_timeout(handle.get(), std::addressof(timeo)); if (check_and_abort_on_multi_error(err_timeout)) { return false; } struct timeval timeout = create_timeout_struct(timeo, this->options.socket_select_max_timeout_millis); // fdset fd_set fdread = create_fd(); fd_set fdwrite = create_fd(); fd_set fdexcep = create_fd(); int maxfd = -1; CURLMcode err_fdset = curl_multi_fdset(handle.get(), std::addressof(fdread), std::addressof(fdwrite), std::addressof(fdexcep), std::addressof(maxfd)); if (check_and_abort_on_multi_error(err_fdset)) { return false; } // wait or select int err_select = 0; if (maxfd == -1) { std::this_thread::sleep_for(std::chrono::milliseconds(this->options.fdset_timeout_millis)); } else { err_select = select(maxfd + 1, std::addressof(fdread), std::addressof(fdwrite), std::addressof(fdexcep), std::addressof(timeout)); } // do perform if no select error int active = -1; if (-1 != err_select) { CURLMcode err_perform = curl_multi_perform(handle.get(), std::addressof(active)); if (check_and_abort_on_multi_error(err_perform)) { return false; } } return true; } bool pop_completed_requests() { for (;;) { int tmp = -1; CURLMsg* cm = curl_multi_info_read(handle.get(), std::addressof(tmp)); if (nullptr == cm) { // all requests in queue inspected break; } int64_t req_key = reinterpret_cast<int64_t> (cm->easy_handle); auto it = requests.find(req_key); if (requests.end() == it) { abort_running_on_multi_error(TRACEMSG("System error: inconsistent queue state, aborting")); return false; } running_request& req = *it->second; if (CURLMSG_DONE == cm->msg) { CURLcode result = cm->data.result; if (req.get_options().abort_on_connect_error && CURLE_OK != result) { req.append_error(curl_easy_strerror(result)); } requests.erase(req_key); } } return true; } size_t unpause_enqueued_requests() { size_t num_paused = 0; for (auto& pa : requests) { running_request& req = *pa.second; if (req.is_paused()) { if (!req.data_queue_is_full()) { req.unpause(); } else { num_paused += 1; } } } return num_paused; } void enqueue_request(request_ticket&& ticket) { // local copy auto pipe = ticket.pipe; try { auto req = std::unique_ptr<running_request>(new running_request(handle.get(), std::move(ticket))); auto ha = req->easy_handle(); auto pa = std::make_pair(reinterpret_cast<int64_t> (ha), std::move(req)); requests.insert(std::move(pa)); } catch (const std::exception& e) { // these two lines are normally called // on requests queue pop, but here // enqueue itself failed pipe->append_error(TRACEMSG(e.what())); pipe->shutdown(); } } bool check_and_abort_on_multi_error(CURLMcode code) { if (CURLM_OK == code) return false; abort_running_on_multi_error(TRACEMSG("cURL engine error, transfer aborted," + " code: [" + curl_multi_strerror(code) + "]")); return true; } void abort_running_on_multi_error(const std::string& error) { for (auto& pa : requests) { running_request& re = *pa.second; re.append_error(error); } requests.clear(); } }; PIMPL_FORWARD_CONSTRUCTOR(multi_threaded_session, (session_options), (), http_exception) PIMPL_FORWARD_METHOD(multi_threaded_session, resource, open_url, (const std::string&)(std::unique_ptr<std::istream>)(request_options), (), http_exception) } // namespace }
[ "alex@staticlibs.net" ]
alex@staticlibs.net
b4a9ab2cab1659c902bd5b28141abf3050988ef2
3f28d1318412b850711ae4eded21319180a6b502
/LinkedList/LinkedList.h
a4b32c3d577e467b0e5734b9c7aee36e6698dcc7
[ "MIT" ]
permissive
thisisyoussef/LinkedList
f79cd3a26458040ed4b0478a9ee72a106ec11004
f4639fd437a3484891babb5d3af59d1185cad77e
refs/heads/master
2023-06-10T18:24:46.806841
2023-05-27T12:56:46
2023-05-27T12:56:46
365,536,086
0
0
null
null
null
null
UTF-8
C++
false
false
10,381
h
#include <vector> #include <algorithm> //#include "leaker.h" using namespace std; template<typename T> class LinkedList { public: LinkedList(); LinkedList(const LinkedList<T>& list); ~LinkedList(); LinkedList<T> operator=(const LinkedList<T> j); struct Node { T data; Node* next = nullptr; Node* prev = nullptr; Node* searchNext(unsigned int index) { if (index == 0) { return this; } else { index--; return next->searchNext(index); } } }; Node* deletedNode = nullptr; Node* n = nullptr; Node* t = nullptr; Node* head = nullptr; Node* tail = nullptr; Node* tp = nullptr; vector<Node*> deletedData; bool FirstAdd = true; bool operator==(const LinkedList<T> j) { Node* x = head; Node* y = j.head; while (x != nullptr) { if (x->data != y->data) { return false; } x = x->next; y = y->next; }return true; } unsigned int _Nodecount = 0; void InsertBefore(Node* node, const T& data) { if (node == head) { AddHead(data); } else { n = new Node; n->data = data; n->next = node; n->prev = node->prev; n->prev->next = n; node->prev = n; _Nodecount++; } } void InsertAfter(Node* node, const T& data) { if (node == tail) { AddTail(data); } else { n = new Node; n->data = data; n->next = node->next; n->prev = node; n->next->prev = n; node->next = n; _Nodecount++; } } void InsertAt(const T& data, unsigned int index) { if (index == 0) { AddHead(data); } else if (index == (_Nodecount)) { AddTail(data); } else { InsertAfter(GetNode(index - 1), data); } } void Clear() { Node* temp = nullptr; for (unsigned int i = 0; i < _Nodecount; i++) { // cout << "deleting" << endl; temp = head; if (head != nullptr) { if (head->next != nullptr) { // cout << "not null" << endl; head = head->next; delete temp; } else { delete head; } } //cout << "delete successful" << endl; } for (Node* p : deletedData) { delete p; } head = nullptr; tail = nullptr; FirstAdd = true; _Nodecount = 0; //cout << "delete successful" << endl; } void AddHead(const T& data) { if (_Nodecount - deletedData.size() == 0) { Clear(); } n = new Node; n->data = data; if (FirstAdd) { head = n; t = n; tail = n; tp = tail; FirstAdd = false; } else { head = n; t->prev = n; head->next = t; t = n; } _Nodecount++; } bool RemoveHead() { if (head == nullptr) { return false; } if (head->next != nullptr) { head->next->prev = nullptr; } deletedData.push_back(head); head = head->next; return true; } bool RemoveTail() { if (tail == nullptr) { return false; } if (tail->prev != nullptr) { tail->prev->next = nullptr; } deletedData.push_back(tail); tail = tail->prev; return true; } bool RemoveAt(unsigned int index) { if (index > _Nodecount) { return false; } if (index == 0) { return RemoveHead(); } else if (index == _Nodecount) { return RemoveTail(); } else { deletedNode = GetNode(index); if (deletedNode != nullptr) { if (deletedNode->next != nullptr) { deletedNode->next->prev = deletedNode->prev; } if (deletedNode->prev != nullptr) { deletedNode->prev->next = deletedNode->next; } deletedData.push_back(deletedNode); return true; } } return false; } unsigned int Remove(const T& data) { unsigned int index = 0; unsigned int timesremoved = 0; Node* x = head; while (x != nullptr) { if ((x->data) == data) { RemoveAt(index); timesremoved++; index--; } x = x->next; index++; } return timesremoved; } void AddTail(const T& data) { if (_Nodecount - deletedData.size() == 0) { Clear(); } n = new Node; n->data = data; if (FirstAdd) { tail = n; head = n; tp = n; t = head; FirstAdd = false; } else { tail = n; tp->next = n; tail->prev = tp; tp = n; } _Nodecount++; } void AddNodesHead(const T* data, unsigned int count) { for (unsigned int i = 0; i < count; i++) { // cout << "in loop" << i;; AddHead(data[count - i - 1]); } // cout << "done loop"; } void AddNodesTail(const T* data, unsigned int count) { for (unsigned int i = 0; i < count; i++) { AddTail(data[i]); } } unsigned int NodeCount() { if (deletedData.size() > _Nodecount) { return 0; } else { return (_Nodecount - deletedData.size()); }; } unsigned int NodeCount() const { return _Nodecount; } void PrintForward() { Node* x = head; while (x != nullptr) { cout << x->data << endl; x = x->next; } } void PrintReverse() { Node* x = tail; while (x != nullptr) { cout << x->data << endl; x = x->prev; } } void PrintForwardRecursive(const Node* node) { if (node != nullptr) { cout << node->data << endl; PrintForwardRecursive(node->next); } } void PrintReverseRecursive(const Node* node) { if (node != nullptr) { cout << node->data << endl; PrintReverseRecursive(node->prev); } } void FindAll(vector<Node*>& outData, const T& value) const { Node* x = head; while (x != nullptr) { if ((x->data) == value) { outData.push_back(x); } x = x->next; } } Node* Head() { return head; } const Node* Head() const { return head; } Node* Tail() { return tail; } const Node* Tail() const { return tail; } const Node* GetNode(unsigned int index) const { if (index >= NodeCount()) { throw std::out_of_range("ArrayList<X>::at() : index is out of range"); } else { if (index == 0) { return head; } if (index == ((NodeCount() - 1))) { return tail; } return head->searchNext(index); } } Node* GetNode(unsigned int index) { if (index >= NodeCount()) { throw std::out_of_range("ArrayList<X>::at() : index is out of range"); } else { if (index == 0) { return head; } if (index == ((NodeCount() - 1))) { return tail; } return head->searchNext(index); } } Node* Find(const T& data) { Node* x = head; while (x != nullptr) { //? if (x->data == data) { return x; } x = x->next; }return head; }; const Node* Find(const T& data) const { Node* x = head; while (x != nullptr) { //? if (x->data == data) { return x; } x = x->next; }return head; }; const T& operator[](unsigned int index) const { if (index >= NodeCount()) { throw std::out_of_range("ArrayList<X>::at() : index is out of range"); } return GetNode(index)->data; } T& operator[](unsigned int index) { if (index >= NodeCount()) { throw std::out_of_range("ArrayList<X>::at() : index is out of range"); } return GetNode(index)->data; } }; template <typename T>LinkedList<T>::LinkedList() {} template <typename T>LinkedList<T>::LinkedList(const LinkedList<T>& list) { this->_Nodecount = list._Nodecount; // cout << this->_Nodecount << endl; for (unsigned int i = 0; i < this->_Nodecount; i++) { // cout << "nodecount= "<< this->_Nodecount << " " << endl; //cout << "looped " << i << list.GetNode(i)->data; AddTail(list.GetNode(i)->data); this->_Nodecount--; } } template <typename T>LinkedList<T>::~LinkedList() { Node* temp = nullptr; for (unsigned int i = 0; i < NodeCount(); i++) { // cout << "deleting" << endl; temp = head; if (head != nullptr) { if (head->next != nullptr) { // cout << "not null" << endl; head = head->next; delete temp; } else { delete head; } } //cout << "delete successful" << endl; } for (Node* p : deletedData) { delete p; } } template <typename T> LinkedList<T> LinkedList<T>::operator= (const LinkedList<T> j) { Clear(); this->_Nodecount = j._Nodecount; for (unsigned int i = 0; i < this->_Nodecount; i++) { // cout << "nodecount= "<< this->_Nodecount << " " << endl; //cout << "looped " << i << list.GetNode(i)->data; AddTail(j.GetNode(i)->data); this->_Nodecount--; } return *this; }
[ "youssefiahmedis@gmail.com" ]
youssefiahmedis@gmail.com
aee9d0e6a6a14891f32c49edf315ed7636358ecb
de1c9eeec2bcc9b28a36b5c4f67fecf47fb0605c
/code/math/vector2d.h
c058f3255d3479ce810f6220ac32e53aca3d001a
[ "MIT" ]
permissive
danganea/software-rasterizer
77f2cd7521bdd3a18dbe7f79c907069c88d9901f
41123c223ed8a1567fc016dc0a009fa75415f4d4
refs/heads/master
2020-04-13T11:28:08.608090
2019-06-25T14:56:17
2019-06-25T14:56:17
163,175,530
0
0
null
null
null
null
UTF-8
C++
false
false
1,690
h
#pragma once #include <defs.h> namespace rast { template <typename T> class Vector2D { // TODO(DAN): Consistent usage of Vector<T> or just "Vector" public: T x, y; Vector2D() = default; Vector2D(T x, T y) : x(x), y(y) {} // Allow explicit vector conversions template <typename U> explicit Vector2D(const Vector2D<U> &other) : x(other.x), y(other.y) {} inline bool hasNaN() { return isNaN(x) || isNaN(y); } // Explicitness favored over code size. inline Vector2D operator-() { return Vector2D<T>(-x, -y); } inline Vector2D operator+() { return Vector2D<T>(x, y); } inline Vector2D &operator+=(const Vector2D &rhs) { x += rhx.x; y += rhx.y; return *this; } inline Vector2D operator+(const Vector2D &rhs) { return Vector2D(x + rhs.x, y + rhs.y); } inline Vector2D &operator-=(const Vector2D &rhs) { x -= rhs.x; y -= rhs.y; return *this; } inline Vector2D operator-(const Vector2D &rhs) { return Vector2D<T>(x - rhs.x, y - rhs.y); } template <typename U> inline Vector2D operator*(U f) { return Vector2D<T>(x * f, y * f); } // Note(Dan): Division operator not implemented for types not float/double. inline Vector2D operator/(float f) { assert(f != 0); T temp = 1.0f / f; return Vector2D<T>(x * temp, y * temp); } inline Vector2D operator/(double f) { assert(f != 0); T temp = 1.0 / f; return Vector2D<T>(x * temp, y * temp); } static inline Vector2D zero() { return Vector2D(0, 0); } static inline Vector2D one() { return Vector2D(1, 1); } }; using vec2f = Vector2D<float>; using ivec2 = Vector2D<int>; using uivec2 = Vector2D<uint32_t>; } // namespace rast
[ "obidan2@gmail.com" ]
obidan2@gmail.com
fd14049a3bcc1c8117a44df2dab23a089fc69bc7
a533d4198ee1237df55c94ee8ae3df4aefdc55bd
/dp/HeadFirstDesignPatterns/c_plusplus/Silver/Compound/Ducks/DuckSimulator/RubberDuck.hpp
5ec54f6a7a69a6be1d95a06255bec0ca74a841e8
[]
no_license
jufenghua596/book
c15aeb9b96e5fbb2e998286ef50bc5f569fa31a5
8b7d2db6b91268b3dcca39da4b067630768afdb6
refs/heads/master
2021-05-06T16:44:30.339828
2017-12-10T06:57:50
2017-12-10T06:57:50
113,723,089
1
0
null
null
null
null
UTF-8
C++
false
false
412
hpp
#ifndef _HFDP_CPP_COMPOUND_DUCKS_RUBBER_DUCK_HPP_ #define _HFDP_CPP_COMPOUND_DUCKS_RUBBER_DUCK_HPP_ #include "DuckSimulator.hpp" namespace HeadFirstDesignPatterns { namespace Compound { namespace Ducks { class RubberDuck : public Quackable { public: void quack() const { std::cout << "Squeak" << std::endl; } }; } // namespace Ducks } // namespace Compound } // namespace HeadFirstDesignPatterns #endif
[ "jufenghua596@163.com" ]
jufenghua596@163.com
791948409eb5e7422ba9386c26805763ca5d8f63
3009ccdaf935cacabba949b39d9582552292ff2e
/oving02/main.cpp
93382798f7f51e17860ec36303efb2ff5f6111a9
[]
no_license
Eliassoren/Cpp-for-Programmers
65e74f7a6be703e31733ef60555c81c9d61c267f
6302b36501b30a7cf196b40527deaea1bf4be80e
refs/heads/master
2021-01-01T04:08:56.440652
2017-12-18T10:15:17
2017-12-18T10:15:17
97,132,285
0
0
null
null
null
null
UTF-8
C++
false
false
2,144
cpp
#include <iostream> using namespace std; void oppg1(){ //Oppg a) int i = 3; int j = 5; int *p = &i; int *q = &j; cout << "i: " << i << " j: " << j << " *p: " << p << " *q: " << q << endl; cout << "&i: " << &i << " &j: " << &j << " &p: " << &p << " &q: " << &q << endl; //Oppg b) *p = 7; cout << "p: " << *p << endl; *q += 4; cout << "q: " << *q << endl; *q = *p+1; cout << "q: " << *q << endl; p = q; cout << "p: " << *p << endl; } void oppg4(){ /*/home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp: In function ‘void oppg4()’: /home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:27:8: error: ‘b’ declared as reference but not initialized int &b; ^ /home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:30:4: error: invalid type argument of unary ‘*’ (have ‘int’) *a = *b + *c; ^ /home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:30:9: error: invalid type argument of unary ‘*’ (have ‘int’) *a = *b + *c; ^ /home/elias/Documents/git/cpp/Cpp-for-Programmers/oving02/main.cpp:31:6: error: lvalue required as left operand of assignment &b = 2; ^*/ int a = 5; int &b = a; // Referansen må initieres. int *c = &b; a = b + *c; // a og b er ikke definert som pekere b = 2; //En referanse er allerede tildelt, og kan ikke endres på. } void oppg5(){ int num; int *ptr = &num; int &ref = num; num = 1; // Metode 1 cout << "Num1: " << num << endl; ++*ptr; // Metode 2 cout << "Num2: " << num << endl; ++ref; // Metode 3 cout << "Num3: " << num << endl; } int sum(int *arr, int elems){ int sum = 0; for(int i = 0; i < elems; ++i){ sum += arr[i]; } return sum; } void oppg6(){ int len = 20; int arr[len]; for(int i = 0; i < len;i++){ arr[i] = i; } // Oppg a) cout << "Sum a): " << sum(arr,10) << endl; // Oppg b) cout << "Sum b): " << sum(&arr[9],5) << endl; // Oppg c) cout << "Sum c) " << sum(&arr[14],5) << endl; } int main() { oppg1(); oppg4(); oppg5(); oppg6(); return 0; }
[ "eliassorr@gmail.com" ]
eliassorr@gmail.com
d0126e4ecd0646850fa80be8577a99beb21873bd
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_wsp_Pole_Orb_Light_b_functions.cpp
b9341d072315c9acc7dfbb20056eee338c7a6534
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
788
cpp
// Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_wsp_Pole_Orb_Light_b_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function wsp_Pole_Orb_Light_b.wsp_Pole_Orb_Light_b_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void Awsp_Pole_Orb_Light_b_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function wsp_Pole_Orb_Light_b.wsp_Pole_Orb_Light_b_C.UserConstructionScript"); Awsp_Pole_Orb_Light_b_C_UserConstructionScript_Params params; UObject::ProcessEvent(fn, &params); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
5faa232a523d15a4b1bd63705cacb6e1fc8d1593
792e697ba0f9c11ef10b7de81edb1161a5580cfb
/tools/clang/test/SemaCXX/cxx11-inheriting-ctors.cpp
39582660984b8a71d3450a8ee852af88491b2c92
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
opencor/llvmclang
9eb76cb6529b6a3aab2e6cd266ef9751b644f753
63b45a7928f2a8ff823db51648102ea4822b74a6
refs/heads/master
2023-08-26T04:52:56.472505
2022-11-02T04:35:46
2022-11-03T03:55:06
115,094,625
0
1
Apache-2.0
2021-08-12T22:29:21
2017-12-22T08:29:14
LLVM
UTF-8
C++
false
false
3,770
cpp
// RUN: %clang_cc1 -std=c++11 %s -verify namespace PR15757 { struct S { }; template<typename X, typename Y> struct T { template<typename A> T(X x, A &&a) {} template<typename A> explicit T(A &&a) noexcept(noexcept(T(X(), static_cast<A &&>(a)))) : T(X(), static_cast<A &&>(a)) {} }; template<typename X, typename Y> struct U : T<X, Y> { using T<X, Y>::T; }; U<S, char> foo(char ch) { return U<S, char>(ch); } int main() { U<S, int> a(42); U<S, char> b('4'); return 0; } } namespace WrongIdent { struct A {}; struct B : A {}; struct C : B { using B::A; }; } namespace DefaultCtorConflict { struct A { A(int = 0); }; struct B : A { using A::A; } b; // ok, not ambiguous, inherited constructor suppresses implicit default constructor struct C { B b; } c; } namespace InvalidConstruction { struct A { A(int); }; struct B { B() = delete; }; struct C : A, B { using A::A; }; // Initialization here is performed as if by a defaulted default constructor, // which would be ill-formed (in the immediate context) in this case because // it would be defined as deleted. template<typename T> void f(decltype(T(0))*); template<typename T> int &f(...); int &r = f<C>(0); } namespace ExplicitConv { struct B {}; struct D : B { // expected-note 3{{candidate}} using B::B; }; struct X { explicit operator B(); } x; struct Y { explicit operator D(); } y; D dx(x); // expected-error {{no matching constructor}} D dy(y); } namespace NestedListInit { struct B { B(); } b; // expected-note 3{{candidate}} struct D : B { // expected-note 14{{not viable}} using B::B; }; // This is a bit weird. We're allowed one pair of braces for overload // resolution, and one more pair of braces due to [over.ics.list]/2. B b1 = {b}; B b2 = {{b}}; B b3 = {{{b}}}; // expected-error {{no match}} // Per a proposed defect resolution, we don't get to call // D's version of B::B(const B&) here. D d0 = b; // expected-error {{no viable conversion}} D d1 = {b}; // expected-error {{no match}} D d2 = {{b}}; // expected-error {{no match}} D d3 = {{{b}}}; // expected-error {{no match}} D d4 = {{{{b}}}}; // expected-error {{no match}} } namespace PR31606 { // PR31606: as part of a proposed defect resolution, do not consider // inherited constructors that would be copy constructors for any class // between the declaring class and the constructed class (inclusive). struct Base {}; struct A : Base { using Base::Base; bool operator==(A const &) const; // expected-note {{no known conversion from 'PR31606::B' to 'const PR31606::A' for 1st argument}} }; struct B : Base { using Base::Base; }; bool a = A{} == A{}; // Note, we do *not* allow operator=='s argument to use the inherited A::A(Base&&) constructor to construct from B{}. bool b = A{} == B{}; // expected-error {{invalid operands}} } namespace implicit_member_srcloc { template<class T> struct S3 { }; template<class T> struct S2 { S2(S3<T> &&); }; template<class T> struct S1 : S2<T> { using S2<T>::S2; S1(); }; template<class T> struct S0 { S0(); S0(S0&&) = default; S1<T> m1; }; void foo1() { S0<int> s0; } } namespace PR47555 { struct A { constexpr A(int) {} }; struct B : A { using A::A; }; template<typename> void f() { constexpr B b = 0; }; template void f<int>(); } namespace PR48545 { struct B { void f(); private: B(int, int = 0); }; struct D : B { using B::B; }; void B::f() { D{0}; D{0, 0}; D(0); D(0, 0); D u = {0}; D v = {0, 0}; D w{0}; D x{0, 0}; D y(0); D z(0, 0); } }
[ "agarny@hellix.com" ]
agarny@hellix.com
3504c9584b4c8aaab8359f36579fb07530e58c12
580f51a5344f94a5a31b2a19943e60ad973e96bc
/sora/gl_env.cpp
bb86255a077855b421f665b68bfff709531b5cfa
[]
no_license
weimingtom/sora_old
e22b844d71b99e73fba33309977cca51e7f93d2c
45f842b3d40948542b859a6e21bed898ab542b6f
refs/heads/master
2021-01-16T19:11:07.138568
2012-05-21T15:46:14
2012-05-21T15:46:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,498
cpp
/* Copyright (C) 2011 by if1live */ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Ŭnicode please #include "sora_stdafx.h" #include "common_string.h" #include "gl_env.h" #if SR_ANDROID #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif namespace sora {; namespace gl { bool GLEnv::CheckFrameBufferStatus(const char *name) { GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status == GL_FRAMEBUFFER_COMPLETE) { return true; } //else,, const char *error_msg = NULL; switch(status) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: error_msg = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; #if SR_WIN && (SR_GLES == 0) case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: #else case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: #endif error_msg = "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: error_msg = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_UNSUPPORTED: error_msg = "GL_FRAMEBUFFER_UNSUPPORTED"; break; #if SR_WIN && (SR_GLES == 0) case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : error_msg = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; #endif default: CheckError(name); error_msg = "Unknown Error"; break; } LOGE("FrameBuffer Error [%s] : %s", name, error_msg); //SR_ASSERT(false); return false; } bool GLEnv::CheckError(const char *name) { int error = glGetError(); if (error != GL_NO_ERROR) { const char *error_msg; switch (error) { case GL_INVALID_ENUM: error_msg = "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: error_msg = "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: error_msg = "GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error_msg = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: error_msg = "GL_OUT_OF_MEMORY"; break; default: error_msg = "UNKNOWN"; break; } LOGE("OpenGL Error [%s] : %s", name, error_msg); #if SR_ANDROID exit(-1); #endif return false; } return true; } const std::vector<std::string> &GLEnv::GetExtensionList() const { using std::vector; using std::string; static vector<string> ext_list; static bool run = false; if (run == false) { run = true; const char *str = (const char*)glGetString(GL_EXTENSIONS); string ext_str = str; Split(ext_str, ' ', &ext_list); } return ext_list; } const std::string &GLEnv::GetVersion() const { static bool run = false; static std::string version; if (run == false) { run = true; const char *str = (const char *)glGetString(GL_VERSION); version = str; } return version; } const std::string &GLEnv::GetVender() const { static bool run = false; static std::string version; if (run == false) { run = true; const char *str = (const char *)glGetString(GL_VENDOR); version = str; } return version; } const std::string &GLEnv::GetRenderer() const { static bool run = false; static std::string version; if (run == false) { run = true; const char *str = (const char *)glGetString(GL_RENDERER); version = str; } return version; } GLenum GLEnv::TypeToGLEnum(DrawType type) { static bool run = false; static std::array<GLenum, kDrawTypeCount> enum_list; if(run == false) { run = true; enum_list[kDrawPoints] = GL_POINTS; enum_list[kDrawLines] = GL_LINES; enum_list[kDrawLineStrip] = GL_LINE_STRIP; enum_list[kDrawLineLoop] = GL_LINE_LOOP; enum_list[kDrawTriangles] = GL_TRIANGLES; enum_list[kDrawTriangleStrip] = GL_TRIANGLE_STRIP; enum_list[kDrawTriangleFan] = GL_TRIANGLE_FAN; } SR_ASSERT(type >= 0); SR_ASSERT(type < kDrawTypeCount); return enum_list[(int)type]; } GLenum GLEnv::TypeToGLEnum(TexFormatType type) { static bool run = false; static std::array<GLenum, kTexFormatTypeCount> enum_list; if(run == false) { run = true; enum_list[kTexFormatAlpha] = GL_ALPHA; enum_list[kTexFormatLumianceAlpha] = GL_LUMINANCE_ALPHA; enum_list[kTexFormatLumiance] = GL_LUMINANCE; enum_list[kTexFormatRGB] = GL_RGB; enum_list[kTexFormatRGBA] = GL_RGBA; } SR_ASSERT(type >= 0); SR_ASSERT(type < kTexFormatTypeCount); return enum_list[(int)type]; } GLenum GLEnv::TypeToGLEnum(TexMagFilter type) { static bool run = false; static std::array<GLenum, kTexMagFilterCount> enum_list; if(run == false) { run = true; enum_list[kTexMagLinear] = GL_LINEAR; enum_list[kTexMagNearest] = GL_NEAREST; } SR_ASSERT(type >= 0); SR_ASSERT(type < kTexMagFilterCount); return enum_list[(int)type]; } GLenum GLEnv::TypeToGLEnum(TexMinFilter type) { static bool run = false; static std::array<GLenum, kTexMinFilterCount> enum_list; if(run == false) { run = true; enum_list[kTexMinLinear] = GL_LINEAR; enum_list[kTexMinNearest] = GL_NEAREST; enum_list[kTexMinNearestMipmapNearest] = GL_NEAREST_MIPMAP_NEAREST; enum_list[kTexMinNearestMipmapLinear] = GL_NEAREST_MIPMAP_LINEAR; enum_list[kTexMinLinearMipmapNearest] = GL_LINEAR_MIPMAP_NEAREST; enum_list[kTexMinLinearMipmapLinear] = GL_LINEAR_MIPMAP_LINEAR; } SR_ASSERT(type >= 0); SR_ASSERT(type < kTexMinFilterCount); return enum_list[(int)type]; } GLenum GLEnv::TypeToGLEnum(TexWrapMode type) { static bool run = false; static std::array<GLenum, kTexWrapModeCount> enum_list; if(run == false) { run = true; enum_list[kTexWrapRepeat] = GL_REPEAT; enum_list[kTexWrapMirroredRepeat] = GL_MIRRORED_REPEAT; enum_list[kTexWrapClampToEdge] = GL_CLAMP_TO_EDGE; } SR_ASSERT(type >= 0); SR_ASSERT(type < kTexWrapModeCount); return enum_list[(int)type]; } GLenum GLEnv::TypeToGLEnum(BufferUsageType type) { static bool run = false; static std::array<GLenum, 10> enum_list; if(run == false) { run = true; enum_list[kBufferUsageStatic] = GL_STATIC_DRAW; enum_list[kBufferUsageDyanmic] = GL_DYNAMIC_DRAW; enum_list[kBufferUsageStream] = GL_STREAM_DRAW; } return enum_list[(int)type]; } GLenum GLEnv::VertexElemTypeToGLEnum(VarType type) { static bool run = false; static std::array<GLenum, kVarTypeCount> enum_list; if(run == false) { run = true; enum_list[kTypeFloat] = GL_FLOAT, enum_list[kTypeInt] = GL_INT, enum_list[kTypeUint] = GL_UNSIGNED_INT; enum_list[kTypeShort] = GL_SHORT; enum_list[kTypeUshort] = GL_UNSIGNED_SHORT; enum_list[kTypeByte] = GL_BYTE; enum_list[kTypeUbyte] = GL_UNSIGNED_BYTE; } SR_ASSERT(type >= 0); SR_ASSERT(type < kVarTypeCount); return enum_list[(GLenum)type]; } VertexInfo GLEnv::ToGLVertexInfo(const VertexInfo &info) { VertexInfo result = info; result.pos_type = VertexElemTypeToGLEnum(static_cast<VarType>(info.pos_type)); result.color_type = VertexElemTypeToGLEnum(static_cast<VarType>(info.color_type)); result.normal_type = VertexElemTypeToGLEnum(static_cast<VarType>(info.normal_type)); result.texcoord_type = VertexElemTypeToGLEnum(static_cast<VarType>(info.texcoord_type)); result.tangent_type = VertexElemTypeToGLEnum(static_cast<VarType>(info.tangent_type)); return result; } int vartype_glenum_table[][2] = { { kTypeFloat, GL_FLOAT }, { kTypeInt, GL_INT }, { kTypeUint, GL_UNSIGNED_INT }, { kTypeShort, GL_SHORT }, { kTypeUshort, GL_UNSIGNED_SHORT }, { kTypeByte, GL_BYTE }, { kTypeUbyte, GL_UNSIGNED_BYTE }, { kTypeFloatMat4, GL_FLOAT_MAT4 }, { kTypeFloatMat3, GL_FLOAT_MAT3 }, { kTypeFloatMat2, GL_FLOAT_MAT2 }, { kTypeFloatVec4, GL_FLOAT_VEC4 }, { kTypeFloatVec3, GL_FLOAT_VEC3 }, { kTypeFloatVec2, GL_FLOAT_VEC2 }, { kTypeIntVec4, GL_INT_VEC4 }, { kTypeIntVec3, GL_INT_VEC3 }, { kTypeIntVec2, GL_INT_VEC2 }, { kTypeSample2D, GL_SAMPLER_2D }, { kTypeSampleCube, GL_SAMPLER_CUBE }, }; VarType GLEnv::GLEnumToVarType(GLenum type) { const int table_size = sizeof(vartype_glenum_table) / sizeof(vartype_glenum_table[0]); for(int i = 0 ; i < table_size ; i++) { if(vartype_glenum_table[i][1] == type) { return (VarType)vartype_glenum_table[i][0]; } } SR_ASSERT(!"do not reach, not valid glenum"); return kTypeFloat; } GLenum GLEnv::VarTypeToGLEnum(VarType type) { const int table_size = sizeof(vartype_glenum_table) / sizeof(vartype_glenum_table[0]); for(int i = 0 ; i < table_size ; i++) { if(vartype_glenum_table[i][0] == type) { return vartype_glenum_table[i][1]; } } SR_ASSERT(!"do not reach, not valid VarType"); return kTypeFloat; } const VertexInfo &GLEnv::GetGLVertexInfo(VertexCode code) { static bool run = false; static std::array<VertexInfo, kVertexCodeCount> data; if(run == false) { run = true; for(int i = 0 ; i < kVertexCodeCount ; i++) { data[i] = ToGLVertexInfo(VertexInfo::Info((VertexCode)i)); } } return data[code]; } } //namespace gl } //namespace sora
[ "4ipperz@gmail.com" ]
4ipperz@gmail.com
e1cd099caa98ad44a2810de5eb7425962bb0f478
37ab17d6648d7493684cb2d94e5c3c7576fcf72a
/learning/programming_2/программирование2сем/лаб4/4.fix2.cpp
6f5c97f1dbdd30907d6b5b2222dd389fcaa360de
[]
no_license
ArtyomAdov/learning_sibsutis
74780d96658fe23efda916047ebc857215f81fc4
4a55314b91f7326ff792ca4521bd8bdf96f44bce
refs/heads/main
2023-02-11T17:44:42.124067
2021-01-03T11:25:46
2021-01-03T11:25:46
326,384,347
2
0
null
null
null
null
UTF-8
C++
false
false
875
cpp
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <ctime> using namespace std; int random (int N){return rand ()%N;} int main() { int **B, n, *A, i, j, *tmp; cout<<"vvedite razmer massiva\n"; cin>>n; cout<<endl; A=new int[n]; if (A==NULL) { cout<<"error"; return 1; }; B=new int *[n]; if (B==NULL) { cout<<"error"; return 1; }; cout<<"massiv"<<endl; for (i=0; i<n; i++) { A[i]=rand()%n-n/3; B[i]=&A[i]; } for (i=0; i<n; i++) { cout<<A[i]<<"||"<<*B[i]<<endl; } for (i=n-1; i>0; i--) { for (j=0; j<i; j++) { if (*B[j]>*B[j+1]) { tmp=B[j+1]; B[j+1]=B[j]; B[j]=tmp; } } } cout<<"otsortirovanii massiv"<<endl; for (i=0; i<n; i++){ cout<<A[i]<<"||"<<*B[i]<<endl; } delete A; delete B; A=NULL; B=NULL; return 0; system ("PAUSE"); }
[ "death1angel1annushka1@gmail.com" ]
death1angel1annushka1@gmail.com
a48e5f05e6639d9542b5de5bb34a41ae3e85a971
b142216f65c6a571a0158c707c5930b6eacf29e5
/algorithm/segmenttree.cpp
b50534319b2a9a17f349b431d4e601a18556a816
[]
no_license
beardnick/my_acm
992260719470d52d1d6e1235e0bc3e276dfc76f2
682404af6bab8834d75cfc11183226eec7a98a4e
refs/heads/master
2021-08-16T19:44:47.841459
2019-03-19T11:25:07
2019-03-19T11:25:07
102,596,550
1
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include <cstdio> #include <algorithm> using namespace std; #define lson l , m , rt << 1 #define rson m + 1 , r , rt << 1 | 1 const int maxn = 222222; int h , w , n; int MAX[maxn<<2]; void PushUP(int rt) { MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]); } void build(int l,int r,int rt) { MAX[rt] = w; if (l == r) return ; int m = (l + r) >> 1; build(lson); build(rson); } int query(int x,int l,int r,int rt) { if (l == r) { MAX[rt] -= x; return l; } int m = (l + r) >> 1; int ret = (MAX[rt<<1] >= x) ? query(x , lson) : query(x , rson); PushUP(rt); return ret; } int main() { while (~scanf("%d%d%d",&h,&w,&n)) { if (h > n) h = n; build(1 , h , 1); while (n --) { int x; scanf("%d",&x); if (MAX[1] < x) puts("-1"); else printf("%d\n",query(x , 1 , h , 1)); } } return 0; }
[ "1685437606@qq.com" ]
1685437606@qq.com
83abfd0b4a6e9b05ee5cfa139d440931665a866f
90a19a82c1b2c11c25c54debb932c400cef0844a
/demos/008_Image_Based_Lighting/vk_initializers.cpp
d7cd301edf184c1dc21554ce5fe537f4e58fd8a0
[]
no_license
manuel76413/Vulkan_Demos
bcb0abff31752307049c6ef0630bf9adc9e26242
09a0df5c7b358d7b172854f61912547f4f3097dd
refs/heads/master
2023-08-23T12:09:36.186423
2021-10-13T10:18:15
2021-10-13T10:18:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,680
cpp
#include "vk_initializers.h" #include "vk_mesh.h" #include "vk_material.h" #include <array> VkCommandPoolCreateInfo vkinit::commandPoolCreateInfo(uint32_t queueFamilyIndex, VkCommandPoolCreateFlags flags /*= 0*/) { VkCommandPoolCreateInfo commandPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO }; commandPoolInfo.pNext = nullptr; commandPoolInfo.queueFamilyIndex = queueFamilyIndex; commandPoolInfo.flags = flags; return commandPoolInfo; } VkRenderPassBeginInfo vkinit::renderPassBeginInfo(VkRenderPass renderPass, VkExtent2D swapChainExtent, VkFramebuffer framebuffer) { VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffer; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; static std::array<VkClearValue, 2> clearValues{}; clearValues[0].color = { {0.0f, 0.0f, 0.0f, 1.0f} }; clearValues[1].depthStencil = { 1.0f, 0 }; renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size()); renderPassInfo.pClearValues = clearValues.data(); return renderPassInfo; } VkCommandBufferAllocateInfo vkinit::commandBufferAllocateInfo(VkCommandPool pool, uint32_t count /*= 1*/, VkCommandBufferLevel level /*= VK_COMMAND_BUFFER_LEVEL_PRIMARY*/) { VkCommandBufferAllocateInfo info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO }; info.pNext = nullptr; info.commandPool = pool; info.commandBufferCount = count; info.level = level; return info; } VkPipelineShaderStageCreateInfo vkinit::pipelineShaderStageCreateInfo(VkShaderStageFlagBits stage, VkShaderModule shaderModule) { VkPipelineShaderStageCreateInfo info{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO }; info.pNext = nullptr; //shader stage info.stage = stage; //module containing the code for this shader stage info.module = shaderModule; //the entry point of the shader info.pName = "main"; return info; } VkPipelineVertexInputStateCreateInfo vkinit::vertexInputStateCreateInfo(const std::vector<VkVertexInputBindingDescription>& bindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& attributeDescriptions) { VkPipelineVertexInputStateCreateInfo vertexInputInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; vertexInputInfo.pNext = nullptr; //no vertex bindings or attributes vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data(); vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); return vertexInputInfo; } VkPipelineInputAssemblyStateCreateInfo vkinit::inputAssemblyCreateInfo(VkPrimitiveTopology topology) { VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; inputAssemblyInfo.pNext = nullptr; inputAssemblyInfo.topology = topology; //we are not going to use primitive restart on the entire tutorial so leave it on false inputAssemblyInfo.primitiveRestartEnable = VK_FALSE; return inputAssemblyInfo; } VkPipelineViewportStateCreateInfo vkinit::viewportStateCreateInfo(const VkViewport* viewport, const VkRect2D* scissor) { VkPipelineViewportStateCreateInfo viewportState{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; viewportState.viewportCount = 1; viewportState.pViewports = viewport; viewportState.scissorCount = 1; viewportState.pScissors = scissor; return viewportState; } VkPipelineRasterizationStateCreateInfo vkinit::rasterizationStateCreateInfo(VkPolygonMode polygonMode) { VkPipelineRasterizationStateCreateInfo rasterizerInfo = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; rasterizerInfo.pNext = nullptr; rasterizerInfo.depthClampEnable = VK_FALSE; //rasterizer discard allows objects with holes, default to no rasterizerInfo.rasterizerDiscardEnable = VK_FALSE; rasterizerInfo.polygonMode = polygonMode; rasterizerInfo.lineWidth = 1.0f; rasterizerInfo.cullMode = VK_CULL_MODE_NONE; rasterizerInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; //no depth bias rasterizerInfo.depthBiasEnable = VK_FALSE; rasterizerInfo.depthBiasConstantFactor = 0.0f; rasterizerInfo.depthBiasClamp = 0.0f; rasterizerInfo.depthBiasSlopeFactor = 0.0f; return rasterizerInfo; } VkPipelineMultisampleStateCreateInfo vkinit::multisamplingStateCreateInfo(VkSampleCountFlagBits msaaSamples) { VkPipelineMultisampleStateCreateInfo multisamplingInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; multisamplingInfo.pNext = nullptr; multisamplingInfo.sampleShadingEnable = VK_FALSE; //multisampling defaulted to no multisampling (1 sample per pixel) multisamplingInfo.rasterizationSamples = msaaSamples; // multisamplingInfo.minSampleShading = 1.0f; multisamplingInfo.pSampleMask = nullptr; multisamplingInfo.alphaToCoverageEnable = VK_FALSE; multisamplingInfo.alphaToOneEnable = VK_FALSE; return multisamplingInfo; } VkPipelineDepthStencilStateCreateInfo vkinit::depthStencilCreateInfo(VkCompareOp compareOp) { VkPipelineDepthStencilStateCreateInfo depthStencilInfo{ VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO }; depthStencilInfo.depthTestEnable = VK_TRUE; depthStencilInfo.depthWriteEnable = VK_TRUE; depthStencilInfo.depthCompareOp = compareOp; depthStencilInfo.depthBoundsTestEnable = VK_FALSE; depthStencilInfo.stencilTestEnable = VK_FALSE; return depthStencilInfo; } VkPipelineColorBlendAttachmentState vkinit::colorBlendAttachmentState() { VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; return colorBlendAttachment; } VkPipelineColorBlendStateCreateInfo vkinit::colorBlendAttachmentCreateInfo(VkPipelineColorBlendAttachmentState& colorBlendAttachment) { VkPipelineColorBlendStateCreateInfo colorBlending{ VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO }; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; return colorBlending; } VkPipelineLayoutCreateInfo vkinit::pipelineLayoutCreateInfo(std::span<VkDescriptorSetLayout> descriptorSetLayouts) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{ VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; pipelineLayoutInfo.pNext = nullptr; //empty defaults pipelineLayoutInfo.flags = 0; pipelineLayoutInfo.setLayoutCount = descriptorSetLayouts.size(); pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data(); pipelineLayoutInfo.pushConstantRangeCount = 0; pipelineLayoutInfo.pPushConstantRanges = nullptr; return pipelineLayoutInfo; } VkFramebufferCreateInfo vkinit::framebufferCreateInfo(VkRenderPass renderPass, VkExtent2D extent, const std::array<VkImageView, 3>& attachments) { VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; framebufferInfo.pNext = nullptr; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = extent.width; framebufferInfo.height = extent.height; framebufferInfo.layers = 1; return framebufferInfo; } VkDescriptorSetLayoutBinding vkinit::descriptorSetLayoutBinding(VkDescriptorType type, VkShaderStageFlags stageFlags, uint32_t binding, uint32_t descriptorCount /*= 1*/) { VkDescriptorSetLayoutBinding setbind = {}; setbind.binding = binding; setbind.descriptorCount = descriptorCount; setbind.descriptorType = type; setbind.pImmutableSamplers = nullptr; setbind.stageFlags = stageFlags; return setbind; } VkSemaphoreCreateInfo vkinit::semaphoreCreateInfo(VkSemaphoreCreateFlags flags /*= 0*/) { VkSemaphoreCreateInfo semaphoreInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; semaphoreInfo.pNext = nullptr; semaphoreInfo.flags = flags; return semaphoreInfo; } VkFenceCreateInfo vkinit::fenceCreateInfo(VkFenceCreateFlags flags /*= 0*/) { VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO }; fenceInfo.pNext = nullptr; fenceInfo.flags = flags; return fenceInfo; }
[ "hooyuser@outlook.com" ]
hooyuser@outlook.com
9e208ee847afe310a8b8769bbe6c1c27338fb2a5
234efff5291e2ab5e87ef71eb8ad80ec3b1854a2
/TestingHexThrombus/processor10/0.0025/s
7c8995feff5bcb43b2df32a7db637d5970a7e7a9
[]
no_license
tomwpeach/thrombus-code
5c6f86f0436177d9bbacae70d43f645d70be1a97
8cd3182c333452543f3feaecde08282bebdc00ed
refs/heads/master
2021-05-01T12:25:22.036621
2018-04-10T21:45:28
2018-04-10T21:45:28
121,060,409
1
0
null
null
null
null
UTF-8
C++
false
false
1,830
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0025"; object s; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 0.75; boundaryField { INLET { type fixedValue; value nonuniform 0(); } OUTLET { type zeroGradient; } WALL { type fixedValue; value uniform 0.75; } PATCH { type fixedValue; value nonuniform 0(); } procBoundary10to6 { type processor; value uniform 0.75; } procBoundary10to8 { type processor; value uniform 0.75; } procBoundary10to11 { type processor; value uniform 0.75; } procBoundary10to14 { type processor; value uniform 0.75; } procBoundary10to15 { type processor; value uniform 0.75; } } // ************************************************************************* //
[ "tom@tom-VirtualBox.(none)" ]
tom@tom-VirtualBox.(none)
56b0c00887c5b8f51783fe31d1fd293fec110b25
ebe8246fb06c08fff880d5356ada6c8abf796aa0
/Ivanov/ordinary polar/polar 2/mexbind0x/examples/funcs.cpp
8fd37b786d35293eba6d6088a7d57ce0899e8513
[ "MIT" ]
permissive
ISChetverikov/PolarCodesUnion
d6e6156d0b0a0e90cd4e8f08796c8fe27e4dcb38
6fe1818c7845808f19efa256a7ee36f7e2a2ef46
refs/heads/master
2023-02-05T10:21:46.141613
2020-12-24T14:44:47
2020-12-24T14:44:47
290,478,579
4
7
null
2020-12-24T14:44:48
2020-08-26T11:31:53
Jupyter Notebook
UTF-8
C++
false
false
928
cpp
#include <mex_commands.h> #include <vector> using namespace mexbind0x; int add(int a, int b) { return a + b; } void mex(MXCommands &m) { m.on("add", add); m.on("sub", [](int a, int b) { return a - b; }); m.on("sum", [](std::vector<std::vector<int>> v) { int r = 0; for (const auto &a : v) for (auto b : a) r += b; return r; }); m.on("sum bool", [](std::vector<std::vector<bool>> v) { int r = 0; for (const auto &a : v) for (auto b : a) r += b; return r; }); m.on_varargout("divmod", [](int nargout, int a, int b) -> std::vector<mx_auto> { if (nargout == 2) return {a / b, a % b}; else if (nargout < 2) return {a / b}; else throw std::invalid_argument("too many output arguments"); }); } MEX_SIMPLE(mex);
[ "ischetverikov@gmail.com" ]
ischetverikov@gmail.com
6bd270691d09a0c7377c614b7567dca33e9768cb
5c63b0e637d53dd7b5a17b7e97bd9170ad63a3bb
/Structural/Adapter.Exercise/text.cpp
de98d462119d5e2e4f05683bb8ac93fc78a366d5
[]
no_license
infotraining/cpp-dp-2021-06-30
24750fa173ad1184e5809b7ce445feff057df666
6edd71490f9bfc76c1cf0c07dd0ab6fd354fea65
refs/heads/master
2023-06-05T20:58:03.019024
2021-07-02T14:11:42
2021-07-02T14:11:42
380,954,754
0
0
null
null
null
null
UTF-8
C++
false
false
83
cpp
#include "text.hpp" namespace { // TODO - register creator for a Text class }
[ "krystian.piekos@infotraining.pl" ]
krystian.piekos@infotraining.pl
c2ab047f7ee8257302cb95e1e9608c170e8bc9b0
5eb685b218cedf230b5ee556ec18d53b3ce12aea
/Project2/main.cpp
436fb18319ae9ae338917d65ef28fb7bc6136791
[ "MIT" ]
permissive
harrisonyei/CPP2021Project2
a59c306225c07b31b3b2bd88e2fd3318b85d8cae
6dba0e669e7ffb4f6cb0ce22d1d0723b693568f1
refs/heads/main
2023-05-01T13:18:51.013551
2021-05-03T04:51:36
2021-05-03T04:51:36
361,139,198
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
#include "GameManager.h" #include <iostream> int main() { chess::GameManager game; return game.Run(); }
[ "tinghaoyei" ]
tinghaoyei
87a9c7a93a934824409f5cb0ca0e3c7f2de0f36d
f2fcefde8c9f1faa98542392a80b80cf78389249
/trees/BST.h
00d8161d8c9abf45494b9027791646910a4bad55
[]
no_license
nicolopizzo/algorithms-cpp
b080a0fd46178e2f6691747ea03a2cc9b5db59d5
9aa1d2b856b2d693f05c485c4a18c83f8120ceb0
refs/heads/main
2023-06-03T21:17:20.205836
2021-06-14T15:21:43
2021-06-14T15:21:43
374,140,295
0
0
null
null
null
null
UTF-8
C++
false
false
955
h
#ifndef BST_H #define BST_H template <class T> struct BSTNode { T value; BSTNode<T>* left; BSTNode<T>* right; BSTNode(T v) { value = v; left = nullptr; right = nullptr; } }; template <class T> class BST { BSTNode<T>* root; public: BST(); BST(T*, int); void insert(T value); bool search(T value); void remove(T value); void preorder(); void postorder(); void inorder(); bool isEmpty(); ~BST(); private: void insert(BSTNode<T>*& n, T value); bool search(BSTNode<T>* n, T value); void remove(BSTNode<T>*& n, T value); void preorder(BSTNode<T>* n); void postorder(BSTNode<T>* n); void inorder(BSTNode<T>* n); BSTNode<T>*& min(BSTNode<T>*& n); BSTNode<T>*& max(BSTNode<T>*& n); void deleteNode(BSTNode<T>*& n); }; #include "BST.cpp" #endif
[ "nicolopizzo@outlook.com" ]
nicolopizzo@outlook.com
776e20d424cff9d3be1632338cb6eeacefacfd61
dae4878b1febbdc8350a53402a9db051b272c1e2
/src/lib/DriverFramework/drivers/ms5611/MS5611.hpp
5b67a12a1d0562cafa1b60db3a0fa41a5ffae062
[]
no_license
ANCL/UAV_DOBIBS
5c86a38e65a58654957ae8344205ef2581ff00a8
65f39f5ff8baeed71338b7476963d7f4662bc6a6
refs/heads/master
2020-09-05T04:07:33.932986
2020-08-05T15:44:45
2020-08-05T15:44:45
219,977,726
6
5
null
2020-03-18T03:10:25
2019-11-06T11:08:15
C
UTF-8
C++
false
false
4,590
hpp
/**************************************************************************** * * Copyright (C) 2015 Mark Charlebois. All rights reserved. * Copyright (C) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include "BaroSensor.hpp" namespace DriverFramework { struct ms5611_sensor_calibration { uint16_t factory_setup; uint16_t c1_pressure_sens; uint16_t c2_pressure_offset; uint16_t c3_temp_coeff_pres_sens; uint16_t c4_temp_coeff_pres_offset; uint16_t c5_reference_temp; uint16_t c6_temp_coeff_temp; uint16_t serial_and_crc; }; struct ms5611_sensor_measurement { int32_t temperature_cc; // Temperature with 0.01 DegC resolution 2356 = 23.56 DegC int64_t off; // Offset at actual temperature int64_t sens; // Sensitivity at actual temperature int32_t pressure_mbar; // Temperature compensated pressure with 0.01 mbar resolution }; #define BARO_DEVICE_PATH "/dev/i2c-1" // update frequency is 50 Hz (44.4-51.3Hz ) at 8x oversampling #define MS5611_MEASURE_INTERVAL_US 20000 // microseconds #define MS5611_CONVERSION_INTERVAL_US 10000 /*microseconds */ #define MS5611_BUS_FREQUENCY_IN_KHZ 400 #define MS5611_TRANSFER_TIMEOUT_IN_USECS 9000 #define MS5611_MAX_LEN_SENSOR_DATA_BUFFER_IN_BYTES 6 #define MS5611_MAX_LEN_CALIB_VALUES 16 #define DRV_DF_DEVTYPE_MS5611 0x45 #define MS5611_SLAVE_ADDRESS 0x77 /* 7-bit slave address */ #if MS5611_MEASURE_INTERVAL_US < (MS5611_CONVERSION_INTERVAL_US * 2) #error "MS5611_MEASURE_INTERVAL_US Must >= MS5611_CONVERSION_INTERVAL_US * 2" #endif class MS5611 : public BaroSensor { public: MS5611(const char *device_path) : BaroSensor(device_path, MS5611_MEASURE_INTERVAL_US / 2), m_temperature_from_sensor(0), m_pressure_from_sensor(0), m_measure_phase(0) { m_id.dev_id_s.devtype = DRV_DF_DEVTYPE_MS5611; m_id.dev_id_s.address = MS5611_SLAVE_ADDRESS; } virtual ~MS5611() = default; // @return 0 on success, -errno on failure int start(); // @return 0 on success, -errno on failure int stop(); protected: void _measure(); virtual int _publish(struct baro_sensor_data &data); // Returns pressure in Pa as unsigned 32 bit integer // Output value of “24674867” represents // 24674867/100 = 246748.67 Pa = 24674867 hPa int64_t convertPressure(int64_t adc_pressure); // Returns temperature in DegC, resolution is 0.01 DegC // Output value of “5123” equals 51.23 DegC virtual int32_t convertTemperature(int32_t adc_temperature); int loadCalibration(); // Request to convert pressure or temperature data int _request(uint8_t phase); // Read out the requested sensor data int _collect(uint32_t &raw); bool crc4(uint16_t *n_prom); // returns 0 on success, -errno on failure int ms5611_init(); // Send reset to device int reset(); struct ms5611_sensor_calibration m_sensor_calibration; struct ms5611_sensor_measurement m_raw_sensor_convertion; uint32_t m_temperature_from_sensor; uint32_t m_pressure_from_sensor; int m_measure_phase; }; }; // namespace DriverFramework
[ "moeini@ualberta.ca" ]
moeini@ualberta.ca
9aa173a2549db98cc3394eaa27a9823422429e30
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/variations/cros_evaluate_seed/evaluate_seed.cc
efd2cfd35e04219a0ecae3c7c3def56f698a5744
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
4,184
cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/variations/cros_evaluate_seed/evaluate_seed.h" #include "base/check.h" #include "base/containers/flat_set.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/system/sys_info.h" #include "build/branding_buildflags.h" #include "chromeos/ash/components/dbus/featured/featured.pb.h" #include "chromeos/crosapi/cpp/channel_to_enum.h" #include "chromeos/crosapi/cpp/crosapi_constants.h" #include "components/variations/proto/study.pb.h" #include "components/variations/service/variations_field_trial_creator.h" namespace variations::cros_early_boot::evaluate_seed { namespace { constexpr char kSafeSeedSwitch[] = "use-safe-seed"; constexpr char kEnterpriseEnrolledSwitch[] = "enterprise-enrolled"; } // namespace base::Version CrosVariationsServiceClient::GetVersionForSimulation() { // TODO(mutexlox): Get the version that will be used on restart instead of // the current version IF this is necessary. (We may not need simulations for // early-boot experiments.) // See ChromeVariationsServiceClient::GetVersionForSimulation. return version_info::GetVersion(); } scoped_refptr<network::SharedURLLoaderFactory> CrosVariationsServiceClient::GetURLLoaderFactory() { // Do not load any data on CrOS early boot. This function is only called to // fetch a new seed, and we should not fetch new seeds in evaluate_seed. return nullptr; } network_time::NetworkTimeTracker* CrosVariationsServiceClient::GetNetworkTimeTracker() { // Do not load any data on CrOS early boot; evaluate_seed should not load new // seeds. return nullptr; } bool CrosVariationsServiceClient::OverridesRestrictParameter( std::string* parameter) { // TODO(b/263975722): Implement. return false; } // Get the active channel, if applicable. version_info::Channel CrosVariationsServiceClient::GetChannel() { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) std::string channel; if (base::SysInfo::GetLsbReleaseValue(crosapi::kChromeOSReleaseTrack, &channel)) { return crosapi::ChannelToEnum(channel); } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) return version_info::Channel::UNKNOWN; } bool CrosVariationsServiceClient::IsEnterprise() { return base::CommandLine::ForCurrentProcess()->HasSwitch( kEnterpriseEnrolledSwitch); } std::unique_ptr<ClientFilterableState> GetClientFilterableState() { CrosVariationsServiceClient client; // TODO(b/263975722): Properly use VariationsServiceClient and // VariationsFieldTrialCreator::GetClientFilterableStateForVersion. auto state = std::make_unique<ClientFilterableState>( base::BindOnce([](bool enrolled) { return enrolled; }, client.IsEnterprise()), base::BindOnce([] { return base::flat_set<uint64_t>(); })); state->channel = ConvertProductChannelToStudyChannel(client.GetChannelForVariations()); state->form_factor = client.GetCurrentFormFactor(); return state; } absl::optional<SafeSeed> GetSafeSeedData(FILE* stream) { featured::SeedDetails safe_seed; if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSafeSeedSwitch)) { // Read safe seed from |stream|. std::string safe_seed_data; if (!base::ReadStreamToString(stream, &safe_seed_data)) { PLOG(ERROR) << "Failed to read from stream:"; return absl::nullopt; } // Parse safe seed. if (!safe_seed.ParseFromString(safe_seed_data)) { LOG(ERROR) << "Failed to parse proto from input"; return absl::nullopt; } return SafeSeed{true, safe_seed}; } return SafeSeed{false, safe_seed}; } int EvaluateSeedMain(FILE* stream) { absl::optional<SafeSeed> safe_seed = GetSafeSeedData(stream); if (!safe_seed.has_value()) { LOG(ERROR) << "Failed to read seed from stdin"; return EXIT_FAILURE; } std::unique_ptr<ClientFilterableState> state = GetClientFilterableState(); // TODO(b/263975722): Implement this binary. (void)state; return EXIT_SUCCESS; } } // namespace variations::cros_early_boot::evaluate_seed
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
68a9b73ab43926a02beef61b1f096d4c597a7e10
be3c35d27245654e53c47619a485ef3d0e50901d
/C++/CPPDemos/cppSTLreview/modernCpp/modernCpp/random.cpp
26d26f7f0c40fdde9c54ad6a9cbb96007321412e
[]
no_license
zzhan08/Exercises
9aa6a439e36222806310eef50199250353291c4d
1be3566206ead9cc329c809c7ad1a2f03c010056
refs/heads/main
2023-03-03T05:52:30.539181
2021-02-07T20:43:03
2021-02-07T20:43:03
336,820,822
0
0
null
null
null
null
UTF-8
C++
false
false
37
cpp
#include "stdafx.h" #include <random>
[ "zhangz@innopharmalabs.com" ]
zhangz@innopharmalabs.com
8cbf3c54e526e63e20656a6f242b4a9c992756b7
7b46f4140b078c5cb7954b6735fff6a31e2e7751
/aten/src/TH/THTensorCopy.cpp
482a7b986f5302cc5363d098902099e7758c2726
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
jcjohnson/pytorch
f704a5a602f54f6074f6b49d1696f30e05dea429
ab253c2bf17747a396c12929eaee9d379bb116c4
refs/heads/master
2020-04-02T15:36:09.877841
2018-10-24T21:57:42
2018-10-24T22:02:40
101,438,891
8
2
NOASSERTION
2018-10-24T21:55:49
2017-08-25T20:13:19
Python
UTF-8
C++
false
false
206
cpp
#include "THTensor.hpp" #include "THVector.h" #include <algorithm> #include "generic/THTensorCopy.cpp" #include "THGenerateAllTypes.h" #include "generic/THTensorCopy.cpp" #include "THGenerateHalfType.h"
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
c243025120eb69861bfec3cd22ecc8e77dfdbe71
52ca1b5adba2ca71c41b66f5ba7c9de655718a36
/src/parallel_omp/src/compare.cpp
d69bc704a1b07e0168060f838ab3d4853dbd24dd
[ "MIT" ]
permissive
IGMercier/15418-S20-Parallel-Compression-
80b8eb3f7a48a09a0435f6e95900ab596bd1c489
b6521ff5d668908ee8493aa04108b56dd04aaa26
refs/heads/master
2022-06-30T01:24:32.786669
2020-05-10T23:44:56
2020-05-10T23:44:56
258,647,046
0
0
null
null
null
null
UTF-8
C++
false
false
4,166
cpp
#include <iostream> #include <dirent.h> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../../../include/stb_image.h" #include "../../../include/stb_image_write.h" bool same(std::string &save_dir, std::string &img1, std::string &img2) { // Load imagges int width, height, bpp; uint8_t *img_par = stbi_load((save_dir + img1).data(), &width, &height, &bpp, 3); int _width, _height, _bpp; uint8_t *img_ser = stbi_load((save_dir + img2).data(), &_width, &_height, &_bpp, 3); // Check dimensions if (width != _width || height != _height || bpp != _bpp) { std::cout << "INCORRECT dimensions: " << img1 << " and " << img2; std::cout << std::endl; return false; } // Check pixel values long error = 0; int max_diff = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { uint8_t *bgrPixelPar = img_par + (i * width + j) * 3; uint8_t *bgrPixelSer = img_ser + (i * width + j) * 3; if (bgrPixelPar[0] != bgrPixelPar[1] || bgrPixelPar[0] != bgrPixelPar[2] || bgrPixelSer[0] != bgrPixelSer[1] || bgrPixelSer[0] != bgrPixelSer[2]) { std::cout << "Pixel values across channels are not same" << std::endl; } max_diff = std::max(max_diff, abs(bgrPixelPar[0] - bgrPixelSer[0])); error += !!abs(bgrPixelPar[0] - bgrPixelSer[0]); // Print information about the mismatching pixels if (bgrPixelPar[0] != bgrPixelSer[0]) { // std::cout << "H: " << i << " W: " << j << std::endl; // printf("Parallel: %d\n", bgrPixelPar[0]); // printf("Serial: %d\n", bgrPixelSer[0]); // break; } } } if (error == 0) { std::cout << "CORRECT" << std::endl; } else { std::cout << "INCORRECT: " << img1 << " and " << img2; std::cout << " | Num different values: " << error << " | Max diff: " << max_diff; std::cout << std::endl; } return error == 0; } int main() { std::cout << "*********" << " COMPARISON " << "*********" << std::endl; std::vector<std::string> par_files, ser_files; std::string file = "", refined_file = ""; std::string save_dir = "./compressed_images/"; DIR *dir; struct dirent *ent; if ((dir = opendir (save_dir.data())) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { file = ent->d_name; refined_file = ""; for (auto &c: file) { if (c == ' ') continue; refined_file += c; } if (refined_file.substr(0, 3) == "ser") { ser_files.push_back(refined_file); } else if (refined_file.substr(0, 3) == "par") { par_files.push_back(refined_file); } } closedir (dir); } else { /* could not open directory */ perror (""); return EXIT_FAILURE; } sort(ser_files.begin(), ser_files.end()); sort(par_files.begin(), par_files.end()); if (ser_files.size() != par_files.size()) { std::cout << "Unequal amount of serial and parallel files" << std::endl; return 0; } for (int i = 0; i < ser_files.size(); i++) { auto img1 = par_files[i]; auto img2 = ser_files[i]; if (img1.length() != img2.length()) { std::cout << "Different images" << std::endl; } std::string p = "", s = ""; for (int i = 0; i < img1.length(); i++) { if (isdigit(img1[i])) { p += img1[i]; } if (isdigit(img2[i])) { s += img2[i]; } } if (s != p) { std::cout << "Different images" << std::endl; } if (!same(save_dir, par_files[i], ser_files[i])) { // break; } } return 0; }
[ "dhananjs@ghc66.ghc.andrew.cmu.edu" ]
dhananjs@ghc66.ghc.andrew.cmu.edu
0a73bf07ad89254669f0149b93a2dce25d13cb71
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_6943.cpp
d3815f880bdd46588e960210e2cdec7579cf1f65
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
} nexttype = get_token(fp, nexttoken); } if (nexttype != ACCESS){ print_error("Should be ACCESS", nexttoken, nexttype); free_node(np); return 0; } type = get_token(fp, token); if (type != READONLY && type != READWRITE && type != WRITEONLY && type != NOACCESS && type != READCREATE){ print_error("Bad access type", nexttoken, nexttype); free_node(np); return 0; } type = get_token(fp, token); if (type != STATUS){ print_error("Should be STATUS", token, nexttype); free_node(np); return 0; } type = get_token(fp, token); if (type != MANDATORY && type != CURRENT && type != OPTIONAL && type != OBSOLETE && type != DEPRECATED){ print_error("Bad status", token, type); free_node(np); return 0;
[ "993273596@qq.com" ]
993273596@qq.com
a57e1d67181e6e3e60d3af16f4ff03b043880316
db8be521b8e2eab424f594a50886275d68dd5a1b
/Competitive Programming/codechef/NOV13/SPOTWO.cpp
e3d5d55ae680d347d5b7d32c695054e67a9eb9f7
[]
no_license
purnimamehta/Articles-n-Algorithms
7f2aa8046c8eef0e510689771a493f84707e9297
aaea50bf1627585b935f8e43465360866b3b4eac
refs/heads/master
2021-01-11T01:01:53.382696
2017-01-15T04:12:44
2017-01-15T04:12:44
70,463,305
10
4
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include<iostream> using namespace std; #define MOD 1000000007 long long power[]={2, 1024, 976371285, 688423210, 905611805, 607723520, 235042059, 255718402, 494499948, 140625001, 291251492, 25600497, 959366170, 836339738, 621966918, 264444359, 271283348, 952065854, 719476260, 28918236LL, 894102506LL, 663968931LL, 721365950LL, 70015478LL, 881107223LL, 331368790LL}; int main() { int t; cin>>t; while(t--) { int n; cin>>n; int i=0; long long solution=1; while(n) { if(n&1) { solution*=power[i]; solution%=MOD; } i++; n>>=1; } solution*=solution; solution%=MOD; cout<<solution<<endl; } }
[ "me@lefeeza.com" ]
me@lefeeza.com
0c2892fff0a7370e2a6e1eeac45c7d1f83b90b40
986c21d401983789d9b3e5255bcf9d76070f65ec
/src/plugins/lmp/sync/clouduploader.h
4f1d892e5666543c92d62e8387d3775d0b94a94c
[ "BSL-1.0" ]
permissive
0xd34df00d/leechcraft
613454669be3a0cecddd11504950372c8614c4c8
15c091d15262abb0a011db03a98322248b96b46f
refs/heads/master
2023-07-21T05:08:21.348281
2023-06-04T16:50:17
2023-06-04T16:50:17
119,854
149
71
null
2017-09-03T14:16:15
2009-02-02T13:52:45
C++
UTF-8
C++
false
false
1,184
h
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #pragma once #include <QObject> #include <QList> #include <interfaces/lmp/icloudstorageplugin.h> namespace LC { namespace LMP { class CloudUploader : public QObject { Q_OBJECT ICloudStoragePlugin *Cloud_; public: struct UploadJob { bool RemoveOnFinish_ = false; QString Account_; QString Filename_; }; private: QList<UploadJob> Queue_; UploadJob CurrentJob_; public: CloudUploader (ICloudStoragePlugin*, QObject* = 0); void Upload (const UploadJob&); private: void StartJob (const UploadJob&); bool IsRunning () const; private slots: void handleUploadFinished (const QString& localPath, LC::LMP::CloudStorageError error, const QString& errorStr); signals: void startedCopying (const QString&); void finishedCopying (); }; } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
1eee6733540ea6aa410e3aa4d250449eaa9ebb9c
df7bade8db21b3730a8475571efa41c7f57fc478
/Arduino/Complete_wearable/Challenge2GMMHrMonitor/Accelerometer.ino
29fbca92d2b2f0c3b95e0b8a5b2aa26727688cc2
[]
no_license
williamliuzhenwei/MyWatch
2d59c3a48571b9a269539787ea7db1ee472b872c
29ce13aeda74ffe416546ec377956c323e5272ee
refs/heads/master
2023-05-24T14:57:14.004960
2021-06-13T18:52:49
2021-06-13T18:52:49
376,611,838
0
0
null
null
null
null
UTF-8
C++
false
false
323
ino
const int accelX = A2; const int accelY = A3; const int accelZ = A4; void setupAccelSensor(){ Serial.begin(115200); pinMode(accelX, INPUT); pinMode(accelY, INPUT); pinMode(accelZ, INPUT); } void readAccelSensor(){ ax = analogRead(accelX); ay = analogRead(accelY); az = analogRead(accelZ); }
[ "zhl012@ucsd.edu" ]
zhl012@ucsd.edu
6c0af95970f24812f0c98a6e1579c5ceaae6d306
e4ec5b6cf3cfe2568ef0b5654c019e398b4ecc67
/aws-sdk-cpp/1.2.10/include/aws/iot/model/AttachPrincipalPolicyRequest.h
0079c026aafbf3a554c17a39e7273d35c17e1be8
[ "MIT", "Apache-2.0", "JSON" ]
permissive
EnjoyLifeFund/macHighSierra-cellars
59051e496ed0e68d14e0d5d91367a2c92c95e1fb
49a477d42f081e52f4c5bdd39535156a2df52d09
refs/heads/master
2022-12-25T19:28:29.992466
2017-10-10T13:00:08
2017-10-10T13:00:08
96,081,471
3
1
null
2022-12-17T02:26:21
2017-07-03T07:17:34
null
UTF-8
C++
false
false
4,925
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/iot/IoT_EXPORTS.h> #include <aws/iot/IoTRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace IoT { namespace Model { /** * <p>The input for the AttachPrincipalPolicy operation.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/iot-2015-05-28/AttachPrincipalPolicyRequest">AWS * API Reference</a></p> */ class AWS_IOT_API AttachPrincipalPolicyRequest : public IoTRequest { public: AttachPrincipalPolicyRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "AttachPrincipalPolicy"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The policy name.</p> */ inline const Aws::String& GetPolicyName() const{ return m_policyName; } /** * <p>The policy name.</p> */ inline void SetPolicyName(const Aws::String& value) { m_policyNameHasBeenSet = true; m_policyName = value; } /** * <p>The policy name.</p> */ inline void SetPolicyName(Aws::String&& value) { m_policyNameHasBeenSet = true; m_policyName = std::move(value); } /** * <p>The policy name.</p> */ inline void SetPolicyName(const char* value) { m_policyNameHasBeenSet = true; m_policyName.assign(value); } /** * <p>The policy name.</p> */ inline AttachPrincipalPolicyRequest& WithPolicyName(const Aws::String& value) { SetPolicyName(value); return *this;} /** * <p>The policy name.</p> */ inline AttachPrincipalPolicyRequest& WithPolicyName(Aws::String&& value) { SetPolicyName(std::move(value)); return *this;} /** * <p>The policy name.</p> */ inline AttachPrincipalPolicyRequest& WithPolicyName(const char* value) { SetPolicyName(value); return *this;} /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline const Aws::String& GetPrincipal() const{ return m_principal; } /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline void SetPrincipal(const Aws::String& value) { m_principalHasBeenSet = true; m_principal = value; } /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline void SetPrincipal(Aws::String&& value) { m_principalHasBeenSet = true; m_principal = std::move(value); } /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline void SetPrincipal(const char* value) { m_principalHasBeenSet = true; m_principal.assign(value); } /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline AttachPrincipalPolicyRequest& WithPrincipal(const Aws::String& value) { SetPrincipal(value); return *this;} /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline AttachPrincipalPolicyRequest& WithPrincipal(Aws::String&& value) { SetPrincipal(std::move(value)); return *this;} /** * <p>The principal, which can be a certificate ARN (as returned from the * CreateCertificate operation) or an Amazon Cognito ID.</p> */ inline AttachPrincipalPolicyRequest& WithPrincipal(const char* value) { SetPrincipal(value); return *this;} private: Aws::String m_policyName; bool m_policyNameHasBeenSet; Aws::String m_principal; bool m_principalHasBeenSet; }; } // namespace Model } // namespace IoT } // namespace Aws
[ "Raliclo@gmail.com" ]
Raliclo@gmail.com
1133c8f2d588ff52914933a1e1269e8a88246df8
d3cfaa7be41b70205e027d718f5546723f59906d
/network_programming/WebServer/WebServer/Epoll.h
15ff5e899f86dcdf64f47dab4c12309d9652d282
[ "MIT" ]
permissive
15757170756/All-Code-I-Have-Done
8836c11ad1648f06cb815ab76f3378cddc41ac63
e8985935efa641e68b76c231dddaf6326e3f3f98
refs/heads/master
2022-12-12T10:01:26.132458
2021-09-02T13:34:00
2021-09-02T13:34:09
111,758,971
9
3
null
2022-12-07T23:30:17
2017-11-23T03:31:03
Jupyter Notebook
UTF-8
C++
false
false
914
h
// @Author Lin Ya // @Email xxbbb@vip.qq.com #pragma once #include "Channel.h" #include "HttpData.h" #include "Timer.h" #include <vector> #include <unordered_map> #include <sys/epoll.h> #include <memory> class Epoll { public: Epoll(); ~Epoll(); void epoll_add(SP_Channel request, int timeout); void epoll_mod(SP_Channel request, int timeout); void epoll_del(SP_Channel request); std::vector<std::shared_ptr<Channel>> poll(); std::vector<std::shared_ptr<Channel>> getEventsRequest(int events_num); void add_timer(std::shared_ptr<Channel> request_data, int timeout); int getEpollFd() { return epollFd_; } void handleExpired(); private: static const int MAXFDS = 100000; int epollFd_; std::vector<epoll_event> events_; std::shared_ptr<Channel> fd2chan_[MAXFDS]; std::shared_ptr<HttpData> fd2http_[MAXFDS]; TimerManager timerManager_; };
[ "15757170756@139.com" ]
15757170756@139.com
d08d682f9f9fce9e3dd0d187bdd25534bc2f53b7
4a3ca65ba2228c20e3f04f3ab1538dd00f87e976
/src/qt/notificator.cpp
6d5e26ea55d31b1cccdde63bf128f49629a3d20c
[ "MIT" ]
permissive
bonoproject/Bonorum
dd5b29a80b41a8e9fc0e0311b11730b5bf6fb3c2
d0dede6c416b812398a6c88cb2f54dad049c932e
refs/heads/master
2020-12-20T16:41:40.978500
2020-06-08T12:04:16
2020-06-08T12:04:16
236,138,813
1
1
null
null
null
null
UTF-8
C++
false
false
8,418
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Copyright (c) 2020 The BonorumCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "notificator.h" #include <QApplication> #include <QByteArray> #include <QIcon> #include <QImageWriter> #include <QMessageBox> #include <QMetaType> #include <QStyle> #include <QSystemTrayIcon> #include <QTemporaryFile> #include <QVariant> #ifdef USE_DBUS #include <QtDBus> #include <stdint.h> #endif // Include ApplicationServices.h after QtDbus to avoid redefinition of check(). // This affects at least OSX 10.6. See /usr/include/AssertMacros.h for details. // Note: This could also be worked around using: // #define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 #ifdef Q_OS_MAC #include "macnotificationhandler.h" #include <ApplicationServices/ApplicationServices.h> #endif #ifdef USE_DBUS // https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128 const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128; #endif Notificator::Notificator(const QString& programName, QSystemTrayIcon* trayicon, QWidget* parent) : QObject(parent), parent(parent), programName(programName), mode(None), trayIcon(trayicon) #ifdef USE_DBUS , interface(0) #endif { if (trayicon && trayicon->supportsMessages()) { mode = QSystemTray; } #ifdef USE_DBUS interface = new QDBusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications"); if (interface->isValid()) { mode = Freedesktop; } #endif #ifdef Q_OS_MAC // check if users OS has support for NSUserNotification if (MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) { mode = UserNotificationCenter; } #endif } Notificator::~Notificator() { #ifdef USE_DBUS delete interface; #endif } #ifdef USE_DBUS // Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html class FreedesktopImage { public: FreedesktopImage() {} FreedesktopImage(const QImage& img); static int metaType(); // Image to variant that can be marshalled over DBus static QVariant toVariant(const QImage& img); private: int width, height, stride; bool hasAlpha; int channels; int bitsPerSample; QByteArray image; friend QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i); friend const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i); }; Q_DECLARE_METATYPE(FreedesktopImage); // Image configuration settings const int CHANNELS = 4; const int BYTES_PER_PIXEL = 4; const int BITS_PER_SAMPLE = 8; FreedesktopImage::FreedesktopImage(const QImage& img) : width(img.width()), height(img.height()), stride(img.width() * BYTES_PER_PIXEL), hasAlpha(true), channels(CHANNELS), bitsPerSample(BITS_PER_SAMPLE) { // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format QImage tmp = img.convertToFormat(QImage::Format_ARGB32); const uint32_t* data = reinterpret_cast<const uint32_t*>(tmp.bits()); unsigned int num_pixels = width * height; image.resize(num_pixels * BYTES_PER_PIXEL); for (unsigned int ptr = 0; ptr < num_pixels; ++ptr) { image[ptr * BYTES_PER_PIXEL + 0] = data[ptr] >> 16; // R image[ptr * BYTES_PER_PIXEL + 1] = data[ptr] >> 8; // G image[ptr * BYTES_PER_PIXEL + 2] = data[ptr]; // B image[ptr * BYTES_PER_PIXEL + 3] = data[ptr] >> 24; // A } } QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i) { a.beginStructure(); a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image; a.endStructure(); return a; } const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i) { a.beginStructure(); a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image; a.endStructure(); return a; } int FreedesktopImage::metaType() { return qDBusRegisterMetaType<FreedesktopImage>(); } QVariant FreedesktopImage::toVariant(const QImage& img) { FreedesktopImage fimg(img); return QVariant(FreedesktopImage::metaType(), &fimg); } void Notificator::notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout) { Q_UNUSED(cls); // Arguments for DBus call: QList<QVariant> args; // Program Name: args.append(programName); // Unique ID of this notification type: args.append(0U); // Application Icon, empty string args.append(QString()); // Summary args.append(title); // Body args.append(text); // Actions (none, actions are deprecated) QStringList actions; args.append(actions); // Hints QVariantMap hints; // If no icon specified, set icon based on class QIcon tmpicon; if (icon.isNull()) { QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion; switch (cls) { case Information: sicon = QStyle::SP_MessageBoxInformation; break; case Warning: sicon = QStyle::SP_MessageBoxWarning; break; case Critical: sicon = QStyle::SP_MessageBoxCritical; break; default: break; } tmpicon = QApplication::style()->standardIcon(sicon); } else { tmpicon = icon; } hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage()); args.append(hints); // Timeout (in msec) args.append(millisTimeout); // "Fire and forget" interface->callWithArgumentList(QDBus::NoBlock, "Notify", args); } #endif void Notificator::notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout) { Q_UNUSED(icon); QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon; switch (cls) // Set icon based on class { case Information: sicon = QSystemTrayIcon::Information; break; case Warning: sicon = QSystemTrayIcon::Warning; break; case Critical: sicon = QSystemTrayIcon::Critical; break; } trayIcon->showMessage(title, text, sicon, millisTimeout); } // Based on Qt's tray icon implementation #ifdef Q_OS_MAC void Notificator::notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon) { // icon is not supported by the user notification center yet. OSX will use the app icon. MacNotificationHandler::instance()->showNotification(title, text); } #endif void Notificator::notify(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout) { switch (mode) { #ifdef USE_DBUS case Freedesktop: notifyDBus(cls, title, text, icon, millisTimeout); break; #endif case QSystemTray: notifySystray(cls, title, text, icon, millisTimeout); break; #ifdef Q_OS_MAC case UserNotificationCenter: notifyMacUserNotificationCenter(cls, title, text, icon); break; #endif default: if (cls == Critical) { // Fall back to old fashioned pop-up dialog if critical and no other notification available QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok); } break; } }
[ "60004952+bonoproject@users.noreply.github.com" ]
60004952+bonoproject@users.noreply.github.com
60062b240a87e6db39a8dc3d314ced4d2ab1c8cc
b01e58e74ba0f989c5beb8f532eec2c11f5439b5
/contests/samara/A.cpp
085446d7946051c3ee984c1c2b7f3a7bce938645
[]
no_license
breno-helf/TAPA.EXE
54d56e2a2c15e709819c172695200479b1b34729
3ac36a3d2401a2d4861fc7a51ce9b1b6a20ab112
refs/heads/master
2021-01-19T11:18:15.958602
2018-08-03T22:25:03
2018-08-03T22:25:03
82,236,704
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include <bits/stdc++.h> using namespace std; const long double PI = acos(-1); int main(){ long double a, b, c, r; long double p; cin >> a >> b >> c >> r; p = (a+b+c)/2; long double area = sqrt(p) * sqrt(p-a) * sqrt(p-b) * sqrt(p-c); long double ri = (2.0 * area) / (a + b + c); long double ratio = r / ri; long double ai = a * ratio, bi = b * ratio , ci = c * ratio; long double pi = (ai + bi + ci) / 2; long double A2 = sqrt(pi) * sqrt(pi - ai) * sqrt(pi - bi) * sqrt(pi - ci); long double calc = A2 - r * r * PI; // cout << "--- "; // cout << ri << ' ' << A2 << ' ' << calc << '\n'; cout << fixed << setprecision(10) << (area - calc) / area << '\n'; return 0; }
[ "breno.moura@hotmail.com" ]
breno.moura@hotmail.com
8314c352c4e6974da82c0ee035d7164ce16aefda
e2c3bc4ac8501c0681d770d94e7e744ae1cfd4a3
/libraries/pfodESP8266WiFi/src/pfodESP8266WiFiMulti.h
73416ff3c0541471d142bf83877923b674940c4d
[]
no_license
fionachui/herbertBasil
baf37e1c9e969962d360d0f133ab00afadfa843f
0419fddb5b6cfd439b6464e64402db2e2fda6b46
refs/heads/master
2016-09-13T23:41:26.239504
2016-05-06T03:41:20
2016-05-06T03:41:20
58,089,865
1
0
null
null
null
null
UTF-8
C++
false
false
1,747
h
/** * * @file ESP8266WiFiMulti.h * @date 16.05.2015 * @author Markus Sattler * * Copyright (c) 2015 Markus Sattler. All rights reserved. * This file is part of the esp8266 core for Arduino environment. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef WIFICLIENTMULTI_H_ #define WIFICLIENTMULTI_H_ #include "pfodESP8266WiFi.h" #undef min #undef max #include <vector> //#define DEBUG_WIFI_MULTI(...) Serial1.printf( __VA_ARGS__ ) #ifndef DEBUG_WIFI_MULTI #define DEBUG_WIFI_MULTI(...) #endif typedef struct { char * ssid; char * passphrase; } WifiAPlist_t; class ESP8266WiFiMulti { public: ESP8266WiFiMulti(); ~ESP8266WiFiMulti(); bool addAP(const char* ssid, const char *passphrase = NULL); wl_status_t run(void); private: std::vector<WifiAPlist_t> APlist; bool APlistAdd(const char* ssid, const char *passphrase = NULL); void APlistClean(void); }; #endif /* WIFICLIENTMULTI_H_ */
[ "fionachui.23@gmail.com" ]
fionachui.23@gmail.com
eb37f7fe55533ea4e3676a68379fac0a7fde975e
0ca50389f4b300fa318452128ab5437ecc97da65
/src/color/hsl/get/gray.hpp
63abdea574030fc743127d47d70fa95199af1a2b
[ "Apache-2.0" ]
permissive
dmilos/color
5981a07d85632d5c959747dac646ac9976f1c238
84dc0512cb5fcf6536d79f0bee2530e678c01b03
refs/heads/master
2022-09-03T05:13:16.959970
2022-08-20T09:22:24
2022-08-22T06:03:32
47,105,546
160
25
Apache-2.0
2021-09-29T07:11:04
2015-11-30T08:37:43
C++
UTF-8
C++
false
false
1,398
hpp
#ifndef color_hsl_get_gray #define color_hsl_get_gray // ::color::get::gray( c ) #include "../../gray/place/place.hpp" #include "../../gray/akin/hsl.hpp" #include "../../gray/trait/component.hpp" #include "../category.hpp" #include "../../_internal/normalize.hpp" #include "../../_internal/diverse.hpp" #include "../../generic/trait/scalar.hpp" namespace color { namespace get { template< typename tag_name > inline typename ::color::trait::component< typename ::color::akin::gray< ::color::category::hsl<tag_name> >::akin_type >::return_type gray( ::color::model< ::color::category::hsl<tag_name> > const& color_parameter ) { typedef ::color::category::hsl< tag_name > category_type; typedef typename ::color::trait::scalar< category_type >::instance_type scalar_type; typedef typename ::color::akin::gray< category_type >::akin_type akin_type; typedef ::color::_internal::diverse< akin_type > diverse_type; typedef ::color::_internal::normalize< category_type > normalize_type; enum { lightness_p = ::color::place::_internal::lightness<category_type>::position_enum }; scalar_type g = normalize_type::template process<lightness_p >( color_parameter.template get<lightness_p >() ); return diverse_type::template process<0>( g ); } } } #endif
[ "dmilos@gmail.com" ]
dmilos@gmail.com
8e3025d7f0a14946cee3b945754b95d4f0872eda
0c7ee2d3762f5537e27304cd66e3ed11a09276d6
/SRC/qosgabsolutemodeltransform.cpp
121599c429eb71214c5c97cc55515685ef5dc2bb
[]
no_license
codingman/osgQTWidget
2df469a2db0dca482dad37a96f0c6e314f5a7534
7b9b1a74b5bb3bf2a0dd90e1213ba80622ff0abe
refs/heads/master
2023-03-15T16:35:24.354807
2018-07-16T08:33:12
2018-07-16T08:33:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,936
cpp
#include "qosgabsolutemodeltransform.h" #include <osgUtil/CullVisitor> QOSGAbsoluteModelTransform::QOSGAbsoluteModelTransform(QObject *parent) : QObject(parent) { setReferenceFrame( osg::Transform::ABSOLUTE_RF ); } QOSGAbsoluteModelTransform::QOSGAbsoluteModelTransform( const osg::Matrix& m,QObject *parent ) : QObject(parent), _matrix( m ) { setReferenceFrame( osg::Transform::ABSOLUTE_RF ); } QOSGAbsoluteModelTransform::QOSGAbsoluteModelTransform( const QOSGAbsoluteModelTransform& rhs, const osg::CopyOp& copyop,QObject *parent ) : QObject(parent), osg::Transform( rhs, copyop ), _matrix( rhs._matrix ) { setReferenceFrame( osg::Transform::ABSOLUTE_RF ); } QOSGAbsoluteModelTransform::~QOSGAbsoluteModelTransform() { } bool QOSGAbsoluteModelTransform::computeLocalToWorldMatrix( osg::Matrix& matrix, osg::NodeVisitor* nv ) const { if( getReferenceFrame() == osg::Transform::ABSOLUTE_RF ) { osg::Matrix view; if( !nv ) osg::notify( osg::INFO ) << "AbsoluteModelTransform: NULL NodeVisitor; can't get view." << std::endl; else if( nv->getVisitorType() != osg::NodeVisitor::CULL_VISITOR ) osg::notify( osg::INFO ) << "AbsoluteModelTransform: NodeVisitor is not CullVisitor; can't get view." << std::endl; else { osgUtil::CullVisitor* cv = static_cast< osgUtil::CullVisitor* >( nv ); #ifdef SCENEVIEW_ANAGLYPHIC_STEREO_SUPPORT // If OSG_STEREO=ON is in the environment, SceneView hides the view matrix // in a stack rather than placing it in a Camera node. Enable this code // (using CMake) to use a less-efficient way to compute the view matrix that // is compatible with SceneView's usage. osg::NodePath np = nv->getNodePath(); np.pop_back(); osg::Matrix l2w = osg::computeLocalToWorld( np ); osg::Matrix invL2w = osg::Matrix::inverse( l2w ); view = invL2w * *( cv->getModelViewMatrix() ); #else // Faster way to determine the view matrix, but not compatible with // SceneView anaglyphic stereo. osg::Camera* cam = cv->getCurrentCamera(); cam->computeLocalToWorldMatrix( view, cv ); #endif } matrix = ( _matrix * view ); } else // RELATIVE_RF matrix.preMult(_matrix); return( true ); } bool QOSGAbsoluteModelTransform::computeWorldToLocalMatrix( osg::Matrix& matrix, osg::NodeVisitor* nv ) const { osg::Matrix inv( osg::Matrix::inverse( _matrix ) ); if( getReferenceFrame() == osg::Transform::ABSOLUTE_RF ) { osg::Matrix invView; if( !nv ) osg::notify( osg::NOTICE ) << "AbsoluteModelTransform: NULL NodeVisitor; can't get invView." << std::endl; else if( nv->getVisitorType() != osg::NodeVisitor::CULL_VISITOR ) osg::notify( osg::NOTICE ) << "AbsoluteModelTransform: NodeVisitor is not CullVisitor; can't get invView." << std::endl; else { osgUtil::CullVisitor* cv = static_cast< osgUtil::CullVisitor* >( nv ); #ifdef SCENEVIEW_ANAGLYPHIC_STEREO_SUPPORT // If OSG_STEREO=ON is in the environment, SceneView hides the view matrix // in a stack rather than placing it in a Camera node. Enable this code // (using CMake) to use a less-efficient way to compute the view matrix that // is compatible with SceneView's usage. osg::NodePath np = nv->getNodePath(); np.pop_back(); osg::Matrix l2w = osg::computeLocalToWorld( np ); invView = *( cv->getModelViewMatrix() ) * l2w; #else osg::Camera* cam = cv->getCurrentCamera(); cam->computeWorldToLocalMatrix( invView, cv ); #endif } matrix = ( invView * inv ); } else // RELATIVE_RF matrix.postMult( inv ); return( true ); }
[ "kangjie.wang@aqrose.com" ]
kangjie.wang@aqrose.com
6633a135158cb378d5a5b49bd8d729a9d2ba3630
de3b6cb3696b2b9f6a6c3568408d3889f12244ae
/libs/img/src/jpeglib/jerror.cpp
a4130281568399d8761dd5768de48e0c020b191b
[ "BSD-3-Clause", "IJG" ]
permissive
HitLumino/mrpt
a8cc3bf6e61b8e7478390de76f5caab3afd37e7b
827122befe5d7b20e1e36b0b34212b98087dd205
refs/heads/master
2021-04-15T05:24:30.519492
2018-03-27T08:44:56
2018-03-27T08:44:56
126,834,177
1
0
BSD-3-Clause
2018-03-26T13:36:55
2018-03-26T13:36:55
null
UTF-8
C++
false
false
7,517
cpp
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ #include "jinclude.h" #include "mrpt_jpeglib.h" #include "jversion.h" #include "jerror.h" #ifdef USE_WINDOWS_MESSAGEBOX #include <windows.h> #endif #ifndef EXIT_FAILURE /* define exit() codes if not provided */ #define EXIT_FAILURE 1 #endif /* * Create the message string table. * We do this from the master message list in jerror.h by re-reading * jerror.h with a suitable definition for macro JMESSAGE. * The message table is made an external symbol just in case any applications * want to refer to it directly. */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_std_message_table jMsgTable #endif #define JMESSAGE(code, string) string, const char* const jpeg_std_message_table[] = { #include "jerror.h" NULL}; /* * Error exit handler: must not return to caller. * * Applications may override this if they want to get control back after * an error. Typically one would longjmp somewhere instead of exiting. * The setjmp buffer can be made a private field within an expanded error * handler object. Note that the info needed to generate an error message * is stored in the error object, so you can generate the message now or * later, at your convenience. * You should make sure that the JPEG object is cleaned up (with jpeg_abort * or jpeg_destroy) at some point. */ METHODDEF(void) error_exit(j_common_ptr cinfo) { /* Always display the message */ (*cinfo->err->output_message)(cinfo); /* Let the memory manager delete any temp files before we die */ jpeg_destroy(cinfo); fprintf(stderr, "[jpeg::error_exit] critical error\n"); // exit(EXIT_FAILURE); } /* * Actual output of an error or trace message. * Applications may override this method to send JPEG messages somewhere * other than stderr. * * On Windows, printing to stderr is generally completely useless, * so we provide optional code to produce an error-dialog popup. * Most Windows applications will still prefer to override this routine, * but if they don't, it'll do something at least marginally useful. * * NOTE: to use the library in an environment that doesn't support the * C stdio library, you may have to delete the call to fprintf() entirely, * not just not use this routine. */ METHODDEF(void) output_message(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; /* Create the message */ (*cinfo->err->format_message)(cinfo, buffer); #ifdef USE_WINDOWS_MESSAGEBOX /* Display it in a message dialog box */ MessageBox( GetActiveWindow(), buffer, "JPEG Library Error", MB_OK | MB_ICONERROR); #else /* Send it to stderr, adding a newline */ fprintf(stderr, "%s\n", buffer); #endif } /* * Decide whether to emit a trace or warning message. * msg_level is one of: * -1: recoverable corrupt-data warning, may want to abort. * 0: important advisory messages (always display to user). * 1: first level of tracing detail. * 2,3,...: successively more detailed tracing messages. * An application might override this method if it wanted to abort on warnings * or change the policy about which messages to display. */ METHODDEF(void) emit_message(j_common_ptr cinfo, int msg_level) { struct jpeg_error_mgr* err = cinfo->err; if (msg_level < 0) { /* It's a warning message. Since corrupt files may generate many * warnings, * the policy implemented here is to show only the first warning, * unless trace_level >= 3. */ if (err->num_warnings == 0 || err->trace_level >= 3) (*err->output_message)(cinfo); /* Always count warnings in num_warnings. */ err->num_warnings++; } else { /* It's a trace message. Show it if trace_level >= msg_level. */ if (err->trace_level >= msg_level) (*err->output_message)(cinfo); } } /* * Format a message string for the most recent JPEG error or message. * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX * characters. Note that no '\n' character is added to the string. * Few applications should need to override this method. */ METHODDEF(void) format_message(j_common_ptr cinfo, char* buffer) { struct jpeg_error_mgr* err = cinfo->err; int msg_code = err->msg_code; const char* msgtext = nullptr; const char* msgptr; char ch; boolean isstring; /* Look up message string in proper table */ if (msg_code > 0 && msg_code <= err->last_jpeg_message) { msgtext = err->jpeg_message_table[msg_code]; } else if ( err->addon_message_table != nullptr && msg_code >= err->first_addon_message && msg_code <= err->last_addon_message) { msgtext = err->addon_message_table[msg_code - err->first_addon_message]; } /* Defend against bogus message number */ if (msgtext == nullptr) { err->msg_parm.i[0] = msg_code; msgtext = err->jpeg_message_table[0]; } /* Check for string parameter, as indicated by %s in the message text */ isstring = FALSE; msgptr = msgtext; while ((ch = *msgptr++) != '\0') { if (ch == '%') { if (*msgptr == 's') isstring = TRUE; break; } } /* Format the message into the passed buffer */ if (isstring) sprintf(buffer, msgtext, err->msg_parm.s); else sprintf( buffer, msgtext, err->msg_parm.i[0], err->msg_parm.i[1], err->msg_parm.i[2], err->msg_parm.i[3], err->msg_parm.i[4], err->msg_parm.i[5], err->msg_parm.i[6], err->msg_parm.i[7]); } /* * Reset error state variables at start of a new image. * This is called during compression startup to reset trace/error * processing to default state, without losing any application-specific * method pointers. An application might possibly want to override * this method if it has additional error processing state. */ METHODDEF(void) reset_error_mgr(j_common_ptr cinfo) { cinfo->err->num_warnings = 0; /* trace_level is not reset since it is an application-supplied parameter */ cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */ } /* * Fill in the standard error-handling methods in a jpeg_error_mgr object. * Typical call is: * struct jpeg_compress_struct cinfo; * struct jpeg_error_mgr err; * * cinfo.err = jpeg_std_error(&err); * after which the application may override some of the methods. */ GLOBAL(struct jpeg_error_mgr*) jpeg_std_error(struct jpeg_error_mgr* err) { err->error_exit = error_exit; err->emit_message = emit_message; err->output_message = output_message; err->format_message = format_message; err->reset_error_mgr = reset_error_mgr; err->trace_level = 0; /* default = no tracing */ err->num_warnings = 0; /* no warnings emitted yet */ err->msg_code = 0; /* may be useful as a flag for "no error" */ /* Initialize message table pointers */ err->jpeg_message_table = jpeg_std_message_table; err->last_jpeg_message = (int)JMSG_LASTMSGCODE - 1; err->addon_message_table = nullptr; err->first_addon_message = 0; /* for safety */ err->last_addon_message = 0; return err; }
[ "joseluisblancoc@gmail.com" ]
joseluisblancoc@gmail.com
9c1572368999ea52be1aadfd259c9ae7ced938af
40712dc426dfb114dfabe5913b0bfa08ab618961
/Extras/wxWidgets-2.9.0/include/wx/osx/dataobj.h
876cf0e78c0bbf2dd12d60eedc73c7d0641692ca
[]
no_license
erwincoumans/dynamica
7dc8e06966ca1ced3fc56bd3b655a40c38dae8fa
8b5eb35467de0495f43ed929d82617c21d2abecb
refs/heads/master
2021-01-17T05:53:34.958159
2015-02-10T18:34:11
2015-02-10T18:34:11
31,622,543
7
3
null
null
null
null
UTF-8
C++
false
false
1,488
h
/////////////////////////////////////////////////////////////////////////////// // Name: mac/dataobj.h // Purpose: declaration of the wxDataObject // Author: Stefan Csomor (adapted from Robert Roebling's gtk port) // Modified by: // Created: 10/21/99 // RCS-ID: $Id: dataobj.h 58168 2009-01-17 10:43:43Z SC $ // Copyright: (c) 1998, 1999 Vadim Zeitlin, Robert Roebling // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_MAC_DATAOBJ_H_ #define _WX_MAC_DATAOBJ_H_ // ---------------------------------------------------------------------------- // wxDataObject is the same as wxDataObjectBase under wxGTK // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxDataObject : public wxDataObjectBase { public: wxDataObject(); #ifdef __DARWIN__ virtual ~wxDataObject() { } #endif virtual bool IsSupportedFormat( const wxDataFormat& format, Direction dir = Get ) const; void AddToPasteboard( void * pasteboardRef , int itemID ); // returns true if the passed in format is present in the pasteboard static bool IsFormatInPasteboard( void * pasteboardRef, const wxDataFormat &dataFormat ); // returns true if any of the accepted formats of this dataobj is in the pasteboard bool HasDataInPasteboard( void * pasteboardRef ); bool GetFromPasteboard( void * pasteboardRef ); }; #endif // _WX_MAC_DATAOBJ_H_
[ "erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499" ]
erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499
c1e90eb0bd8a4cbe609e894b92e14e0c74dcf0b7
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/device/bluetooth/bluetooth_socket_bluez_unittest.cc
80585bc373b899143e4f8f5676b680b3a59dedd8
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
22,632
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_bluez.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_device_bluez.h" #include "device/bluetooth/bluetooth_socket.h" #include "device/bluetooth/bluetooth_socket_bluez.h" #include "device/bluetooth/bluetooth_socket_thread.h" #include "device/bluetooth/bluetooth_uuid.h" #include "device/bluetooth/dbus/bluez_dbus_manager.h" #include "device/bluetooth/dbus/fake_bluetooth_adapter_client.h" #include "device/bluetooth/dbus/fake_bluetooth_agent_manager_client.h" #include "device/bluetooth/dbus/fake_bluetooth_device_client.h" #include "device/bluetooth/dbus/fake_bluetooth_gatt_service_client.h" #include "device/bluetooth/dbus/fake_bluetooth_input_client.h" #include "device/bluetooth/dbus/fake_bluetooth_profile_manager_client.h" #include "device/bluetooth/dbus/fake_bluetooth_profile_service_provider.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" using device::BluetoothAdapter; using device::BluetoothDevice; using device::BluetoothSocket; using device::BluetoothSocketThread; using device::BluetoothUUID; namespace { void DoNothingDBusErrorCallback(const std::string& error_name, const std::string& error_message) {} } // namespace namespace bluez { class BluetoothSocketBlueZTest : public testing::Test { public: BluetoothSocketBlueZTest() : success_callback_count_(0), error_callback_count_(0), last_bytes_sent_(0), last_bytes_received_(0), last_reason_(BluetoothSocket::kSystemError) {} void SetUp() override { scoped_ptr<bluez::BluezDBusManagerSetter> dbus_setter = bluez::BluezDBusManager::GetSetterForTesting(); dbus_setter->SetBluetoothAdapterClient( scoped_ptr<bluez::BluetoothAdapterClient>( new bluez::FakeBluetoothAdapterClient)); dbus_setter->SetBluetoothAgentManagerClient( scoped_ptr<bluez::BluetoothAgentManagerClient>( new bluez::FakeBluetoothAgentManagerClient)); dbus_setter->SetBluetoothDeviceClient( scoped_ptr<bluez::BluetoothDeviceClient>( new bluez::FakeBluetoothDeviceClient)); dbus_setter->SetBluetoothGattServiceClient( scoped_ptr<bluez::BluetoothGattServiceClient>( new bluez::FakeBluetoothGattServiceClient)); dbus_setter->SetBluetoothInputClient( scoped_ptr<bluez::BluetoothInputClient>( new bluez::FakeBluetoothInputClient)); dbus_setter->SetBluetoothProfileManagerClient( scoped_ptr<bluez::BluetoothProfileManagerClient>( new bluez::FakeBluetoothProfileManagerClient)); BluetoothSocketThread::Get(); // Grab a pointer to the adapter. device::BluetoothAdapterFactory::GetAdapter(base::Bind( &BluetoothSocketBlueZTest::AdapterCallback, base::Unretained(this))); base::MessageLoop::current()->Run(); ASSERT_TRUE(adapter_.get() != nullptr); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); // Turn on the adapter. adapter_->SetPowered(true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } void TearDown() override { adapter_ = nullptr; BluetoothSocketThread::CleanupForTesting(); bluez::BluezDBusManager::Shutdown(); } void AdapterCallback(scoped_refptr<BluetoothAdapter> adapter) { adapter_ = adapter; if (base::MessageLoop::current() && base::MessageLoop::current()->is_running()) { base::MessageLoop::current()->QuitWhenIdle(); } } void SuccessCallback() { ++success_callback_count_; message_loop_.QuitWhenIdle(); } void ErrorCallback(const std::string& message) { ++error_callback_count_; last_message_ = message; if (message_loop_.is_running()) message_loop_.QuitWhenIdle(); } void ConnectToServiceSuccessCallback(scoped_refptr<BluetoothSocket> socket) { ++success_callback_count_; last_socket_ = socket; message_loop_.QuitWhenIdle(); } void SendSuccessCallback(int bytes_sent) { ++success_callback_count_; last_bytes_sent_ = bytes_sent; message_loop_.QuitWhenIdle(); } void ReceiveSuccessCallback(int bytes_received, scoped_refptr<net::IOBuffer> io_buffer) { ++success_callback_count_; last_bytes_received_ = bytes_received; last_io_buffer_ = io_buffer; message_loop_.QuitWhenIdle(); } void ReceiveErrorCallback(BluetoothSocket::ErrorReason reason, const std::string& error_message) { ++error_callback_count_; last_reason_ = reason; last_message_ = error_message; message_loop_.QuitWhenIdle(); } void CreateServiceSuccessCallback(scoped_refptr<BluetoothSocket> socket) { ++success_callback_count_; last_socket_ = socket; if (message_loop_.is_running()) message_loop_.QuitWhenIdle(); } void AcceptSuccessCallback(const BluetoothDevice* device, scoped_refptr<BluetoothSocket> socket) { ++success_callback_count_; last_device_ = device; last_socket_ = socket; message_loop_.QuitWhenIdle(); } void ImmediateSuccessCallback() { ++success_callback_count_; } protected: base::MessageLoop message_loop_; scoped_refptr<BluetoothAdapter> adapter_; unsigned int success_callback_count_; unsigned int error_callback_count_; std::string last_message_; scoped_refptr<BluetoothSocket> last_socket_; int last_bytes_sent_; int last_bytes_received_; scoped_refptr<net::IOBuffer> last_io_buffer_; BluetoothSocket::ErrorReason last_reason_; const BluetoothDevice* last_device_; }; TEST_F(BluetoothSocketBlueZTest, Connect) { BluetoothDevice* device = adapter_->GetDevice( bluez::FakeBluetoothDeviceClient::kPairedDeviceAddress); ASSERT_TRUE(device != nullptr); device->ConnectToService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), base::Bind(&BluetoothSocketBlueZTest::ConnectToServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the socket for the remainder of the test. scoped_refptr<BluetoothSocket> socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Send data to the socket, expect all of the data to be sent. scoped_refptr<net::StringIOBuffer> write_buffer( new net::StringIOBuffer("test")); socket->Send(write_buffer.get(), write_buffer->size(), base::Bind(&BluetoothSocketBlueZTest::SendSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_EQ(last_bytes_sent_, write_buffer->size()); success_callback_count_ = 0; error_callback_count_ = 0; // Receive data from the socket, and fetch the buffer from the callback; since // the fake is an echo server, we expect to receive what we wrote. socket->Receive(4096, base::Bind(&BluetoothSocketBlueZTest::ReceiveSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ReceiveErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_EQ(4, last_bytes_received_); EXPECT_TRUE(last_io_buffer_.get() != nullptr); // Take ownership of the received buffer. scoped_refptr<net::IOBuffer> read_buffer = last_io_buffer_; last_io_buffer_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; std::string data = std::string(read_buffer->data(), last_bytes_received_); EXPECT_EQ("test", data); read_buffer = nullptr; // Receive data again; the socket will have been closed, this should cause a // disconnected error to be returned via the error callback. socket->Receive(4096, base::Bind(&BluetoothSocketBlueZTest::ReceiveSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ReceiveErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(0U, success_callback_count_); EXPECT_EQ(1U, error_callback_count_); EXPECT_EQ(BluetoothSocket::kDisconnected, last_reason_); EXPECT_EQ(net::ErrorToString(net::OK), last_message_); success_callback_count_ = 0; error_callback_count_ = 0; // Send data again; since the socket is closed we should get a system error // equivalent to the connection reset error. write_buffer = new net::StringIOBuffer("second test"); socket->Send(write_buffer.get(), write_buffer->size(), base::Bind(&BluetoothSocketBlueZTest::SendSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(0U, success_callback_count_); EXPECT_EQ(1U, error_callback_count_); EXPECT_EQ(net::ErrorToString(net::ERR_CONNECTION_RESET), last_message_); success_callback_count_ = 0; error_callback_count_ = 0; // Close our end of the socket. socket->Disconnect(base::Bind(&BluetoothSocketBlueZTest::SuccessCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); } TEST_F(BluetoothSocketBlueZTest, Listen) { adapter_->CreateRfcommService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), BluetoothAdapter::ServiceOptions(), base::Bind(&BluetoothSocketBlueZTest::CreateServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the socket for the remainder of the test. scoped_refptr<BluetoothSocket> server_socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Simulate an incoming connection by just calling the ConnectProfile method // of the underlying fake device client (from the BlueZ point of view, // outgoing and incoming look the same). // // This is done before the Accept() call to simulate a pending call at the // point that Accept() is called. bluez::FakeBluetoothDeviceClient* fake_bluetooth_device_client = static_cast<bluez::FakeBluetoothDeviceClient*>( bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()); BluetoothDevice* device = adapter_->GetDevice( bluez::FakeBluetoothDeviceClient::kPairedDeviceAddress); ASSERT_TRUE(device != nullptr); fake_bluetooth_device_client->ConnectProfile( static_cast<BluetoothDeviceBlueZ*>(device)->object_path(), bluez::FakeBluetoothProfileManagerClient::kRfcommUuid, base::Bind(&base::DoNothing), base::Bind(&DoNothingDBusErrorCallback)); message_loop_.RunUntilIdle(); server_socket->Accept( base::Bind(&BluetoothSocketBlueZTest::AcceptSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the client socket for the remainder of the test. scoped_refptr<BluetoothSocket> client_socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Close our end of the client socket. client_socket->Disconnect(base::Bind( &BluetoothSocketBlueZTest::SuccessCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); client_socket = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Run a second connection test, this time calling Accept() before the // incoming connection comes in. server_socket->Accept( base::Bind(&BluetoothSocketBlueZTest::AcceptSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.RunUntilIdle(); fake_bluetooth_device_client->ConnectProfile( static_cast<BluetoothDeviceBlueZ*>(device)->object_path(), bluez::FakeBluetoothProfileManagerClient::kRfcommUuid, base::Bind(&base::DoNothing), base::Bind(&DoNothingDBusErrorCallback)); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the client socket for the remainder of the test. client_socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Close our end of the client socket. client_socket->Disconnect(base::Bind( &BluetoothSocketBlueZTest::SuccessCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); client_socket = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Now close the server socket. server_socket->Disconnect( base::Bind(&BluetoothSocketBlueZTest::ImmediateSuccessCallback, base::Unretained(this))); message_loop_.RunUntilIdle(); EXPECT_EQ(1U, success_callback_count_); } TEST_F(BluetoothSocketBlueZTest, ListenBeforeAdapterStart) { // Start off with an invisible adapter, register the profile, then make // the adapter visible. bluez::FakeBluetoothAdapterClient* fake_bluetooth_adapter_client = static_cast<bluez::FakeBluetoothAdapterClient*>( bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()); fake_bluetooth_adapter_client->SetVisible(false); adapter_->CreateRfcommService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), BluetoothAdapter::ServiceOptions(), base::Bind(&BluetoothSocketBlueZTest::CreateServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the socket for the remainder of the test. scoped_refptr<BluetoothSocket> socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // But there shouldn't be a profile registered yet. bluez::FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client = static_cast<bluez::FakeBluetoothProfileManagerClient*>( bluez::BluezDBusManager::Get() ->GetBluetoothProfileManagerClient()); bluez::FakeBluetoothProfileServiceProvider* profile_service_provider = fake_bluetooth_profile_manager_client->GetProfileServiceProvider( bluez::FakeBluetoothProfileManagerClient::kRfcommUuid); EXPECT_TRUE(profile_service_provider == nullptr); // Make the adapter visible. This should register a profile. fake_bluetooth_adapter_client->SetVisible(true); message_loop_.RunUntilIdle(); profile_service_provider = fake_bluetooth_profile_manager_client->GetProfileServiceProvider( bluez::FakeBluetoothProfileManagerClient::kRfcommUuid); EXPECT_TRUE(profile_service_provider != nullptr); // Cleanup the socket. socket->Disconnect( base::Bind(&BluetoothSocketBlueZTest::ImmediateSuccessCallback, base::Unretained(this))); message_loop_.RunUntilIdle(); EXPECT_EQ(1U, success_callback_count_); } TEST_F(BluetoothSocketBlueZTest, ListenAcrossAdapterRestart) { // The fake adapter starts off visible by default. bluez::FakeBluetoothAdapterClient* fake_bluetooth_adapter_client = static_cast<bluez::FakeBluetoothAdapterClient*>( bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()); adapter_->CreateRfcommService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), BluetoothAdapter::ServiceOptions(), base::Bind(&BluetoothSocketBlueZTest::CreateServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take ownership of the socket for the remainder of the test. scoped_refptr<BluetoothSocket> socket = last_socket_; last_socket_ = nullptr; success_callback_count_ = 0; error_callback_count_ = 0; // Make sure the profile was registered with the daemon. bluez::FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client = static_cast<bluez::FakeBluetoothProfileManagerClient*>( bluez::BluezDBusManager::Get() ->GetBluetoothProfileManagerClient()); bluez::FakeBluetoothProfileServiceProvider* profile_service_provider = fake_bluetooth_profile_manager_client->GetProfileServiceProvider( bluez::FakeBluetoothProfileManagerClient::kRfcommUuid); EXPECT_TRUE(profile_service_provider != nullptr); // Make the adapter invisible, and fiddle with the profile fake to unregister // the profile since this doesn't happen automatically. fake_bluetooth_adapter_client->SetVisible(false); message_loop_.RunUntilIdle(); // Then make the adapter visible again. This should re-register the profile. fake_bluetooth_adapter_client->SetVisible(true); message_loop_.RunUntilIdle(); profile_service_provider = fake_bluetooth_profile_manager_client->GetProfileServiceProvider( bluez::FakeBluetoothProfileManagerClient::kRfcommUuid); EXPECT_TRUE(profile_service_provider != nullptr); // Cleanup the socket. socket->Disconnect( base::Bind(&BluetoothSocketBlueZTest::ImmediateSuccessCallback, base::Unretained(this))); message_loop_.RunUntilIdle(); EXPECT_EQ(1U, success_callback_count_); } TEST_F(BluetoothSocketBlueZTest, PairedConnectFails) { BluetoothDevice* device = adapter_->GetDevice( bluez::FakeBluetoothDeviceClient::kPairedUnconnectableDeviceAddress); ASSERT_TRUE(device != nullptr); device->ConnectToService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), base::Bind(&BluetoothSocketBlueZTest::ConnectToServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(0U, success_callback_count_); EXPECT_EQ(1U, error_callback_count_); EXPECT_TRUE(last_socket_.get() == nullptr); device->ConnectToService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), base::Bind(&BluetoothSocketBlueZTest::ConnectToServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(0U, success_callback_count_); EXPECT_EQ(2U, error_callback_count_); EXPECT_TRUE(last_socket_.get() == nullptr); } TEST_F(BluetoothSocketBlueZTest, SocketListenTwice) { adapter_->CreateRfcommService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), BluetoothAdapter::ServiceOptions(), base::Bind(&BluetoothSocketBlueZTest::CreateServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(0U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take control of this socket. scoped_refptr<BluetoothSocket> server_socket; server_socket.swap(last_socket_); server_socket->Accept( base::Bind(&BluetoothSocketBlueZTest::AcceptSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); server_socket->Close(); server_socket = nullptr; message_loop_.RunUntilIdle(); EXPECT_EQ(1U, success_callback_count_); EXPECT_EQ(1U, error_callback_count_); adapter_->CreateRfcommService( BluetoothUUID(bluez::FakeBluetoothProfileManagerClient::kRfcommUuid), BluetoothAdapter::ServiceOptions(), base::Bind(&BluetoothSocketBlueZTest::CreateServiceSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); message_loop_.Run(); EXPECT_EQ(2U, success_callback_count_); EXPECT_EQ(1U, error_callback_count_); EXPECT_TRUE(last_socket_.get() != nullptr); // Take control of this socket. server_socket.swap(last_socket_); server_socket->Accept( base::Bind(&BluetoothSocketBlueZTest::AcceptSuccessCallback, base::Unretained(this)), base::Bind(&BluetoothSocketBlueZTest::ErrorCallback, base::Unretained(this))); server_socket->Close(); server_socket = nullptr; message_loop_.RunUntilIdle(); EXPECT_EQ(2U, success_callback_count_); EXPECT_EQ(2U, error_callback_count_); } } // namespace bluez
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
de3a488d7b1da745e08ff6dc80fd5b4d02016ee5
614911fac5e9c6c4932123db4ec2b2f60e2c8e31
/polymorphism/regular_polymorphism/shapes_drawer.cpp
3825329fe5e18220533b2af132b96239fa773ce8
[ "Apache-2.0" ]
permissive
google/cpp-from-the-sky-down
9460e76e71c8b36f698ccc7959cf1386f3fc2f38
0d4417f574be620d1d97184997a036f1e8d6408a
refs/heads/master
2023-08-30T15:57:28.476415
2022-06-07T00:02:12
2022-06-07T00:02:12
144,897,672
247
36
Apache-2.0
2023-04-13T17:28:08
2018-08-15T19:59:21
HTML
UTF-8
C++
false
false
144
cpp
#include "shapes_drawer.hpp" void draw_shapes(const std::vector<my_shapes::shape>& shapes) { for (const auto& shape : shapes) shape.draw(); }
[ "jbandela@ad.corp.google.com" ]
jbandela@ad.corp.google.com
a13d5ed969d00a49e828fda2356f71a632d7b71a
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/11_2785_18.cpp
ab3654f4eae1720f73bfcf78b5c450dbeb2990d8
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
cpp
// A.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<cstdlib> #include<cstdio> #include<iostream> #include<string> #include<conio.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int n,nop,*a,x,flag=0; float low,high; freopen("A.in","rt",stdin); freopen("A.out","wt",stdout); cin>>n; for(int i=0;i<n;i++) { flag=0; cin>>nop>>low>>high; a = new int[nop]; for(int k=0;k<nop;k++) cin>>a[k]; x=low; for( ;x<=high;x++) { for(int k=0;k<nop;k++) { if((x%a[k]!=0)&&(a[k]%x!=0)) { flag=1; break; } } if(flag==0) break; else { flag=0; continue; } } if(flag==0) cout<<"Case #"<<(i+1)<<": "<<x<<endl; else cout<<"Case #"<<(i+1)<<": "<<"NO"<<endl; } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
24048a7b72dd8d138c54738ed3986c33c1490b8c
3a30fefcb893e3a0f1b40a46f57f3d50376d868d
/client-qt/fpv_service.cpp
635f3a265b8652685ad81b302a0b2c42d212dde0
[]
no_license
ming4883/mkart
7d2640797fa319782a100e8472bb8986597789b0
6489abe7949967215c277a085d3748cd31359815
refs/heads/master
2021-09-01T06:34:00.942782
2017-12-24T05:06:04
2017-12-24T05:06:04
115,331,734
0
0
null
null
null
null
UTF-8
C++
false
false
7,375
cpp
#include "fpv_service.h" #include "timing.h" #include <QtNetwork> #include <QOpenGLTexture> #include <QOpenGLPixelTransferOptions> class FpvContext : public QObject { //Q_OBJECT public: Tcp m_tcp; QOpenGLTexture* m_tex; bool m_capture; float m_last_recv_time; float m_avg_recv_time; FpvContext() : m_tex(nullptr), m_capture(false), m_last_recv_time(0), m_avg_recv_time(0) { } void init() { m_tex = nullptr; m_tcp.init(); m_capture = false; m_last_recv_time = current_time_in_ms(); } void update() { m_tcp.update(); void* msg_ptr; unsigned int msg_len; if (m_tcp.read_message(msg_ptr, msg_len)) { if (is_4cc(msg_ptr, 'J', 'P', 'E', 'G')) { on_recieve_jpeg(((char*)msg_ptr) + 4, msg_len - 4); } } } bool is_4cc(void* in_ptr, char in_a, char in_b, char in_c, char in_d) { char* c = (char*)in_ptr; return c[0] == in_a && c[1] == in_b && c[2] == in_c && c[3] == in_d; } void on_recieve_jpeg(void* in_ptr, unsigned int in_len) { //qDebug() << "Image recieved"; //m_img = new QImage(256, 128, QImage::Format_RGBA8888); //fill_test_pattern(); // update the statistics float recv_time = current_time_in_ms(); float delta_recv_time = recv_time - m_last_recv_time; if (0 == m_avg_recv_time) { m_avg_recv_time = delta_recv_time; } else { m_avg_recv_time = (m_avg_recv_time + delta_recv_time) * 0.5f; } m_last_recv_time = recv_time; // decode QImage loaded = QImage::fromData(reinterpret_cast<uchar*>(in_ptr), (int)in_len); if(loaded.isNull()) return; loaded = loaded.convertToFormat(QImage::Format_RGBA8888); if (nullptr == m_tex) { m_tex = new QOpenGLTexture(loaded, QOpenGLTexture::DontGenerateMipMaps); m_tex->setMinificationFilter(QOpenGLTexture::Nearest); m_tex->setMagnificationFilter(QOpenGLTexture::Linear); m_tex->setWrapMode(QOpenGLTexture::ClampToEdge); } else { QOpenGLPixelTransferOptions uploadOptions; uploadOptions.setAlignment(1); m_tex->setData(0, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, (const void*)loaded.constBits(), &uploadOptions); } } Tcp::Result set_capturing(bool in_enabled) { m_capture = in_enabled; const char* msg_true = "v4l2_set_capturing(true);"; const char* msg_false = "v4l2_set_capturing(false);"; const char* msg = in_enabled ? msg_true : msg_false; return m_tcp.send_raw(msg, strlen(msg)); } Tcp::Result remote_exit() { const char* msg = "exit();"; return m_tcp.send_raw(msg, strlen(msg)); } void shutdown() { m_tcp.shutdown(); //delete m_img; delete m_tex; } unsigned int get_texture_id() { if(nullptr == m_tex) return 0; return m_tex->textureId(); } unsigned int get_texture_width() { if(nullptr == m_tex) return 0; return (unsigned int)m_tex->width(); } unsigned int get_texture_height() { if(nullptr == m_tex) return 0; return (unsigned int)m_tex->height(); } }; FpvContext g_fpv_context; void FpvService::init() { g_fpv_context.init(); } void FpvService::update() { g_fpv_context.update(); } void FpvService::shutdown() { g_fpv_context.shutdown(); } Tcp::State FpvService::get_state() { return g_fpv_context.m_tcp.get_state(); } Tcp::Result FpvService::disconnect() { return g_fpv_context.m_tcp.disconnect(); } Tcp::Result FpvService::connect(unsigned char in_ip[4], int in_port) { auto ret = g_fpv_context.m_tcp.connect(in_ip, in_port); if (ret == Tcp::ret_succeeded) { set_capturing(g_fpv_context.m_capture); } return ret; } bool FpvService::is_capturing() { return g_fpv_context.m_capture; } void FpvService::set_capturing(bool in_capture) { g_fpv_context.set_capturing(in_capture); } void FpvService::remote_exit() { g_fpv_context.remote_exit(); } unsigned int FpvService::get_texture_id() { return g_fpv_context.get_texture_id(); } unsigned int FpvService::get_texture_width() { return g_fpv_context.get_texture_width(); } unsigned int FpvService::get_texture_height() { return g_fpv_context.get_texture_height(); } float FpvService::get_avg_recv_time() { return g_fpv_context.m_avg_recv_time; } #if 0 #include <vpx/vpx_encoder.h> #include <vpx/vpx_decoder.h> #include <vpx/vp8cx.h> #define VP9_FOURCC 0x30395056 QImage* m_img; vpx_codec_ctx_t codec; bool vpx_init(unsigned int in_w, unsigned int in_h) { vpx_codec_err_t res; vpx_codec_enc_cfg_t cfg; res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), &cfg, 0); if (res) return false; cfg.g_w = in_w; cfg.g_h = in_h; cfg.g_timebase.num = 1;//info.time_base.numerator; cfg.g_timebase.den = 15;//info.time_base.denominator; cfg.rc_target_bitrate = 100;//kilobits per second cfg.g_error_resilient = (vpx_codec_er_flags_t)0;//strtoul(argv[7], NULL, 0); res = vpx_codec_enc_init(&codec, vpx_codec_vp9_cx(), &cfg, 0); if (res) return false; return true; } int vpx_encode_frame(vpx_image_t *img, int frame_index, int flags) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(&codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) return -1; while ((pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; //if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, // pkt->data.frame.sz, // pkt->data.frame.pts)) { // die_codec(codec, "Failed to write compressed frame"); //} //printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; } void fill_test_pattern() { // QImage::Format_RGBA8888 // The order of the colors is the same on any architecture if read as bytes 0xRR,0xGG,0xBB,0xAA. int bval = (int)(current_time_in_ms() * 0.25f) % 255; for(int y = 0; y < m_img->height(); ++y) { uchar* scan = m_img->scanLine(y); for(int x = 0; x < m_img->width(); ++x) { uchar* p = &scan[x * 4]; uchar* r = p++; uchar* g = p++; uchar* b = p++; uchar* a = p++; *r = x; *g = y; *b = bval; *a = 255; } } } #endif
[ "ming4883@hotmail.com" ]
ming4883@hotmail.com
71763b415cb24d6cc30679645e68b40c43403d12
f22ebc1404ee597fecbb08ecba4bc01f7fbb0150
/ch01/exercise1.9.cpp
dd934a8df61feaf10b38e5500c05e6edfba87cff
[]
no_license
matriiix67/cpp-primer
ccb3bd12771488090121d0f336cbb4bfd825f058
ee10f444ecfb66c5dcf9b88a6af3766f98f152ed
refs/heads/master
2021-01-21T04:44:31.816805
2018-04-02T10:15:00
2018-04-02T10:15:00
45,467,049
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include <iostream> int main(int argc, char *argv[]) { int sum = 0, val = 50; while (val <= 100) { sum += val; ++val; } std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl; return 0; }
[ "matriiix67@gmail.com" ]
matriiix67@gmail.com
e1ae2f12cda17e23ca59ab7efcbe747573e7a4c9
0d11203e6a143b2383b5baa8a9a2b3e48383c9b1
/DSA01018.cpp
41c34cddce08f33c403d43a541bf7be7353bdcbb
[]
no_license
namnguyen215/CTDLGT
c36b8526b3af00ea2d4bd113efe378f95091f895
6e7e602940fb5c28b7af830f44f58443375b7666
refs/heads/main
2023-06-25T08:48:47.269848
2021-07-21T16:36:36
2021-07-21T16:36:36
360,927,428
2
1
null
null
null
null
UTF-8
C++
false
false
626
cpp
#include<bits/stdc++.h> using namespace std; void sinh(int a[],int n, int k) { int i=k; while(a[i]==a[i-1]+1) i--; if(i>0) { a[i]--; for(int j=i+1;j<=k;j++) a[j]=n-k+j; } else { for(int j=1;j<=k;j++) a[j]=n-k+j; } } void print(int a[],int k) { for(int i=1;i<=k;i++) cout<<a[i]<<" "; cout<<endl; } int main() { int t;cin>>t; while(t--) { int n,k; cin>>n>>k; int a[k+7]={0}; for(int i=1;i<=k;i++) cin>>a[i]; sinh(a,n,k); print(a,k); } }
[ "namnguyenphuong215@gmail.com" ]
namnguyenphuong215@gmail.com
81e5b7fac2c85b9050cd6ecfc400180cb0c24bb7
e5694cdc45c5eb77f699bdccff936f341d0e87e2
/a/zdr/ZSEMail.cpp
8f9f9cfeb18569ee20c9a7001d3f34cf128d55ec
[]
no_license
arksoftgit/10d
2bee2f20d78dccf0b5401bb7129494499a3c547d
4940b9473beebfbc2f4d934fc013b86aa32f5887
refs/heads/master
2020-04-16T02:26:52.876019
2017-10-10T20:27:34
2017-10-10T20:27:34
49,138,607
0
3
null
2016-08-29T13:03:58
2016-01-06T14:02:53
C
UTF-8
C++
false
false
49,160
cpp
// ZSEM.cpp : Defines the initialization routines for the DLL. // #define KZSYSSVC_INCL #include "KZOENGAA.H" #include "ZDrvrOpr.h" #include <winsock2.h> // includes windows.h #include <time.h> #include <iostream> #include <io.h> #include <tchar.h> #include "zsemail.h" #pragma warning(disable: 4996) // This function or variable may be unsafe // Default empty constructor. FormattedDate::FormattedDate( ) { } // Default empty destructor. FormattedDate::~FormattedDate( ) { } // Returns _TCHAR * string formatted as follows: // Date: Sun, 22 Feb, 2004 16:21:45 -0700 zBOOL FormattedDate::GetFormattedDate( _TCHAR *ptcDateTime ) { SYSTEMTIME systemtime; SYSTEMTIME localtime; // _TCHAR *ptcDateTime = new _TCHAR[ 128 ]; _TCHAR *ptcMonth[] = { "No Month", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; _TCHAR *ptcDay[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // memset( ptcDateTime, 0, zsizeof( _TCHAR ) * 128 ); // "Date: Tue, 30 Dec 2003 23:59:00 +0000 ptcDateTime[ 0 ] = 0; GetSystemTime( &systemtime ); zBOOL bRC = SystemTimeToTzSpecificLocalTime( NULL, &systemtime, &localtime ); _stprintf( ptcDateTime, _T( "Date: %s, %02d %s, %4d %02d:%02d:%02d -0700" ), ptcDay[ localtime.wDayOfWeek ], localtime.wDay, ptcMonth[ localtime.wMonth ], localtime.wYear, localtime.wHour, localtime.wMinute, localtime.wSecond ); // return( ptcDateTime ); return( bRC ); } zOPER_EXPORT zLONG OPERATION CreateSmtpConnection( zPCHAR pchSmtpServer ) { Smtp *pSmtp = new Smtp; if ( pSmtp->CreateSmtpConnection( pchSmtpServer ) == FALSE ) { delete( pSmtp ); pSmtp = 0; } return( (zLONG) pSmtp ); } zOPER_EXPORT zSHORT OPERATION CreateSmtpMessage( zLONG lSmtpConnection, zPCHAR pchSmtpServer, zPCHAR pchSender, zPCHAR pchRecipient, zLONG lRecipientCnt, zPCHAR pchSubject, zLONG lMimeType, // 1 - text; 2 - html zPCHAR pchBody, zLONG lHasAttachment, // 0 - No; 1 - Yes zPCHAR pchAttachFile, zPCHAR pchUserName, zPCHAR pchPassword ) { TraceLine( "CreateSmtpMessage Server: %s Sender: %s Recipient: %s" " Recipient Cnt: %d Subject: %s Mime Type: %d" " User: %s Password %s", pchSmtpServer, pchSender, pchRecipient, lRecipientCnt, pchSubject, lMimeType, pchUserName, "******" ); // pchPassword ); Smtp *pSmtp = (Smtp *) lSmtpConnection; if ( pSmtp ) { zPCHAR *ppchToArray = (zPCHAR *) new char[ sizeof( zPCHAR ) * lRecipientCnt ]; if ( lRecipientCnt == 1 ) { ppchToArray[ 0 ] = pchRecipient; } else { zPCHAR pch = pchRecipient; zLONG lCnt = 0; while ( lCnt < lRecipientCnt ) { ppchToArray[ lCnt ] = pch; pch += zstrlen( pch ) + 1; } } zSHORT nRC = pSmtp->CreateSmtpMessage( pchSmtpServer, pchSender, ppchToArray, lRecipientCnt, pchSubject, lMimeType, // text pchBody, lHasAttachment, pchAttachFile, pchUserName, pchPassword ); delete [] ppchToArray; return( nRC ); } else { return( -1 ); } } zOPER_EXPORT zVOID OPERATION CloseSmtpConnection( zLONG lSmtpConnection ) { Smtp *pSmtp = (Smtp *) lSmtpConnection; if ( pSmtp ) delete( pSmtp ); } ///////////////////////////////////////////////////////////////////////////// // // URL NOTATION // Summary of the separator characters and other special notation that can // appear in a URL. // // Special Notation in a URL Notation Meaning // ? Appears just after the email address, separating it fromthe first // name/value pair. // = Separates each name and value, in the form name=value. // & Separates name/value pairs, as in name1=value1&name2=value2. // % Precedes an ASCII character code in hexadecimal, in the form %xx, as // a way of representing that character. For example,%0A represents a // newline (line feed) character. See more on hex encoding below. // + Another way to represent a space. For example, the value Bjorn Free // could appear in the URL as Bjorn+Free. // // In JavaScript, you can hex-encode a string - that is, substitute the // %xx notation for all characters other than letters and numbers (and // a few special characters) - by using the escape() function, as follows: // // var myString = "Odds & ends for tonight!" // var myEncodedText = escape( myString ); // // This code puts the following value in the variable myEncodedText: // // Odds%20%26%20ends%20for%20tonight%21 // // Notice that the spaces, ampersand, and exclamation point have been // converted to their ASCII character code equivalents: %20,%26,and %21, // respectively. Without hex encoding, this string couldnot be used as // a subject value in a URL, because the ampersand would be interpreted // as a separator between name/value pairs. // // Be sure to hex-encode only the subject and message body values in a // mailto URL. Although the escape() function will not encode letters or // numbers (or the characters * @ - _ + . /), it will encode the? and & // separator characters, which would mess up your URL. // ///////////////////////////////////////////////////////////////////////////// void encode64( zPCHAR pchTgt, zCPCHAR cpcSrc ) { static zPCHAR Base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int nIdx = 0; int nLth = zstrlen( cpcSrc ); int k; for ( k = 0 ; k < nLth ; k += 3 ) { unsigned int uBuffer; uBuffer = ((unsigned char *) cpcSrc)[ k ] << 16; if ( k + 1 < nLth ) uBuffer |= ((unsigned char *) cpcSrc)[ k + 1 ] << 8; if ( k + 2 < nLth ) uBuffer |= ((unsigned char *) cpcSrc)[ k + 2 ]; pchTgt[ nIdx++ ] = Base64Digits[ (uBuffer >> 18) % 64 ]; pchTgt[ nIdx++ ] = Base64Digits[ (uBuffer >> 12) % 64 ]; if ( k + 1 < nLth ) pchTgt[ nIdx++ ] = Base64Digits[ (uBuffer >> 6) % 64 ]; else pchTgt[ nIdx++ ] = '='; if ( k + 2 < nLth ) pchTgt[ nIdx++ ] = Base64Digits[ uBuffer % 64 ]; else pchTgt[ nIdx++ ] = '='; } pchTgt[ nIdx++ ] = 0; } // Default constructor Smtp::Smtp( ) { WSADATA wsaData; WORD wVersionRequested = MAKEWORD( 2, 2 ); m_SA = 0; m_lCount = 1; m_bEhloNotSent = TRUE; WSAStartup( wVersionRequested, &wsaData ); m_lBufferLth = 32768; m_ptcBuffer = new char[ sizeof( _TCHAR ) * m_lBufferLth ]; } // Default destructor Smtp::~Smtp( ) { if ( m_SA ) { SendRecv( "QUIT", "\r\n" ); ::Sleep( 1000 ); INT iErr = shutdown( m_SA, SD_SEND ); if ( iErr == SOCKET_ERROR ) INT iLastError = WSAGetLastError(); for ( ; ; ) { INT iRC = recv( m_SA, m_ptcBuffer, m_lBufferLth, 0 ); if ( iRC == 0 || iRC == SOCKET_ERROR ) break; } iErr = closesocket( m_SA ); if ( iErr == SOCKET_ERROR ) INT iLastError = WSAGetLastError(); } WSACleanup( ); m_SA = 0; m_bEhloNotSent = FALSE; mDeleteInitA( m_ptcBuffer ); } // Create a new smtp server connection // Name of your smtp server zBOOL Smtp::CreateSmtpConnection( zPCHAR pchSmtpServer ) { // Use DNS to resolve address of smtp server. struct hostent *heHostent = gethostbyname( pchSmtpServer ); struct in_addr inaddr; struct sockaddr_in sockaddrSend; inaddr.s_addr = *((unsigned long *) heHostent->h_addr_list[ 0 ]); zPCHAR cpIpAddr = inet_ntoa( inaddr ); // create a new socket for to connect to the Comcast's SMTP server m_SA = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); sockaddrSend.sin_family = AF_INET; sockaddrSend.sin_addr.s_addr = inet_addr( cpIpAddr ); sockaddrSend.sin_port = htons( 25 ); // Attempt up to 5 connections to the webserver. INT err; for ( zLONG lRetry = 0; lRetry < 5; lRetry++ ) { err = connect( m_SA, (struct sockaddr *) &sockaddrSend, sizeof( sockaddr_in ) ); if ( err != SOCKET_ERROR ) { break; } } // If connect failed print message and exit. if ( err == SOCKET_ERROR ) { // printf( "Connect error: %d\n", WSAGetLastError() ); TraceLineI( "Smtp::CreateSmtpConnection Connect Error: ", WSAGetLastError() ); return( FALSE ); } return( TRUE ); } BOOL Smtp::prepare_header() { if ( !Send( "MIME-nVersion: 1.0", "\r\n" ) ) return( FALSE ); return( TRUE ); } BOOL Smtp::insert_mixed_part() { if ( !Send( "Content-Type: multipart/mixed; boundary=\"MessagePartBoundry\"", "\r\n" ) ) { return( FALSE ); } return( TRUE ); } BOOL Smtp::insert_html_part() { if ( !Send( "Content-Type: text/html; charset=US-ASCII", "\r\n" ) ) return( FALSE ); return( TRUE ); } BOOL Smtp::insert_text_part() { if ( !Send( "Content-Type: text/plain; charset=US-ASCII", "\r\n" ) ) return( FALSE ); return( TRUE ); } BOOL Smtp::insert_boundry() { if ( !Send( "\r\n" ) ) return( FALSE ); if ( !Send( "--MessagePartBoundry", "\r\n" ) ) return( FALSE ); return( TRUE ); } BOOL Smtp::insert_end_boundry() { if ( !Send( "\r\n" ) ) return( FALSE ); if ( !Send( "--MessagePartBoundry--", "\r\n" ) ) return( FALSE ); return( TRUE ); } /* Sample Header MIME-nVersion: 1.0 Content-Type: MULTIPART/MIXED; BOUNDARY="-559023410-851401618-1076640626=:18781" ---559023410-851401618-1076640626=:18781 Content-Type: TEXT/PLAIN; charset=US-ASCII Hi There ---559023410-851401618-1076640626=:18781 Content-Type: APPLICATION/octet-stream; name="submitted.tgz" Content-Transfer-Encoding: BASE64 Content-ID: <Pine.GSO.4.58.0402122150260.18781@ruchbah.ccs.neu.edu> Content-Description: Content-Disposition: attachment; filename="submitted.tgz" ---559023410-851401618-1076640626=:18781-- */ zSHORT Smtp::CreateSmtpMessage( zPCHAR pchSmtpServer, zPCHAR pchSender, zPCHAR pchRecipient[], zLONG lRecipientCnt, zPCHAR pchSubject, zLONG lMimeType, // 1 - text; 2 - html zPCHAR pchBody, zLONG lHasAttachment, // 0 - No; 1 - Yes zPCHAR pchAttachFile, zPCHAR pchUserName, zPCHAR pchPassword ) { CHAR szBody[ 65534 ] = ""; CHAR szUName[ 4096 ] = ""; CHAR szPassword[ 4096 ] = ""; zLONG j; m_lCount++; if ( m_bEhloNotSent ) { if ( !SendRecv( "EHLO ", "\r\n" ) ) // EHLO { TraceLineS( "CreateSmtpMessage cannot send: ", "EHLO" ); return( -2 ); } m_bEhloNotSent = FALSE; if ( *pchUserName ) { if ( !SendRecv( "AUTH LOGIN ", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "AUTH LOGIN" ); return( -3 ); } encode64( szUName, pchUserName ); if ( !SendRecv( szUName, "\r\n" ) ) // { TraceLineS( "CreateSmtpMessage cannot send: ", "USER NAME" ); return( -4 ); } encode64( szPassword, pchPassword ); if ( !SendRecv( szPassword, "\r\n" ) ) // { TraceLineS( "CreateSmtpMessage cannot send: ", "PASSWORD" ); return( -5 ); } } } if ( !SendRecv( "MAIL FROM: ", pchSender, "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "MAIL FROM" ); return( -6 ); } for ( j = 0; j < lRecipientCnt; j++ ) { if ( !SendRecv( "RCPT TO: ", pchRecipient[ j ], "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "RCPT TO" ); return( -7 ); } } if ( !SendRecv( "DATA", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "DATA" ); return( -8 ); } FormattedDate fd; _TCHAR tcDate[ 128 ]; BOOL bRC = fd.GetFormattedDate( tcDate ); if ( !Send( tcDate, "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "Date" ); return( -9 ); } if ( !Send( "FROM: ", pchSender, "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "FROM" ); return( -10 ); } for ( j = 0; j < lRecipientCnt; j++ ) { if ( !Send( "TO: ", pchRecipient[ j ], "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "TO" ); return( -11 ); } } if ( !Send( "SUBJECT: ", pchSubject, "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "SUBJECT" ); return( -12 ); } prepare_header(); if ( lMimeType == 2 ) { if ( lHasAttachment == 1 ) // so this is HTML And Attachment { insert_mixed_part(); insert_boundry(); } insert_html_part(); } else // plain text with or without attachment { if ( lHasAttachment == 1 ) // this is plain text with attachment { insert_mixed_part(); insert_boundry(); } insert_text_part(); } // Set the encoding. if ( !Send( "Content-Transfer-Encoding: ", "7bit", "\r\n", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "Content-Transfer-Encoding" ); return( -13 ); } // Do the body. if ( !Send( pchBody ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "Body" ); return( -14 ); } if ( !Send( "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "<CR>" ); return( -15 ); } // Add attachments here if necessary. if ( lHasAttachment == 1 ) { // insert_end_boundry(); insert_boundry(); if ( !Send( "Content-Type: APPLICATION/octet-stream; name=\"", pchAttachFile, "\"", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "APPLICATION" ); return( -16 ); } if ( !Send( "Content-Transfer-Encoding: 7bit", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "Encoding" ); return( -17 ); } if ( !Send( "Content-Disposition: attachment; filename=\"", pchAttachFile, "\"", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send attachment: ", pchAttachFile ); return( -18 ); } if ( !Send( "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "<CR>" ); return( -19 ); } FILE *fh = fopen( pchAttachFile, "r" ); if ( fh ) { int f = _fileno( fh ); long lLth = _filelength( f ); zPCHAR pchBody; if ( lLth > zsizeof( szBody ) ) pchBody = new char[ lLth ]; else pchBody = szBody; fread( pchBody, sizeof( zCHAR ), lLth, fh ); fclose( fh ); if ( !Send( pchBody ) ) { if ( pchBody ) delete [] pchBody; TraceLineS( "CreateSmtpMessage cannot send: ", "Body" ); return( -20 ); } if ( pchBody != szBody ) delete [] pchBody; } insert_end_boundry(); } // end the body if ( !Send( "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", "End Body" ); return( -21 ); } if ( !SendRecv( ".", "\r\n" ) ) { TraceLineS( "CreateSmtpMessage cannot send: ", ".<CR>" ); return( -22 ); } return( 0 ); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// #if 0 // Create and send an email message // smtp server: Name of your smtp server // email address of person sending the message // array of email addresses of person/people to receive the message // count of email addresses in the send to array // subject line // Body of email BOOL Smtp::CreateSmtpMessage( zPCHAR pchSmtpServer, zPCHAR pchSender, zPCHAR pchRecipient[], zLONG lRecipientCnt, zPCHAR pchSubject, zPCHAR pchBody ) { zLONG j; m_iCount++; if ( m_bEhloNotSent ) { if ( !SendRecv( "EHLO ", "\r\n" ) ) return( FALSE ); m_bEhloNotSent = FALSE; } if ( !SendRecv( "MAIL FROM: ", pchSender, "\r\n" ) ) return( FALSE ); for ( j = 0; j < lRecipientCnt; j++ ) { if ( !SendRecv( "RCPT TO: ", pchRecipient[ j ], "\r\n" ) ) return( FALSE ); } if ( !SendRecv( "DATA", "\r\n" ) ) return FALSE; FormattedDate fd; _TCHAR tcDate[ 128 ]; BOOL bRC = fd.GetFormattedDate( tcDate ); if ( !Send( tcDate, "\r\n" ) ) return( FALSE ); if ( !Send( "FROM: ", pchSender, "\r\n" ) ) return( FALSE ); for ( j = 0; j < lRecipientCnt; j++ ) { if ( !Send( "TO: ", pchRecipient[ j ], "\r\n" ) ) return( FALSE ); } if ( !Send( "SUBJECT: ", pchSubject, "\r\n", "\r\n" ) ) return( FALSE ); if ( !Send( pchBody ) ) return( FALSE ); if ( !Send( "\r\n" ) ) return( FALSE ); if ( !SendRecv( ".", "\r\n" ) ) return( FALSE ); return( TRUE ); } #endif ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Create and send a mim encoded html email message // smtp server: Name of your smtp server // email address of person sending the message // array of email addresses of person/people to receive the message // count of email addresses in the send to array // subject line // Body of email /*BOOL Smtp::CreateHtmlSmtpMessage( zPCHAR pchSmtpServer, zPCHAR pchSender, zPCHAR pchRecipient[], zLONG lRecipientCnt, zPCHAR pchSubject, zPCHAR pchBody ) { zLONG j; m_iCount++; if ( m_bEhloNotSent ) { if ( !SendRecv( "EHLO ", "\r\n" ) ) return( FALSE ); m_bEhloNotSent = FALSE; } if ( !SendRecv( "MAIL FROM: ", pchSender, "\r\n" ) ) return( FALSE ); for ( j = 0; j < lRecipientCnt; j++ ) { if ( !SendRecv( "RCPT TO: ", pchRecipient[ j ], "\r\n" ) ) return( FALSE ); } if ( !SendRecv( "DATA", "\r\n" ) ) return( FALSE ); FormatedDate fd; _TCHAR ptcDate = fd.GetFormatedDate(); if ( !Send( ptcDate, "\r\n" ) ) return( FALSE ); delete [] ptcDate; if ( !Send( "FROM: ", pchSender, "\r\n" ) ) return( FALSE ); for ( j = 0; j < lRecipientCnt; j++ ) { if ( !Send( "TO: ", pchRecipient[ j ], "\r\n" ) ) return( FALSE ); } if ( !Send( "Mime-nVersion: ", "1.0", "\r\n" ) ) return( FALSE ); if ( !Send( "Content-Type: ", "text/html; charset=US-ASCII", "\r\n" ) ) return( FALSE ); if ( !Send( "Content-Transfer-Encoding: ", "7bit", "\r\n" ) ) return( FALSE ); if ( !Send( "SUBJECT: ", pchSubject, "\r\n", "\r\n" ) ) return( FALSE ); if ( !Send( pchBody ) ) return( FALSE ); if ( !Send( "\r\n" ) ) return( FALSE ); if ( !SendRecv( ".", "\r\n" ) ) return( FALSE ); return( TRUE ); } */ #if 0 ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /* * All Windows Sockets error constants are biased by WSABASEERR from * the "normal" */ #define WSABASEERR 10000 /* * Windows Sockets definitions of regular Microsoft C error constants */ #define WSAEINTR (WSABASEERR+4) #define WSAEBADF (WSABASEERR+9) #define WSAEACCES (WSABASEERR+13) #define WSAEFAULT (WSABASEERR+14) #define WSAEINVAL (WSABASEERR+22) #define WSAEMFILE (WSABASEERR+24) /* * Windows Sockets definitions of regular Berkeley error constants */ #define WSAEWOULDBLOCK (WSABASEERR+35) #define WSAEINPROGRESS (WSABASEERR+36) #define WSAEALREADY (WSABASEERR+37) #define WSAENOTSOCK (WSABASEERR+38) #define WSAEDESTADDRREQ (WSABASEERR+39) #define WSAEMSGSIZE (WSABASEERR+40) #define WSAEPROTOTYPE (WSABASEERR+41) #define WSAENOPROTOOPT (WSABASEERR+42) #define WSAEPROTONOSUPPORT (WSABASEERR+43) #define WSAESOCKTNOSUPPORT (WSABASEERR+44) #define WSAEOPNOTSUPP (WSABASEERR+45) #define WSAEPFNOSUPPORT (WSABASEERR+46) #define WSAEAFNOSUPPORT (WSABASEERR+47) #define WSAEADDRINUSE (WSABASEERR+48) #define WSAEADDRNOTAVAIL (WSABASEERR+49) #define WSAENETDOWN (WSABASEERR+50) #define WSAENETUNREACH (WSABASEERR+51) #define WSAENETRESET (WSABASEERR+52) #define WSAECONNABORTED (WSABASEERR+53) #define WSAECONNRESET (WSABASEERR+54) #define WSAENOBUFS (WSABASEERR+55) #define WSAEISCONN (WSABASEERR+56) #define WSAENOTCONN (WSABASEERR+57) #define WSAESHUTDOWN (WSABASEERR+58) #define WSAETOOMANYREFS (WSABASEERR+59) #define WSAETIMEDOUT (WSABASEERR+60) #define WSAECONNREFUSED (WSABASEERR+61) #define WSAELOOP (WSABASEERR+62) #define WSAENAMETOOLONG (WSABASEERR+63) #define WSAEHOSTDOWN (WSABASEERR+64) #define WSAEHOSTUNREACH (WSABASEERR+65) #define WSAENOTEMPTY (WSABASEERR+66) #define WSAEPROCLIM (WSABASEERR+67) #define WSAEUSERS (WSABASEERR+68) #define WSAEDQUOT (WSABASEERR+69) #define WSAESTALE (WSABASEERR+70) #define WSAEREMOTE (WSABASEERR+71) #define WSAEDISCON (WSABASEERR+101) /* * Extended Windows Sockets error constant definitions */ #define WSASYSNOTREADY (WSABASEERR+91) #define WSAVERNOTSUPPORTED (WSABASEERR+92) #define WSANOTINITIALISED (WSABASEERR+93) /* * Error return codes from gethostbyname() and gethostbyaddr() * (when using the resolver). Note that these errors are * retrieved via WSAGetLastError() and must therefore follow * the rules for avoiding clashes with error numbers from * specific implementations or language run-time systems. * For this reason the codes are based at WSABASEERR+1001. * Note also that [WSA]NO_ADDRESS is defined only for * compatibility purposes. */ #define h_errno WSAGetLastError() /* Authoritative Answer: Host not found */ #define WSAHOST_NOT_FOUND (WSABASEERR+1001) #define HOST_NOT_FOUND WSAHOST_NOT_FOUND /* Non-Authoritative: Host not found, or SERVERFAIL */ #define WSATRY_AGAIN (WSABASEERR+1002) #define TRY_AGAIN WSATRY_AGAIN /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */ #define WSANO_RECOVERY (WSABASEERR+1003) #define NO_RECOVERY WSANO_RECOVERY /* Valid name, no data record of requested type */ #define WSANO_DATA (WSABASEERR+1004) #define NO_DATA WSANO_DATA /* no address, look for MX record */ #define WSANO_ADDRESS WSANO_DATA #define NO_ADDRESS WSANO_ADDRESS #endif // SendRecv // Pass four character strings; concatenate them; // do a tcp send and receive on the concatenation. BOOL Smtp::SendRecv( _TCHAR *ptc1, _TCHAR *ptc2, _TCHAR *ptc3, _TCHAR *ptc4 ) { zLONG lLth = (zLONG) _tcsclen( ptc1 ) + (zLONG) _tcsclen( ptc2 ) + (zLONG) _tcsclen( ptc3 ) + (zLONG) _tcsclen( ptc4 ) + 1; if ( lLth > m_lBufferLth ) { mDeleteInitA( m_ptcBuffer ); m_lBufferLth = lLth; m_ptcBuffer = new char[ sizeof( _TCHAR ) * m_lBufferLth ]; } _tcscpy( m_ptcBuffer, ptc1 ); _tcscat( m_ptcBuffer, ptc2 ); _tcscat( m_ptcBuffer, ptc3 ); _tcscat( m_ptcBuffer, ptc4 ); lLth = (zLONG) _tcsclen( m_ptcBuffer ); if ( send( m_SA, m_ptcBuffer, lLth, 0 ) == SOCKET_ERROR ) { INT err = WSAGetLastError(); return( FALSE ); } memset( m_ptcBuffer, 0, m_lBufferLth ); if ( recv( m_SA, m_ptcBuffer, m_lBufferLth, 0 ) == SOCKET_ERROR ) { INT err = WSAGetLastError(); return( FALSE ); } return( TRUE ); } // Send // Pass four character string; do a tcp send on them. BOOL Smtp::Send( _TCHAR *ptc1, _TCHAR *ptc2, _TCHAR *ptc3, _TCHAR *ptc4 ) { zLONG lLth = (zLONG) _tcsclen( ptc1 ) + (zLONG) _tcsclen( ptc2 ) + (zLONG) _tcsclen( ptc3 ) + (zLONG) _tcsclen( ptc4 ) + 1; if ( lLth > m_lBufferLth ) { mDeleteInitA( m_ptcBuffer ); m_lBufferLth = lLth; m_ptcBuffer = new char[ sizeof( _TCHAR ) * m_lBufferLth ]; } _tcscpy( m_ptcBuffer, ptc1 ); _tcscat( m_ptcBuffer, ptc2 ); _tcscat( m_ptcBuffer, ptc3 ); _tcscat( m_ptcBuffer, ptc4 ); lLth = (zLONG) _tcsclen( m_ptcBuffer ); if ( send( m_SA, m_ptcBuffer, lLth, 0 ) == SOCKET_ERROR ) { INT err = WSAGetLastError(); return( FALSE ); } return( TRUE ); } #if 0 int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // TODO: Place code here. zPCHAR pchNames[] = { "dks@quinsoft.com", "arksoft@comcast.net" }; FILE *fp; CHAR szBody[ 45120 ] = "" ; CHAR szString[ 1024 ]; Smtp smtpMailMessage; Smtp smtpMailMessage2; Smtp smtpMailMessage3; Smtp smtpMailMessage4; strcpy_s( szBody, zsizeof( szBody ), "This is a plain Text EMAIL" ); smtpMailMessage.CreateSmtpConnection( "www.quinsoft.com" ); smtpMailMessage.CreateSmtpMessage( "www.quinsoft.com", "dks@quinsoft.com", pchNames, 1, "Test", 1, // text szBody, 0, "" ); strcpy_s( szBody, zsizeof( szBody ), "" ); fp = fopen( "C:\\Temp\\test2.html", "r" ); while ( fgets( szString,5120,fp ) ) { strcat_s( szBody, zsizeof( szBody ), szString ); } fclose( fp ); smtpMailMessage2.CreateSmtpConnection( "www.quinsoft.com" ); smtpMailMessage2.CreateSmtpMessage( "www.quinsoft.com", "dks@quinsoft.com", pchNames, 1, "Test", 2, // HTML szBody, 0, "" ); strcpy_s( szBody, zsizeof( szBody ), "This is aNOTHER plain Text EMAIL with Attachment"); smtpMailMessage3.CreateSmtpConnection( "www.quinsoft.com" ); smtpMailMessage3.CreateSmtpMessage( "www.quinsoft.com", "dks@quinsoft.com", pchNames, 1, "Test", 1, szBody, 1, "C:\\temp\\text1.txt" ); strcpy_s( szBody, zsizeof( szBody ), "" ); fp = fopen( "C:\\Temp\\test2.html", "r" ); while ( fgets( szString, 1024, fp ) ) { strcat_s( szBody, zsizeof( szBody ), szString ); } fclose( fp ); smtpMailMessage4.CreateSmtpConnection( "www.quinsoft.com" ); smtpMailMessage4.CreateSmtpMessage( "www.quinsoft.com", "dks@quinsoft.com", pchNames, 1, "Test", 2, // HTML szBody, 1, "C:\\temp\\test1.rtf" ); return( 0 ); } #endif #if 0 ///////////////////////////////////////////////////////////////////////////// // MIMEMessage.cpp: implementation of the CMIMEMessage class. // Author: Wes Clyburn (clyburnw@enmu.edu) ///////////////////////////////////////////////////////////////////////////// #include "MIMEMessage.h" #include "TextPlain.h" #include "AppOctetStream.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif // Static Member Initializers CMIMEMessage::CMIMETypeManager CMIMEMessage::m_MIMETypeManager; ///////////////////////////////////////////////////////////////////////////// // Construction/Destruction ///////////////////////////////////////////////////////////////////////////// CMIMEMessage::CMIMEMessage() { m_sMIMEContentType = _T( "multipart/mixed" ); m_sPartBoundary = _T( "WC_MAIL_PaRt_BoUnDaRy_05151998" ); m_sNoMIMEText = _T( "This is a multi-part message in MIME format." ); // Register the MIME types handled by this class // // These objects are deleted by CMIMTypeManager's destructor CMIMEContentAgent *pType = new CTextPlain( TEXT_PLAIN, GetCharsPerLine() ); register_mime_type( pType ); pType = new CAppOctetStream( APPLICATION_OCTETSTREAM ); register_mime_type( pType ); } CMIMEMessage::~CMIMEMessage() { } // This implementation adds the part to the part-list used // to build the body. BOOL CMIMEMessage::AddMIMEPart( LPCTSTR szContent, int nContentType, LPCTSTR szParameters, int nEncoding, BOOL bPath ) { CMIMEPart part; part.m_nContentType = nContentType; part.m_sParameters = szParameters; part.m_nEncoding = nEncoding; part.m_bPath = bPath; part.m_sContent = szContent; part.m_sContent.TrimLeft(); part.m_sContent.TrimRight(); if ( nContentType == TEXT_PLAIN ) m_MIMEPartList.AddHead( part ); else m_MIMEPartList.AddTail( part ); return TRUE; } void CMIMEMessage::prepare_header() { CString csTemp; // Let the base class add its headers CMailMessage::prepare_header(); add_header_line( _T( "MIME-nVersion: 1.0" ) ); csTemp.Format( _T( "Content-Type: %s; boundary=%s" ), (LPCTSTR) m_sMIMEContentType, (LPCTSTR) m_sPartBoundary ); add_header_line( (LPCTSTR) csTemp ); } void CMIMEMessage::prepare_body() { // Class user may have assigned body text directly. // Convert it to just another MIME part to be processed. // If this default Content-Type isn't good enough for the // class user, he or she should have used AddMIMEPart() instead. if ( m_sBody != _T( "" ) ) AddMIMEPart( (LPCTSTR) m_sBody, TEXT_PLAIN, "", _7BIT, FALSE ); // Initialize the body (replace current contents). m_sBody = m_sNoMIMEText; m_sBody += _T( "\r\n\r\n" ); append_mime_parts(); insert_message_end( m_sBody ); // Let the base class take me to Funky Town CMailMessage::prepare_body(); } void CMIMEMessage::insert_boundary( CString& csText ) { CString csTemp; if ( csText.Right( 2 ) != _T( "\r\n" ) ) csText += _T( "\r\n" ); csTemp.Format( _T( "--%s\r\n" ), (LPCTSTR)m_sPartBoundary ); csText += csTemp; } void CMIMEMessage::insert_message_end( CString& csText ) { CString csTemp; if ( csText.Right( 2 ) != _T( "\r\n" ) ) csText += _T( "\r\n" ); csTemp.Format( _T( "--%s--\r\n" ), (LPCTSTR)m_sPartBoundary ); csText += csTemp; } void CMIMEMessage::register_mime_type( CMIMEContentAgent *pMIMEType ) { ASSERT( pMIMEType ); if ( pMIMEType == NULL ) return; m_MIMETypeManager.RegisterMIMEType( pMIMEType ); } void CMIMEMessage::append_mime_parts() { POSITION part_position; CMIMEPart *pMIMEPart = NULL; CMIMEContentAgent *pMIMEType = NULL; part_position = m_MIMEPartList.GetHeadPosition(); // Get each part from the list, retrieve a handler for it, // and let the handler do its thing. while ( part_position != NULL ) { pMIMEPart = & m_MIMEPartList.GetNext( part_position ); pMIMEType = m_MIMETypeManager.GetHandler( pMIMEPart->m_nContentType ); if ( pMIMEType ) { insert_boundary( m_sBody ); pMIMEType->AppendPart( pMIMEPart->m_sContent, pMIMEPart->m_sParameters, pMIMEPart->m_nEncoding, pMIMEPart->m_bPath, m_sBody ); } } } ///////////////////////////////////////////////////////////////////////////// // CMIMETypeManager Implementation ///////////////////////////////////////////////////////////////////////////// CMIMEMessage::CMIMETypeManager::CMIMETypeManager() { } CMIMEMessage::CMIMETypeManager::~CMIMETypeManager() { POSITION pos; CMIMEContentAgent *p; m_csAccess.Lock(); pos = m_MIMETypeList.GetHeadPosition(); while ( pos ) { p = m_MIMETypeList.GetNext( pos ); delete p; } } void CMIMEMessage::CMIMETypeManager::RegisterMIMEType( CMIMEContentAgent *pMIMEType ) { ASSERT( pMIMEType ); if ( pMIMEType == NULL ) return; m_csAccess.Lock( ); m_MIMETypeList.AddTail( pMIMEType ); } CMIMEContentAgent * CMIMEMessage::CMIMETypeManager::GetHandler( int nContentType ) { POSITION pos; CMIMEContentAgent* pType = NULL; m_csAccess.Lock(); pos = m_MIMETypeList.GetHeadPosition(); while ( pos ) { pType = m_MIMETypeList.GetNext( pos ); if ( pType->QueryType( nContentType ) == TRUE ) break; } return pType; } #endif ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// void DisplaySeeError( int nSeeCode ) { zCHAR szErrorMsg[ zMAX_FILESPEC_LTH + 1 ]; nSeeCode = seeErrorText( 0, nSeeCode, szErrorMsg, zsizeof( szErrorMsg ) ); TraceLine( "SEE Error %d: %s", nSeeCode, szErrorMsg ); } zPCHAR PrefixFilenameWithAt( zCPCHAR cpcFileName ) { zLONG lLth = zstrlen( cpcFileName ) + 2; zPCHAR pchAtFileName = new char[ lLth ]; if ( *cpcFileName == '@' ) strcpy_s( pchAtFileName, lLth, cpcFileName ); else { pchAtFileName[ 0 ] = '@'; strcpy_s( pchAtFileName + 1, lLth - 1, cpcFileName ); } return( pchAtFileName ); } zPCHAR SurroundWithAngleBrackets( zCPCHAR cpcRecipient ) { zLONG lLth = zstrlen( cpcRecipient ) + 3; zPCHAR pchAngleRecipient = new char[ lLth ]; if ( (zstrchr( cpcRecipient, '<' ) == 0) || (zstrchr( cpcRecipient, '>' ) == 0) ) { // Surround with angle brackets. pchAngleRecipient[ 0 ] = '<'; strcpy_s( pchAngleRecipient + 1, lLth - 1, cpcRecipient ); strcat_s( pchAngleRecipient, lLth, ">" ); } else { strcpy_s( pchAngleRecipient, lLth, cpcRecipient ); } return( pchAngleRecipient ); } #define SEE_KEY_CODE 314056830 zOPER_EXPORT zLONG OPERATION CreateSeeConnection( zPCHAR pchSmtpServer, zPCHAR pchSenderEmailAddr, zPCHAR pchSmtpUserName, zPCHAR pchSmtpPassword ) { int nSeeCode = seeAttach( 1, SEE_KEY_CODE ); if ( nSeeCode < 0 ) { TraceLineS( "seeAttach failure: Check key code (SEE_KEY_CODE)", "" ); return( 0 ); } // Enable diagnostics log file. seeStringParam( 0, SEE_LOG_FILE, (LPSTR) "MailHTML.log" ); int nVersion = seeStatistics( 0, SEE_GET_VERSION ); int nBuild = seeStatistics( 0, SEE_GET_BUILD ); TraceLine( "SEE32 Version: %1d.%1d.%1d Build %d Smtp Server: %s " "Sender: %s User: %s Password: %s", 0x0f & (nVersion >> 8), 0x0f & (nVersion >> 4), 0x0f & nVersion, nBuild, pchSmtpServer, pchSenderEmailAddr, pchSmtpUserName ? pchSmtpUserName : "", "" ); // pchSmtpPassword ? pchSmtpPassword : "" ); // Enable ESMTP authentication. seeIntegerParam( 0, SEE_ENABLE_ESMTP, 1 ); // Specify user name and password for authentication. if ( pchSmtpUserName && *pchSmtpUserName ) seeStringParam( 0, SEE_SET_USER, pchSmtpUserName ); if ( pchSmtpPassword && *pchSmtpPassword ) seeStringParam( 0, SEE_SET_SECRET, pchSmtpPassword ); // Connect to ESMTP server. zPCHAR pchAngleSender = SurroundWithAngleBrackets( pchSenderEmailAddr ); TraceLineS( "Connecting to ESMTP server: ", pchSmtpServer ); nSeeCode = seeSmtpConnect( 0, // channel pchSmtpServer, // ESMTP server pchAngleSender, // return email address pchAngleSender ); // Reply-To header delete [] pchAngleSender; // SMTP_USER_NAME and SMTP_PASSWORD are used for ESMTP connection. if ( nSeeCode < 0 ) { // Server may be SMTP rather than ESMTP! (see MailHTML.log) DisplaySeeError( nSeeCode ); seeRelease(); return( 0 ); } // If seeSmtpConnect (or seePop3Connect) fails, do not call seeClose. TraceLineS( "ESMTP Connection successful!", "" ); ZSee *pSee = new ZSee; return( (zLONG) pSee ); } // 4.1 Static Libraries in see_4c.doc zOPER_EXPORT zSHORT OPERATION CreateSeeMessage( zLONG lSeeConnection, zPCHAR pchSmtpServer, zPCHAR pchSender, zPCHAR pchRecipient, zPCHAR pchCC, zPCHAR pchBCC, zPCHAR pchSubject, zLONG lMimeType, // 1 - text; 2 - html zPCHAR pchBody, // if pchBody or pchAltText start // with '@', a file name is expected zPCHAR pchAltText, // valid only when sending html zPCHAR pchEmbeddedImages, zLONG lHasAttachment, // 0 - No; 1 - Yes zPCHAR pchAttachFile, zPCHAR pchUserName, zPCHAR pchPassword ) { TraceLine( "CreateSeeMessage Server: %s Sender: %s Recipient: %s" " Subject: %s Mime Type: %d" " User: %s Password %s", pchSmtpServer, pchSender, pchRecipient, pchSubject, lMimeType, pchUserName, "******" ); // pchPassword ); ZSee *pSee = (ZSee *) lSeeConnection; zPCHAR pchAngleRecipient = 0; zPCHAR pchAngleSender = 0; zSHORT nRC = -1; int nSeeCode = 0; while ( pSee ) // purist's goto { // Verify that we have all strings we need. if ( pchSmtpServer == 0 || *pchSmtpServer == 0 ) { TraceLineS( "ERROR: Missing SMTP server name", "" ); break; } // Check "From:" address. if ( pchSender == 0 || *pchSender == 0 ) { TraceLineS( "ERROR: 'From' address is missing", "" ); break; } // Check "To:" address. if ( pchRecipient == 0 || *pchRecipient == 0 ) { TraceLineS( "ERROR: 'To' address is missing", "" ); break; } if ( pchSubject == 0 || *pchSubject == 0 ) { TraceLineS( "ERROR: Missing 'Subject:'", "" ); break; } if ( pchBody == 0 || *pchBody == 0 ) { if ( lMimeType == 2 ) // html TraceLineS( "ERROR: Missing HTML file", "" ); else TraceLineS( "ERROR: Missing message", "" ); break; } pchAngleRecipient = SurroundWithAngleBrackets( pchRecipient ); pchAngleSender = SurroundWithAngleBrackets( pchSender ); if ( (nSeeCode = seeVerifyFormat( pchAngleRecipient )) < 0 || (nSeeCode = seeVerifyFormat( pchAngleSender )) < 0 ) { break; } // Display To: and From: TraceLine( "To: '%s' From: '%s'", pchAngleRecipient, pchAngleSender ); // Connect to SMTP server. // TraceLine( "Connecting to server '%s'", SmtpString ); // nSeeCode = seeSmtpConnect( 0, (LPSTR) SmtpString, // (LPSTR) FromString, (LPSTR) NULL ); // if ( nSeeCode < 0 ) // { // DisplaySeeError( nSeeCode ); // break; // } // Prefix alternate text filename with '@'. // PrefixFilenameWithAt( (LPSTR) pchAltText ); if ( lMimeType == 2 ) // html { // Ensure HTML filename is prefixed with '@'. // zPCHAR pchAtBody = PrefixFilenameWithAt( pchBody ); zPCHAR pchAtBody = pchBody; // Send email. TraceLine( "Sending html mail ... Recipient: %s Subject: %s " "Body: %s Embedded Images: %s " "Alternate Text: %s Attach File: %s", pchAngleRecipient, pchSubject, pchAtBody, pchEmbeddedImages, pchAltText, pchAttachFile ); nSeeCode = seeSendHTML( 0, // channel 0 pchAngleRecipient, // To list pchCC, // CC list pchBCC, // BCC list pchSubject, // Subject pchAtBody, // Message text pchEmbeddedImages, // Embedded images pchAltText, // Alternate text pchAttachFile ); // MIME attachment // delete [] pchAtBody; } else { nSeeCode = seeSendEmail( 0, // channel 0 pchAngleRecipient, // To list pchCC, // CC list pchBCC, // BCC list pchSubject, // Subject pchBody, // Message text pchAttachFile ); // MIME attachment } break; } if ( pchAngleRecipient ) delete [] pchAngleRecipient; if ( pchAngleSender ) delete [] pchAngleSender; if ( nSeeCode < 0 ) { nRC = -1; DisplaySeeError( nSeeCode ); seeClose( 0 ); return( -1 ); } else nRC = 0; TraceLineI( "Email has been sent ... RC: ", nRC ); return( nRC ); } #if 0 zPCHAR *ppchToArray = (zPCHAR *) new char[ sizeof( zPCHAR ) * lRecipientCnt ]; if ( lRecipientCnt == 1 ) { ppchToArray[ 0 ] = pchRecipient; } else { zPCHAR pch = pchRecipient; zLONG lCnt = 0; while ( lCnt < lRecipientCnt ) { ppchToArray[ lCnt ] = pch; pch += zstrlen( pch ) + 1; } } zSHORT nRC = pSmtp->CreateSmtpMessage( pchSmtpServer, pchSender, ppchToArray, lRecipientCnt, pchSubject, nMimeType, // text pchBody, nHasAttachment, pchAttachFile, pchUserName, pchPassword ); delete [] ppchToArray; #endif zOPER_EXPORT zVOID OPERATION CloseSeeConnection( zLONG lSeeConnection ) { TraceLineS( "Closing Smpt Connection ...", "" ); ZSee *pSee = (ZSee *) lSeeConnection; if ( pSee ) delete( pSee ); } zOPER_EXPORT zSHORT OPERATION ValidateEmailAddressFormat( zCPCHAR cpcEmailAddress ) { zPCHAR pchAngleEmailAddress = SurroundWithAngleBrackets( cpcEmailAddress ); if ( pchAngleEmailAddress ) { int nSeeCode = seeVerifyFormat( pchAngleEmailAddress ); delete [] pchAngleEmailAddress; if ( nSeeCode >= 0 ) return( TRUE ); // DisplaySeeError( nSeeCode ); } return( FALSE ); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // // fsee.cpp // // C++ class wrapper for SEE. See the HELLO.CPP example program. // //#include <windows.h> //#include <iostream.h> //#include "fsee.h" // constructor ZSee::ZSee( void ) { }; // destructor ZSee::~ZSee( void ) { Close( 0 ); Release( ); }; // see32 functions int ZSee::Abort( int Chan ) { return( seeAbort( Chan ) ); } int ZSee::Attach( int Channels, long KeyCode ) { return( seeAttach( Channels, KeyCode ) ); } int ZSee::Close( int Chan ) { return( seeClose( Chan ) ); } int ZSee::Command( int Chan, LPCSTR Command ) { return( seeCommand( Chan, Command ) ); } int ZSee::Debug( int Chan, int Index, LPSTR Buffer, int BufLth ) { return( seeDebug( Chan, Index, Buffer, BufLth ) ); } int ZSee::DecodeBuffer( LPCSTR CodedBuf, LPSTR ClearBuf, int ClearLth ) { return( seeDecodeBuffer( CodedBuf, ClearBuf, ClearLth ) ); } int ZSee::DeleteEmail( int Chan, int Message ) { return( seeDeleteEmail( Chan, Message ) ); } int ZSee::Driver( int Chan ) { return( seeDriver( Chan ) ); } int ZSee::EncodeBuffer( LPCSTR ClearBuf, LPSTR CodedBuf, int CodedLth ) { return( seeEncodeBuffer( ClearBuf, CodedBuf, CodedLth ) ); } int ZSee::ErrorText( int Chan, int nSeeCode, LPSTR Buffer, int BufLth ) { return( seeErrorText( Chan, nSeeCode, Buffer, BufLth ) ); } int ZSee::ExtractLine( LPCSTR Src, int LineNbr, LPSTR Buffer, int BufSize ) { return( seeExtractLine( Src, LineNbr, Buffer, BufSize ) ); } int ZSee::ExtractText( LPCSTR Src, LPCSTR Text, LPSTR Buffer, int BufSize ) { return( seeExtractText( Src, Text, Buffer, BufSize ) ); } int ZSee::GetEmailCount( int Chan ) { return( seeGetEmailCount( Chan ) ); } int ZSee::GetEmailFile( int Chan, int MsgNbr, LPCSTR EmailName, LPCSTR EmailDir, LPCSTR AttachDir ) { return( seeGetEmailFile( Chan, MsgNbr, EmailName, EmailDir, AttachDir ) ); } int ZSee::GetEmailLines( int Chan, int MsgNbr, int Lines, LPSTR Buffer, int Size ) { return( seeGetEmailLines( Chan, MsgNbr, Lines, Buffer, Size ) ); } long ZSee::GetEmailSize( int Chan, int Message ) { return( seeGetEmailSize( Chan, Message ) ); } int ZSee::GetEmailUID( int Chan, int MsgNbr, LPSTR Buffer, int Size ) { return( seeGetEmailUID( Chan, MsgNbr, Buffer, Size ) ); } int ZSee::IntegerParam( int Chan, int ParamName, ULONG ParamValue ) { return( seeIntegerParam( Chan, ParamName, ParamValue ) ); } int ZSee::Pop3Connect( int Chan, LPCSTR Pop3Ptr, LPCSTR UserPtr, LPCSTR PassPtr ) { return( seePop3Connect( Chan, Pop3Ptr, UserPtr, PassPtr ) ); } int ZSee::Release( void ) { return( seeRelease( ) ); } int ZSee::SendEmail( int Chan, LPCSTR ToPtr, LPCSTR CCPtr, LPCSTR BCCPtr, LPCSTR SubjPtr, LPCSTR MsgPtr, LPCSTR AttachPtr ) { return( seeSendEmail( Chan, ToPtr, CCPtr, BCCPtr, SubjPtr, MsgPtr, AttachPtr ) ); } int ZSee::SendHTML( int Chan, LPCSTR ToPtr, LPCSTR CCPtr, LPCSTR BCCPtr, LPCSTR SubjPtr, LPCSTR MsgPtr, LPCSTR ImagesPtr, LPCSTR AltTxtPtr, LPCSTR AttachPtr ) { return( seeSendHTML( Chan, ToPtr, CCPtr, BCCPtr, SubjPtr, MsgPtr, ImagesPtr, AltTxtPtr, AttachPtr ) ); } int ZSee::SmtpConnect( int Chan, LPCSTR SmtpPtr, LPCSTR FromPtr, LPCSTR ReplyTo ) { return( seeSmtpConnect( Chan, SmtpPtr, FromPtr, ReplyTo ) ); } long ZSee::Statistics( int Chan, int ParamName ) { return( seeStatistics( Chan, ParamName ) ); } int ZSee::StringParam( int Chan, int ParamName, LPCSTR ParamPtr ) { return( seeStringParam( Chan, ParamName, ParamPtr ) ); } int ZSee::VerifyFormat( LPCSTR Ptr ) { return( seeVerifyFormat( Ptr ) ); } int ZSee::VerifyUser( int Chan, LPCSTR UserPtr ) { return( seeVerifyUser( Chan, UserPtr ) ); } int ZSee::QuoteBuffer( LPSTR String, LPSTR Buffer, int BufLth ) { return( seeQuoteBuffer( String, Buffer, BufLth ) ); } int ZSee::DecodeUU( LPCSTR CodedPtr, LPSTR ClearPtr ) { return( seeDecodeUU( CodedPtr, ClearPtr ) ); } int ZSee::EncodeUTF8( int UnicodeValue, LPSTR UTF8Buffer ) { return( seeEncodeUTF8( UnicodeValue, UTF8Buffer ) ); } int ZSee::DecodeUTF8( LPCSTR UTF8Buffer, LPSTR UnicodeBuffer ) { return( seeDecodeUTF8( UTF8Buffer, UnicodeBuffer ) ); } ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
[ "arksoft@comcast.net" ]
arksoft@comcast.net
9aa30cdecaf4453a27103f5a3cbf003ab76e0ee7
11267ffd08839606fc4d8fd53c49cd3d373eedcd
/third_party/eigen3/unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h
e11d5ed22e7797a2e132b343a865485c4c274311
[ "LGPL-2.0-or-later", "MPL-2.0", "LGPL-3.0-only", "BSD-3-Clause", "LGPL-2.1-or-later", "GPL-3.0-only", "Minpack", "LGPL-2.1-only", "Apache-2.0" ]
permissive
him-28/TensorFlow
65b7044fd1f74a85cde1e025861a628b3ee9c214
9871a5ef21785b720d75e46bd38b49eea829e808
refs/heads/master
2023-01-21T20:29:20.006510
2015-11-24T07:10:25
2015-11-24T07:10:25
66,283,292
1
1
Apache-2.0
2022-12-20T11:37:24
2016-08-22T15:13:19
C++
UTF-8
C++
false
false
5,180
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H #define EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H namespace Eigen { template<typename Scalar_, std::size_t NumIndices_, int Options_ = 0, typename IndexType = DenseIndex> class Tensor; template<typename Scalar_, typename Dimensions, int Options_ = 0, typename IndexType = DenseIndex> class TensorFixedSize; template<typename Scalar_, int Options_ = 0, typename IndexType = DenseIndex> class TensorVarDim; template<typename PlainObjectType, int Options_ = Unaligned> class TensorMap; template<typename PlainObjectType> class TensorRef; template<typename Derived, int AccessLevel = internal::accessors_level<Derived>::value> class TensorBase; template<typename NullaryOp, typename PlainObjectType> class TensorCwiseNullaryOp; template<typename UnaryOp, typename XprType> class TensorCwiseUnaryOp; template<typename BinaryOp, typename LeftXprType, typename RightXprType> class TensorCwiseBinaryOp; template<typename IfXprType, typename ThenXprType, typename ElseXprType> class TensorSelectOp; template<typename Op, typename Dims, typename XprType> class TensorReductionOp; template<typename XprType> class TensorIndexTupleOp; template<typename ReduceOp, typename Dims, typename XprType> class TensorTupleReducerOp; template<typename Axis, typename LeftXprType, typename RightXprType> class TensorConcatenationOp; template<typename Dimensions, typename LeftXprType, typename RightXprType> class TensorContractionOp; template<typename TargetType, typename XprType> class TensorConversionOp; template<typename Dimensions, typename InputXprType, typename KernelXprType> class TensorConvolutionOp; template<typename Dimensions, typename InputXprType, typename KernelXprType> class TensorConvolutionByFFTOp; template<typename FFT, typename XprType, int FFTDataType, int FFTDirection> class TensorFFTOp; template<typename IFFT, typename XprType, int ResultType> class TensorIFFTOp; template<typename DFT, typename XprType, int ResultType> class TensorDFTOp; template<typename IDFT, typename XprType, int ResultType> class TensorIDFTOp; template<typename PatchDim, typename XprType> class TensorPatchOp; template<DenseIndex Rows, DenseIndex Cols, typename XprType> class TensorImagePatchOp; template<DenseIndex Planes, DenseIndex Rows, DenseIndex Cols, typename XprType> class TensorVolumePatchOp; template<typename Broadcast, typename XprType> class TensorBroadcastingOp; template<DenseIndex DimId, typename XprType> class TensorChippingOp; template<typename NewDimensions, typename XprType> class TensorReshapingOp; template<typename XprType> class TensorLayoutSwapOp; template<typename StartIndices, typename Sizes, typename XprType> class TensorSlicingOp; template<typename ReverseDimensions, typename XprType> class TensorReverseOp; template<typename XprType> class TensorTrueIndicesOp; template<typename PaddingDimensions, typename XprType> class TensorPaddingOp; template<typename Shuffle, typename XprType> class TensorShufflingOp; template<typename Strides, typename XprType> class TensorStridingOp; template<typename Strides, typename XprType> class TensorInflationOp; template<typename Generator, typename XprType> class TensorGeneratorOp; template<typename LeftXprType, typename RightXprType> class TensorAssignOp; template<typename CustomUnaryFunc, typename XprType> class TensorCustomUnaryOp; template<typename CustomBinaryFunc, typename LhsXprType, typename RhsXprType> class TensorCustomBinaryOp; template<typename XprType> class TensorEvalToOp; template<typename XprType> class TensorForcedEvalOp; template<typename ExpressionType, typename DeviceType> class TensorDevice; template<typename Derived, typename Device> struct TensorEvaluator; class DefaultDevice; class ThreadPoolDevice; class GpuDevice; enum DFTResultType { RealPart = 0, ImagPart = 1, BothParts = 2 }; enum FFTDirection { FFT_FORWARD = 0, FFT_REVERSE = 1 }; namespace internal { template <typename Device, typename Expression> struct IsVectorizable { static const bool value = TensorEvaluator<Expression, Device>::PacketAccess; }; template <typename Expression> struct IsVectorizable<GpuDevice, Expression> { static const bool value = TensorEvaluator<Expression, GpuDevice>::PacketAccess && TensorEvaluator<Expression, GpuDevice>::IsAligned; }; template <typename Device, typename Expression> struct IsTileable { static const bool value = TensorEvaluator<Expression, Device>::BlockAccess; }; template <typename Expression, typename Device, bool Vectorizable = IsVectorizable<Device, Expression>::value, bool Tileable = IsTileable<Device, Expression>::value> class TensorExecutor; } // end namespace internal } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H
[ "keveman@gmail.com" ]
keveman@gmail.com
a92f7987382d904caff20ad1946a728c7629d5bc
e817d1835eaf541703b055985fade1fac84a07db
/hw9-1/classes.cc
cd654dae138bf8575e64fac4eb5e74e22276e083
[]
no_license
FYLSunghwan/2019_ITE1015
b260b26639aba11f7c102144b8f8011d92eb9796
4eaa2341db79a74293cb82f79c2c5018b4ea6f1a
refs/heads/master
2021-01-03T09:40:55.686875
2020-02-12T13:55:14
2020-02-12T13:55:14
240,024,961
0
0
null
null
null
null
UTF-8
C++
false
false
229
cc
#include "classes.h" #include <iostream> void A::test() { std::cout << "A::test()" << std::endl; } void B::test() { std::cout << "B::test()" << std::endl; } void C::test() { std::cout << "C::test()" << std::endl; }
[ "sunghwan519@hotmail.com" ]
sunghwan519@hotmail.com
a641d0e04725ba344ac2b8c464e002471838d994
8eac6a6d838ceb06c44daa28bb9ef7aaccddbf9b
/Chapter11/ch11_11_4.cpp
54b8449b56f956e3ab00d75ca7b0477788bf9c11
[]
no_license
Song621/CPP-Classes-and-Data-Structures
e66def3fca5eb85c2e7503e5d8293879e53250c6
d9c1ede3c92ab123a600a18ae03f124e41ba3c6f
refs/heads/master
2023-08-30T12:56:06.279988
2021-11-10T16:53:46
2021-11-10T16:53:46
303,077,699
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include <iostream> using namespace std; void foo(int a, int b) { cout<<"a is: "<<a<<endl; cout<<"b is: "<<b<<endl; } int main() { void (*fptr) (int a, int b); //函数指针,指针名为fptr,*fptr两边的小括号是必须的, //fptr可以指向的函数的返回类型位于指针名称的左边, //指针函数的参数列表位于指针名称的右边。 fptr = foo;//将foo的地址赋给fptr fptr(10,25);//通过使用指针来执行函数,我们不必取fptr指针的内容 return 0; }
[ "2972918569@qq.com" ]
2972918569@qq.com
8c2543a49c87a33cf2bdef4a49e846ba27604a12
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_2213_last_repos.cpp
49cdb871b7d8e87a10617eaf82762adb2a56738d
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
static CURLcode smtp_perform_rcpt_to(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; /* Send the RCPT TO command */ if(smtp->rcpt->data[0] == '<') result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s", smtp->rcpt->data); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>", smtp->rcpt->data); if(!result) state(conn, SMTP_RCPT); return result; }
[ "993273596@qq.com" ]
993273596@qq.com
f423a007134313e02b104af37e7be86c144a784e
780d89a45e6a75834cb4e72fd679a5605f42b250
/find_the_duplicate_number_lc287.cpp
6bb2b4e82f33b33511196bb5d75434dd7f2e0662
[]
no_license
omkarlenka/leetcode
d55a29d6dbfcf1c819d58152c61e3cf629bb170a
0a12474a96beeda25e396977b927d45ae7a67016
refs/heads/master
2023-04-19T00:36:47.405066
2021-05-05T18:30:20
2021-05-05T18:30:20
254,595,595
1
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
// // find_the_duplicate_number_lc287.cpp // // Created by omlenka on 09/01/21. // Copyright © 2021 omkar lenka. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: int findDuplicate(vector<int>& nums) { for(int i = 0;i<nums.size();i++){ int j = i; while(nums[i] != i+1){ if(nums[i] == nums[nums[i]-1]){ return nums[i]; } else{ swap(nums[i],nums[nums[i]-1]); } } i = j; } return -1; } };
[ "omkar.lenka@gmail.com" ]
omkar.lenka@gmail.com
87c12889cf4bc4d857da23d9e6a4befb8dd9632a
208dc025a8ddf6643d29091b39f2548837fbb18e
/include/GLtank.h
e8f024e42f8daeeaec9ffce0f1a4243515d8615c
[]
no_license
Pefes/TankSimulatorOpenGL
da641c79ce8b442be899bfa879743f772925f9e9
302c737134e4fdc73cf91acd63e71028bcb62fed
refs/heads/master
2021-03-05T12:49:22.253051
2020-03-09T19:24:13
2020-03-09T19:24:13
246,123,109
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
h
#ifndef GLTANK_H #define GLTANK_H #include "GLobject.h" namespace GLmodels { class GLtank { public: GLtank(); void left(); void right(); void forward(); void backward(); void turretLeft(); void turretRight(); void barrelUp(); void barrelDown(); void fire(); virtual ~GLtank(); private: class GLbarrel: public GLobject { public: GLbarrel(glm::vec3 position, std::string verticesPath, std::string texturePath); void rotate(Rotate direction, float angle, glm::mat4 turretMatrix); void move(glm::mat4 turretMatrix); private: float m_maxAngleBarrel; } m_barrel; class GLturret: public GLobject { public: GLturret(glm::vec3 position, std::string verticesPath, std::string texturePath); void rotate(Rotate direction, float angle, glm::mat4 bottomMatrix); void move(glm::mat4 bottomMatrix); } m_turret; class GLbottom: public GLobject { public: GLbottom(glm::vec3 position, std::string verticesPath, std::string texturePath); void rotate(Rotate direction, float angle); void move(Move direction, double distance); } m_bottom; class GLbullet: public GLobject { public: GLbullet(glm::vec3 position, std::string verticesPath, std::string texturePath); void move(glm::mat4 barrelMatrix); } m_bullet; }; } #endif // GLTANK_H
[ "pawlo898@gmail.com" ]
pawlo898@gmail.com
58314fe79b81e42c8192280452c1f1a8d693d352
ca9002d2410225bfe3df85ea0c2e419b51effdcc
/CppND-System-Monitor/src/system.cpp
1c6c155168494b0fa9f932848628fc14be06f124
[ "MIT" ]
permissive
ranjitmahadik/CPP-Nanodegree
c1bbe1afa4dcf76a891594ae5f4c8085e5404125
bf8273e09012d7c0e6a80cc6e1c7d64c749bddf1
refs/heads/master
2022-05-27T21:34:26.374236
2020-04-24T09:10:52
2020-04-24T09:10:52
258,457,607
1
0
null
null
null
null
UTF-8
C++
false
false
1,629
cpp
#include <unistd.h> #include <cstddef> #include <set> #include <string> #include <vector> #include "process.h" #include "processor.h" #include "system.h" #include "linux_parser.h" using std::set; using std::size_t; using std::string; using std::vector; System::System(){ cpu_ = Processor(); Processes(); } // TODO: Return the system's CPU Processor& System::Cpu() { return cpu_; } // TODO: Return a container composed of the system's processes vector<Process>& System::Processes() { processes_.clear(); auto pids = LinuxParser::Pids(); for(int pid : pids){ processes_.push_back(Process(pid)); } for (Process& p: processes_){ p.CpuUtilization(LinuxParser::ActiveJiffies(p.Pid()), LinuxParser::Jiffies()); } std::sort(processes_.begin(),processes_.end()); return processes_; } // TODO: Return the system's kernel identifier (string) std::string System::Kernel() { return LinuxParser::Kernel(); } // TODO: Return the system's memory utilization float System::MemoryUtilization() { return LinuxParser::MemoryUtilization(); } // TODO: Return the operating system name std::string System::OperatingSystem() { return LinuxParser::OperatingSystem(); } // TODO: Return the number of processes actively running on the system int System::RunningProcesses() { return LinuxParser::RunningProcesses(); } // TODO: Return the total number of processes on the system int System::TotalProcesses() { return LinuxParser::TotalProcesses(); } // TODO: Return the number of seconds since the system started running long int System::UpTime() { return LinuxParser::UpTime(); }
[ "ran.mahadik14@gmail.com" ]
ran.mahadik14@gmail.com
dccaf6011b1d5fc600816ed9fa7af39eff900eb1
af7974d03f96c5701c60206e1d34ca3f5b6919a8
/content/common/gpu/gpu_channel_manager_delegate.h
c89a165ff4a89f0748ee1eca148a7438fed97753
[ "BSD-3-Clause" ]
permissive
bfgeek/chromium
985d563c2bccbff8cf227696f5b5120a961d81e6
3de75ff3508e61832615c0524b686d17c70e7095
refs/heads/master
2023-03-16T01:41:26.468268
2016-03-14T20:23:28
2016-03-14T20:23:28
53,888,352
0
0
null
2016-03-14T20:09:10
2016-03-14T20:09:10
null
UTF-8
C++
false
false
2,862
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_GPU_GPU_CHANNEL_MANAGER_DELEGATE_H_ #define CONTENT_COMMON_GPU_GPU_CHANNEL_MANAGER_DELEGATE_H_ #include "gpu/command_buffer/common/constants.h" #include "gpu/ipc/common/surface_handle.h" class GURL; namespace IPC { struct ChannelHandle; } namespace content { struct AcceleratedSurfaceBuffersSwappedParams; struct GPUMemoryUmaStats; class GpuChannelManagerDelegate { public: // Sets the currently active URL. Use GURL() to clear the URL. virtual void SetActiveURL(const GURL& url) = 0; // Tells the delegate that a context has subscribed to a new target and // the browser should start sending the corresponding information virtual void AddSubscription(int32_t client_id, unsigned int target) = 0; // Tells the delegate that an offscreen context was created for the provided // |active_url|. virtual void DidCreateOffscreenContext(const GURL& active_url) = 0; // Notification from GPU that the channel is destroyed. virtual void DidDestroyChannel(int client_id) = 0; // Tells the delegate that an offscreen context was destroyed for the provided // |active_url|. virtual void DidDestroyOffscreenContext(const GURL& active_url) = 0; // Tells the delegate that a context was lost. virtual void DidLoseContext(bool offscreen, gpu::error::ContextLostReason reason, const GURL& active_url) = 0; // Tells the delegate about GPU memory usage statistics for UMA logging. virtual void GpuMemoryUmaStats(const GPUMemoryUmaStats& params) = 0; // Tells the delegate that no contexts are subscribed to the target anymore // so the delegate should stop sending the corresponding information. virtual void RemoveSubscription(int32_t client_id, unsigned int target) = 0; // Tells the delegate to cache the given shader information in persistent // storage. The embedder is expected to repopulate the in-memory cache through // the respective GpuChannelManager API. virtual void StoreShaderToDisk(int32_t client_id, const std::string& key, const std::string& shader) = 0; #if defined(OS_MACOSX) // Tells the delegate that an accelerated surface has swapped. virtual void SendAcceleratedSurfaceBuffersSwapped( const AcceleratedSurfaceBuffersSwappedParams& params) = 0; #endif #if defined(OS_WIN) virtual void SendAcceleratedSurfaceCreatedChildWindow( gpu::SurfaceHandle parent_window, gpu::SurfaceHandle child_window) = 0; #endif protected: virtual ~GpuChannelManagerDelegate() {} }; } // namespace content #endif // CONTENT_COMMON_GPU_GPU_CHANNEL_MANAGER_DELEGATE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8fb42a832502589cca1b2a3bf4a3d065cc440a6f
7cc367b30964ac4376f289ff0495831c77f7f38c
/20.有效的括号.cpp
6dd7b25ba07c88753d7d18468330de06086870dc
[]
no_license
HOoOF88/.leetcode
484bbead7128055fe392ed282fb63fddbe5a84e6
aba79b4727b505b5cd834ebb3177dd531628aa17
refs/heads/master
2023-06-10T05:18:18.392939
2021-06-13T05:56:00
2021-06-13T05:56:00
373,693,087
0
0
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
// @before-stub-for-debug-begin #include <vector> #include <string> #include "commoncppproblem20.h" using namespace std; // @before-stub-for-debug-end /* * @lc app=leetcode.cn id=20 lang=cpp * * [20] 有效的括号 */ // @lc code=start #include <bits/stdc++.h> using namespace std; class Solution { public: bool isValid(string s) { stack<char> st; int l = s.length(); int i = 0; if(l==1) return false; while(i<l) { if(s[i] == '(' || s[i] == '[' || s[i] == '{') { st.push(s[i]); } else { if(st.empty()) { return false; } bool a = s[i] == ')' && st.top() == '('; bool b = s[i] == '}' && st.top() == '{'; bool c = s[i] == ']' && st.top() == '['; if( a||b||c ) { st.pop(); } else { return false; } } i++; } if(st.empty()) { return true; } return false; } }; // @lc code=end
[ "hf904178460@gmail.com" ]
hf904178460@gmail.com
c5afbe0b63090d9a30b1f33ec4d6438854d01d38
914be969990885182d03b5c99d7a338ce9d76f57
/stack_balanced.cpp
7055f999cc15a7705fa65d20305f07cc410eb86f
[]
no_license
ketaki04/Data_structures
6cd1fd8f1cbda51437fffeaa065afbaf1f448829
bc79f11c2c708c98f3af1495d7155a5a578a14e4
refs/heads/master
2022-11-20T01:18:43.166678
2020-07-16T09:29:15
2020-07-16T09:29:15
263,404,422
0
0
null
null
null
null
UTF-8
C++
false
false
958
cpp
//Using stack to detect the the balanced paranthesis #include<iostream> #include<stack> #include<string> using namespace std; bool ArePair(char opening,char closing) { if(opening== '(' && closing==')') return true; else if(opening== '[' && closing==']') return true; else if(opening== '{' && closing=='}') return true; return false; } bool AreParanthesisBalanced(string exp) { stack<char> S; for(int i=0;i<exp.length();i++) { if(exp[i]=='('||exp[i]=='['||exp[i]=='{') S.push(exp[i]); else if (exp[i]==')'||exp[i]==']'||exp[i]=='}') { if(S.empty() || !ArePair(S.top(),exp[i])) return false; else S.pop(); } } return S.empty() ? true:false; } int main() { string exp; cout<<"enter the string to check"; cin>>exp; if(AreParanthesisBalanced(exp)) cout<<"Balanced"; else cout<<"Not_Balanced"; return 0; }
[ "ketaki.s.k2000@gmail.com" ]
ketaki.s.k2000@gmail.com
ce4acd78705a416c63df5d353ae80a20dbe83548
9b00394d404ab351050175950b929b09bd0d7351
/11364 - Parking.cpp
eaf721252e24810a4d9f001363abebe061054353
[]
no_license
IElgohary/Uva-solutions
f7a5150942ba6222fc59d455e0164ad462964551
de5b309d4c588eecf52de89a571c2504b55bec5a
refs/heads/master
2021-01-10T17:53:07.719432
2017-11-20T19:18:47
2017-11-20T19:18:47
49,293,636
0
1
null
null
null
null
UTF-8
C++
false
false
365
cpp
/*input 2 4 24 13 89 37 6 7 30 41 14 39 42 */ #include <bits/stdc++.h> using namespace std; int main() { int t , n; int arr[25]; cin >> t; while ( t--) { cin >> n; for ( int i = 0 ; i < n ; i++) cin >> arr[i]; sort(arr , arr+n); int sum = 0; for ( int i = n-1 ; i > 0; i--) { sum += (arr[i] - arr[i-1]); } cout << 2* sum << endl; } }
[ "eslam.elgohary@hotmail.ca" ]
eslam.elgohary@hotmail.ca
3f51685a54bfb5ed2d3f0ac101073ba1ed06a73b
1abf985d2784efce3196976fc1b13ab91d6a2a9e
/opentracker/include/OpenTracker/input/PhantomSink.h
a76e0ff3a5b64377c5769c87e97ee788fd4a3240
[ "BSD-3-Clause" ]
permissive
dolphinking/mirror-studierstube
2550e246f270eb406109d4c3a2af7885cd7d86d0
57249d050e4195982c5380fcf78197073d3139a5
refs/heads/master
2021-01-11T02:19:48.803878
2012-09-14T13:01:15
2012-09-14T13:01:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,095
h
#ifndef _PHANTOM_SINK_H #define _PHANTOM_SINK_H /* ======================================================================== * Copyright (c) 2006, * Institute for Computer Graphics and Vision * Graz University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Graz University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ======================================================================== * PROJECT: OpenTracker * ======================================================================== */ /** header file for PhantomModule. * * @author Christian Fast * * $Id$ * @file */ /* ======================================================================= */ #ifdef USE_PHANTOM // Holds data retrieved from HDAPI. typedef struct { HDdouble force[3]; HDErrorInfo error; HHD handle; } DeviceInputData; namespace ot { class OPENTRACKER_API PhantomSink : public Node { public: /* Container for tracking data*/ Event state; int changed; HHD deviceHandle; HDSchedulerHandle schedulerHandle; bool feedback; float ramprate; DeviceInputData *currentData; PhantomSink(): Node(), changed(1) {} ~PhantomSink(){} int isEventGenerator() { return 1; } /* If something has happened, move Aesop. Who created the * event (the generator) is irrelevant for me now */ virtual void onEventGenerated( Event& event, Node& generator) { state = event; changed = 1; updateObservers( event ); } friend class PhantomModule; }; } #endif // USE_PHANTOM #endif // _PHANTOM_SOURCE_H
[ "s.astanin@gmail.com" ]
s.astanin@gmail.com
03ed37a3056142c156fc30395b3f870619d491bc
d68eb2a3f13dee7ef8a93563b2d6fe16a9b771e6
/SpMV/spmvf_with_data_formatting/src/spmv_mohammad_tb.cpp
72677a6b601bfdfb92ccb318361f2e597554268f
[]
no_license
AminSahebi/SDSoC-Benchmarks
f0ad6cdc6604fbd6365be545cf75fe790635b8bd
9a78baf6e2929e789cfabab6f7458dbc4b64b4cf
refs/heads/master
2023-02-17T11:54:04.951358
2021-01-20T15:57:17
2021-01-20T15:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,134
cpp
/* File: spmv_mohammad_tb.h * Copyright (c) [2016] [Mohammad Hosseinabady (mohammad@hosseinabady.com)] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== * * File name : spmv_mohammad_tb.h * Author : Mohammad Hosseinabady mohammad@hosseinabady.com * Date : 14 September 2018 * Blog : https://highlevel-synthesis.com/ * Project : ENEAC project at Bristol University (Jose Nunez-Yanez) */ #include <stdio.h> #include <stdlib.h> #include "spmv_mohammad.h" #include <math.h> #include <sds_lib.h> #include <stdint.h> #include "time.h" #include <sys/time.h> double getTimestamp() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_usec + tv.tv_sec*1e6; } double software_start; double software_end; double software_execution_time; double hardware_start; double hardware_end; double hardware_execution_time; DATA_TYPE *values; int *col_indices; int *row_ptr; DATA_TYPE *x; DATA_TYPE *y_fpga; DATA_TYPE *y_gold; int row_size = 2000; int col_size = 2000; int nnz = 0; #define M 1 int read_mtx_SpMV(char* inFilename, int *row_size, int *col_size, int *nnz) { DATA_TYPE *cooValHostPtr = 0; int *cooRowIndexHostPtr = 0; int *cooColIndexHostPtr = 0; FILE *fp_input; int r; int c; DATA_TYPE v; fp_input = fopen(inFilename, "r"); int nnzeo_false = 0; if (fp_input != NULL) { char line[1000]; while (fgets(line, sizeof line, fp_input) != NULL) {// read a line from a file if (line[0] != '%') { sscanf(line, "%d %d %d", row_size, col_size, nnz); cooRowIndexHostPtr = (int *)malloc(*nnz * sizeof(int)); cooColIndexHostPtr = (int *)malloc(*nnz * sizeof(int)); cooValHostPtr = (DATA_TYPE *)malloc(*nnz * sizeof(DATA_TYPE)); if ((!cooRowIndexHostPtr) || (!cooColIndexHostPtr) || (!cooValHostPtr)) { printf("Host malloc failed (matrix)\n"); return 1; } int line_number = 0; while (fgets(line, sizeof line, fp_input) != NULL) {// read a line from a file sscanf(line, "%d %d %f", &r, &c, &v); if (v == 0) { // printf("r = %d col = %d val=%lf\n", r, c, v); nnzeo_false++; continue; } r--; c--; //find row place (cooRowIndexHostPtr)[line_number] = r; (cooColIndexHostPtr)[line_number] = c; (cooValHostPtr)[line_number] = v; line_number++; } } } } else { perror(inFilename); //print the error message on stderr. exit(1); } *nnz = *nnz - nnzeo_false; int *cooRowIndexHostNewPtr = (int *)malloc(sizeof(int) * *nnz); int *cooColIndexHostNewPtr = (int *)malloc(sizeof(int) * *nnz); DATA_TYPE *cooValHostNewPtr = (DATA_TYPE *)malloc(sizeof(DATA_TYPE) * *nnz); int index = 0; for (int i = 0; i < *row_size; i++) { for (int j = 0; j < *nnz; j++) { if (cooRowIndexHostPtr[j] == i) { cooRowIndexHostNewPtr[index] = cooRowIndexHostPtr[j]; cooColIndexHostNewPtr[index] = cooColIndexHostPtr[j]; cooValHostNewPtr[index] = cooValHostPtr[j]; index++; } } } // for (int i = 0; i < *nnz; i++) { // printf("%d %d %f\n ", cooRowIndexHostNewPtr[i], cooColIndexHostNewPtr[i], cooValHostNewPtr[i]); // } int d = 0; int r_index = 0; for (r_index = 0; r_index < *row_size; r_index++) { int nonzero_line = 0; for (; d < *nnz; d++) { int current_row_index = cooRowIndexHostNewPtr[d]; if (current_row_index == r_index) { row_ptr[r_index] = d; nonzero_line = 1; break; } } if (nonzero_line==0) { row_ptr[r_index] = row_ptr[r_index-1]; } } row_ptr[r_index]=*nnz; for (int i = 0; i < *nnz; i++) { col_indices[i] = cooColIndexHostNewPtr[i]; values[i] = cooValHostNewPtr[i]; } // for (int i = 0; i < *row_size; i++) { // printf("row_ptr[%d]=%d\n", i, row_ptr[i]); // } free(cooValHostPtr); free(cooRowIndexHostPtr); free(cooColIndexHostPtr); free(cooRowIndexHostNewPtr); } int generateSpMV(int row_size, int col_size, int *nnz) { int rand_index[II*M]; int v_i = 0; int r_i = 0; int index_not_found = 1; for (int ix = 0; ix < row_size; ix++) { row_ptr[r_i] = v_i; int r_tmp = 0; for (int i = 0; i < II*M; i++) { index_not_found = 1; while(index_not_found) { int rand_col_index = rand()%col_size; index_not_found = 0; for (int s = 0; s < r_tmp; s++) { if (rand_index[s] == rand_col_index) { index_not_found = 1; break; } } if (index_not_found == 0) rand_index[r_tmp++] = rand_col_index; } } for (int i = 0; i < II*M; i++) { DATA_TYPE r = (10.0*(rand()+1)/RAND_MAX); values[v_i] = r; col_indices[v_i++] = rand_index[i]; } r_i++; } *nnz = v_i--; row_ptr[r_i]=*nnz; printf("nnz = %d\n", *nnz); return 0; } int gold_spmv() { int i=0, j=0, rowStart=0, rowEnd=row_size; long int k=0; DATA_TYPE y0=0.0; int last_j = 0; for (i = rowStart; i < rowEnd; ++i) { y0 = 0.0; for (j = row_ptr[i] ; j < row_ptr[i+1]; ++j) { y0 += values[j] * x[col_indices[j]]; } y_gold[i] = y0; } return 0; } int main(int argc, char** argv) { if (argc != 2) { printf("please enter the input file name \n"); exit(1); } values = (DATA_TYPE *)sds_alloc_non_cacheable(NNZ_MAX*sizeof(DATA_TYPE)); col_indices = (int *)sds_alloc_non_cacheable(NNZ_MAX*sizeof(int)); row_ptr = (int *)sds_alloc_non_cacheable((ROW_SIZE_MAX+1)*sizeof(int)); x = (DATA_TYPE *)sds_alloc_non_cacheable(COL_SIZE_MAX*sizeof(DATA_TYPE)); y_gold = (DATA_TYPE *)malloc(ROW_SIZE_MAX*sizeof(DATA_TYPE)); y_fpga = (DATA_TYPE *)sds_alloc_non_cacheable(ROW_SIZE_MAX*sizeof(DATA_TYPE)); // generateSpMV(row_size, col_size, &nnz); read_mtx_SpMV(argv[1], &row_size, &col_size, &nnz); for (int i = 0; i < col_size; i++) { x[i] = (1.0*rand()+1.0)/RAND_MAX; } /* for(int i = 0; i < row_size+1; i++) { printf("row_ptr=%d\n", row_ptr[i]); } for(int i = 0; i < nnz; i++) { printf("col_indices=%d, values=%f \n", col_indices[i], values[i]); } for(int i = 0; i < row_size; i++) { printf("y_gold=%f \t y_fpga=%f\n", y_gold[i], y_fpga[i]); } */ gold_spmv(); printf("row_size=%u, col_size=%u, nnz=%u\n", row_size, col_size, nnz); printf("\rHardware version started!\n\r"); hardware_start = getTimestamp(); spmv_mohammad( row_ptr, col_indices, values, y_fpga, x, row_size, row_size, nnz); hardware_end = getTimestamp(); printf("\rHardware version finished!\n\r"); hardware_execution_time = (hardware_end-hardware_start)/(1000); printf("Hardware execution time %.6f ms elapsed\n", hardware_execution_time); int status = 0; for(int i=0;i<row_size;i++) { DATA_TYPE diff = fabs(y_gold[i]-y_fpga[i]); if(diff > 0.1 || diff != diff){ printf("error occurs at %d with value y_hw = %lf, should be y_gold = %lf \n",i,y_fpga[i],y_gold[i]); status = -1; break; } } if(!status) { printf("Hardware Validation PASSED!\n"); } else { printf("Hardware Validation FAILED!\n"); return -1; } sds_free(values); sds_free(col_indices); sds_free(row_ptr); sds_free(x); free(y_gold); sds_free(y_fpga); return status; }
[ "csxmh@bristol.ac.uk" ]
csxmh@bristol.ac.uk
51f5d29f19432ea5dabba65cab22b7a0b95a521a
90c95fd7a5687b1095bf499892b8c9ba40f59533
/sprout/functional/bit_or.hpp
a5adf0712662cdd418f30a43b439a143114d34fb
[ "BSL-1.0" ]
permissive
CreativeLabs0X3CF/Sprout
af60a938fd12e8439a831d4d538c4c48011ca54f
f08464943fbe2ac2030060e6ff20e4bb9782cd8e
refs/heads/master
2021-01-20T17:03:24.630813
2016-08-15T04:44:46
2016-08-15T04:44:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
hpp
/*============================================================================= Copyright (c) 2011-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_FUNCTIONAL_BIT_OR_HPP #define SPROUT_FUNCTIONAL_BIT_OR_HPP #include <utility> #include <sprout/config.hpp> #include <sprout/utility/forward.hpp> #include <sprout/functional/transparent.hpp> namespace sprout { // 20.8.7 bitwise operations template<typename T = void> struct bit_or { public: typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; public: SPROUT_CONSTEXPR T operator()(T const& x, T const& y) const { return x | y; } }; template<> struct bit_or<void> : public sprout::transparent<> { public: template<typename T, typename U> SPROUT_CONSTEXPR decltype(std::declval<T>() | std::declval<U>()) operator()(T&& x, U&& y) const SPROUT_NOEXCEPT_IF_EXPR(std::declval<T>() | std::declval<U>()) { return SPROUT_FORWARD(T, x) | SPROUT_FORWARD(U, y); } }; } // namespace sprout #endif // #ifndef SPROUT_FUNCTIONAL_BIT_OR_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
3bac51bd24c11ba948f935d1f3e2ca9c68612013
3f78a9da3eecc6d8e401f1cce37e054a252930bc
/[Client]MH/interface/cIconGridDialog.cpp
a4b1837c37fa8aaf5b6eb5e843b1c19a7ae94883
[]
no_license
apik1997/Mosiang-Online-Titan-DarkStroy-Azuga-Source-Code
9055aa319c5371afd1ebd504044160234ddbb418
74d6441754efb6da87855ee4916994adb7f838d5
refs/heads/master
2020-06-14T07:46:03.383719
2019-04-09T00:07:28
2019-04-09T00:07:28
194,951,315
0
0
null
2019-07-03T00:14:59
2019-07-03T00:14:59
null
UHC
C++
false
false
13,520
cpp
// cIconGridDialog.cpp: implementation of the cIconGridDialog class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "cIconGridDialog.h" #include "cWindowManager.h" #include "cIcon.h" #include "../Input/Mouse.h" #include "cScriptManager.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// cIconGridDialog::cIconGridDialog() { m_nRow=m_nCol=0; m_IconDlgID=0; m_wCellBorderX=0; m_wCellBorderY=0; m_wCellWidth=0; m_wCellHeight=0; m_acceptableIconType=0xffffffff; //all accept m_type = WT_ICONGRIDDIALOG; SetRect(&m_cellRect,0,0,0,0); m_lCurSelCellPos = -1; m_lCurDragOverPos = -1; m_nIconType = WT_ICON; m_bItemDraged = FALSE; m_pIconGridCell = NULL; m_bShowGrid = FALSE; #ifdef _JAPAN_LOCAL_ m_DisableFromPos = 0; m_DisableToPos = 0; #endif // _JAPAN_LOCAL #ifdef _HK_LOCAL_ m_DisableFromPos = 0; m_DisableToPos = 0; #endif // _HK_LOCAL #ifdef _TL_LOCAL_ m_DisableFromPos = 0; m_DisableToPos = 0; #endif // _HK_LOCAL } cIconGridDialog::~cIconGridDialog() { SAFE_DELETE_ARRAY(m_pIconGridCell); } void cIconGridDialog::InitDialog(LONG x, LONG y, WORD wid, WORD hei, cImage * basicImage, WORD col, WORD row, LONG ID) { cDialog::Init(x,y,wid,hei,basicImage,ID); m_nRow = row; m_nCol = col; m_pIconGridCell = new cIconGridCell[m_nRow*m_nCol]; for(int i = 0 ; i < m_nRow*m_nCol ; i++) { m_pIconGridCell[i].icon = NULL; m_pIconGridCell[i].use = NOTUSE; } m_wCellBorderX = DEFAULT_CELLBORDER; m_wCellBorderY = DEFAULT_CELLBORDER; m_wCellWidth = DEFAULT_CELLSIZE; m_wCellHeight = DEFAULT_CELLSIZE; SCRIPTMGR->GetImage( 137, &m_GridLockImage, PFT_HARDPATH ); } void cIconGridDialog::InitGrid(LONG grid_x, LONG grid_y, WORD cellWid, WORD cellHei, WORD borderX, WORD borderY) { m_gridPos.x = (float)grid_x; m_gridPos.y = (float)grid_y; m_wCellWidth = cellWid; m_wCellHeight = cellHei; m_wCellBorderX = borderX; m_wCellBorderY = borderY; m_cellRect.left = (LONG)m_gridPos.x; m_cellRect.right = m_cellRect.left + m_nCol*m_wCellWidth+m_wCellBorderX*(m_nCol+1); m_cellRect.top = (LONG)m_gridPos.y; m_cellRect.bottom = m_cellRect.top + m_nRow*m_wCellHeight+m_wCellBorderY*(m_nRow+1); } BOOL cIconGridDialog::PtInCell(LONG x, LONG y) { /* // this is not precise calc // must be modified at last if(m_absPos.x+m_cellRect.left > x || m_absPos.y+m_cellRect.top > y || m_absPos.x+m_cellRect.right < x || m_absPos.y+m_cellRect.bottom < y) return FALSE; else return TRUE; */ for(int i = 0 ; i < m_nCol*m_nRow ; i++) if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon && m_pIconGridCell[i].icon->IsDepend()) { if(m_pIconGridCell[i].icon->PtInWindow(x,y)) return TRUE; } return FALSE; } void cIconGridDialog::SetCellRect(RECT * rect) { CopyRect(&m_cellRect, rect); } void cIconGridDialog::SetAbsXY(LONG x, LONG y) { LONG tmpX = x - (LONG)m_absPos.x; LONG tmpY = y - (LONG)m_absPos.y; for(int i = 0 ; i < m_nCol*m_nRow ; i++) if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon && m_pIconGridCell[i].icon->IsDepend()) { m_pIconGridCell[i].icon->SetAbsXY(tmpX+(LONG)m_pIconGridCell[i].icon->GetAbsX(), tmpY+(LONG)m_pIconGridCell[i].icon->GetAbsY()); } cDialog::SetAbsXY(x,y); } DWORD cIconGridDialog::ActionEvent(CMouse * mouseInfo) { if(!m_bActive) return WE_NULL; DWORD we = WE_NULL; DWORD we2 = WE_NULL; BOOL selCell = FALSE; POSTYPE pos; we = cDialog::ActionEvent(mouseInfo); if( !m_bDisable ) { if(we & WE_LBTNCLICK) { if(GetPositionForXYRef(mouseInfo->GetMouseEventX(),mouseInfo->GetMouseEventY(),pos)) { m_lCurSelCellPos = pos; cbWindowFunc(m_ID, m_pParent, WE_LBTNCLICK); //PPP } } else if(we & WE_LBTNDBLCLICK) { if(GetPositionForXYRef(mouseInfo->GetMouseEventX(),mouseInfo->GetMouseEventY(),pos)) { m_lCurSelCellPos = pos; cbWindowFunc(m_ID, m_pParent, WE_LBTNDBLCLICK); //PPP } } else if(we & WE_RBTNDBLCLICK) { if(GetPositionForXYRef(mouseInfo->GetMouseEventX(),mouseInfo->GetMouseEventY(),pos)) { m_lCurSelCellPos = pos; cbWindowFunc(m_ID, this, WE_RBTNDBLCLICK); } } else { if( mouseInfo->LButtonDrag() ) { if( ( we & WE_MOUSEOVER ) && IsDragOverDraw() && GetPositionForXYRef(mouseInfo->GetMouseX(),mouseInfo->GetMouseY(),pos) ) { m_lCurDragOverPos = pos; m_bItemDraged = TRUE; } else { m_lCurDragOverPos = -1; m_bItemDraged = FALSE; } } else { if( m_bItemDraged ) //드래그후에 끝냈음. { if( GetPositionForXYRef(mouseInfo->GetMouseEventX(),mouseInfo->GetMouseEventY(),pos) ) m_lCurSelCellPos = pos; m_bItemDraged = FALSE; } m_lCurDragOverPos = -1; } } } for(int i = 0 ; i < m_nCol*m_nRow ; i++) { if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon->IsActive() && m_pIconGridCell[i].icon && m_pIconGridCell[i].icon->IsDepend()) m_pIconGridCell[i].icon->ActionEvent(mouseInfo); } return we; } void cIconGridDialog::Render() { cDialog::Render(); VECTOR2 start_pos; if(m_lCurSelCellPos != -1 && !m_SelectedBGImage.IsNull()) { start_pos.x = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(m_lCurSelCellPos%m_nCol+1))+(m_lCurSelCellPos%m_nCol*m_wCellWidth)-2; // 하드 코딩 -2(taiyo temp) start_pos.y = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(m_lCurSelCellPos/m_nCol+1))+(m_lCurSelCellPos/m_nCol*m_wCellHeight)-2; // 하드 코딩 -2(taiyo temp) m_SelectedBGImage.RenderSprite(NULL,NULL,0,&start_pos,RGBA_MERGE(m_dwImageRGB, m_alpha * m_dwOptionAlpha / 100)); } if(m_lCurDragOverPos != -1 && !m_DragOverBGImage.IsNull()) // if(IsDragOverDraw()) { start_pos.x = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(m_lCurDragOverPos%m_nCol+1))+(m_lCurDragOverPos%m_nCol*m_wCellWidth)-2; // 하드 코딩 -2(taiyo temp) start_pos.y = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(m_lCurDragOverPos/m_nCol+1))+(m_lCurDragOverPos/m_nCol*m_wCellHeight)-2; // 하드 코딩 -2(taiyo temp) m_DragOverBGImage.RenderSprite(NULL,NULL,0,&start_pos,RGBA_MERGE(m_dwImageRGB, m_alpha * m_dwOptionAlpha / 100)); } // inverse order for tooltip for(int i = m_nCol*m_nRow-1 ; i >= 0 ; --i) if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon && m_pIconGridCell[i].icon->IsDepend()) m_pIconGridCell[i].icon->Render(); #ifdef _JAPAN_LOCAL_ for(i=m_DisableFromPos; i<m_DisableToPos; ++i) { if( !m_GridLockImage.IsNull() ) { start_pos.x = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(i%m_nCol+1))+(i%m_nCol*m_wCellWidth)-2; start_pos.y = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(i/m_nCol+1))+(i/m_nCol*m_wCellHeight)-2; m_GridLockImage.RenderSprite(NULL,NULL,0,&start_pos,RGBA_MERGE(m_dwImageRGB, m_alpha * m_dwOptionAlpha / 100)); } } #endif // _JAPAN_LOCAL_ #ifdef _HK_LOCAL_ for(i=m_DisableFromPos; i<m_DisableToPos; ++i) { if( !m_GridLockImage.IsNull() ) { start_pos.x = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(i%m_nCol+1))+(i%m_nCol*m_wCellWidth)-2; start_pos.y = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(i/m_nCol+1))+(i/m_nCol*m_wCellHeight)-2; m_GridLockImage.RenderSprite(NULL,NULL,0,&start_pos,RGBA_MERGE(m_dwImageRGB, m_alpha * m_dwOptionAlpha / 100)); } } #endif // _HK_LOCAL_ #ifdef _TL_LOCAL_ for(i=m_DisableFromPos; i<m_DisableToPos; ++i) { if( !m_GridLockImage.IsNull() ) { start_pos.x = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(i%m_nCol+1))+(i%m_nCol*m_wCellWidth)-2; start_pos.y = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(i/m_nCol+1))+(i/m_nCol*m_wCellHeight)-2; m_GridLockImage.RenderSprite(NULL,NULL,0,&start_pos,RGBA_MERGE(m_dwImageRGB, m_alpha * m_dwOptionAlpha / 100)); } } #endif // _HK_LOCAL_ } void cIconGridDialog::SetActive(BOOL val) { if( m_bDisable ) return; cDialog::SetActiveRecursive(val); /// need confirm m_lCurSelCellPos = -1; /// for(int i = 0 ; i < m_nCol*m_nRow ; i++) if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon && m_pIconGridCell[i].icon->IsDepend()) m_pIconGridCell[i].icon->SetActive(val); } void cIconGridDialog::SetAlpha(BYTE al) { cDialog::SetAlpha(al); for(int i = 0 ; i < m_nCol*m_nRow ; i++) { if(m_pIconGridCell[i].use == USE && m_pIconGridCell[i].icon) m_pIconGridCell[i].icon->SetAlpha(al); } } /**/ /**/ /**/ /**/ // 1-dimension BOOL cIconGridDialog::IsAddable(WORD pos) { ASSERT(pos < m_nCol*m_nRow); if(m_pIconGridCell[pos].use == USE) return FALSE; return TRUE; } BOOL cIconGridDialog::AddIcon(WORD pos, cIcon * icon) { ASSERT(pos < m_nCol*m_nRow); WORD cellX = pos%m_nCol; WORD cellY = pos/m_nCol; // ASSERT(m_pIconGridCell[pos].use == USE); if(m_pIconGridCell[pos].use == USE) return FALSE; icon->SetAbsXY((LONG)(m_absPos.x+m_cellRect.left+(m_wCellBorderX*(cellX+1))+((cellX)*m_wCellWidth)), (LONG)(m_absPos.y+m_cellRect.top+(m_wCellBorderY*(cellY+1))+((cellY)*m_wCellHeight))); icon->SetDepend(TRUE); icon->SetActive(m_bActive); m_pIconGridCell[pos].icon = icon; m_pIconGridCell[pos].use = USE; icon->SetParent(this); //현재 창이 디스에이블상태면 아이콘도 디스에이블로 if( m_bDisable ) icon->SetDisable( TRUE ); icon->SetCellPosition(cellX,cellY); return TRUE; } BOOL cIconGridDialog::GetCellAbsPos(WORD pos, int& absX, int& absY) { ASSERT(pos < m_nCol*m_nRow); WORD cellX = pos%m_nCol; WORD cellY = pos/m_nCol; if(m_pIconGridCell[pos].use == NOTUSE) return FALSE; absX = (int)(m_absPos.x+m_cellRect.left+(m_wCellBorderX*(cellX+1))+((cellX)*m_wCellWidth)); absY = (int)(m_absPos.y+m_cellRect.top+(m_wCellBorderY*(cellY+1))+((cellY)*m_wCellHeight)); return TRUE; } // 2-dimension BOOL cIconGridDialog::GetCellPosition(LONG mouseX, LONG mouseY, WORD& cellX,WORD& cellY) { /* int tempX = (mouseX-m_absPos.x-m_cellRect.left)/m_wCellWidth; int tempY = (mouseY-m_absPos.y-m_cellRect.top)/m_wCellHeight; if(tempX<0||tempY<0) return FALSE; cellX = tempX; cellY = tempY; return TRUE; */ for(int i = 0 ; i < m_nCol ; i++) { for(int j = 0 ; j < m_nRow ; j++) { int cellpX = (int)(m_absPos.x+m_cellRect.left+(m_wCellBorderX*(i+1))+(i*m_wCellWidth)); int cellpY = (int)(m_absPos.y+m_cellRect.top+(m_wCellBorderY*(j+1))+(j*m_wCellHeight)); if(cellpX < mouseX && mouseX < cellpX + DEFAULT_CELLSIZE && cellpY < mouseY && mouseY < cellpY + DEFAULT_CELLSIZE) { cellX = i; cellY = j; return TRUE; } } } return FALSE; } BOOL cIconGridDialog::GetPositionForXYRef(LONG mouseX, LONG mouseY, WORD& pos) { /* int cellX = (mouseX-m_absPos.x-m_cellRect.left)/m_wCellWidth; int cellY = (mouseY-m_absPos.y-m_cellRect.top)/m_wCellHeight; if(cellX<0||cellY<0) return FALSE; pos = (cellY)*m_nCol+(cellX); */ /* for(int i = 0 ; i < m_nCol ; i++) { for(int j = 0 ; j < m_nRow ; j++) { int cellpX = m_absPos.x+m_cellRect.left+(m_wCellBorderX*(i+1))+(i*m_wCellWidth); int cellpY = m_absPos.y+m_cellRect.top+(m_wCellBorderY*(j+1))+(j*m_wCellHeight); if(cellpX < mouseX && mouseX < cellpX + DEFAULT_CELLSIZE && cellpY < mouseY && mouseY < cellpY + DEFAULT_CELLSIZE) { pos = j*m_nCol+i; return TRUE; } } } return FALSE; */ WORD x,y; BOOL rt = GetCellPosition(mouseX, mouseY, x, y); pos = y*m_nCol+x; //tmp) pos = GetPositionForCell(x,y); return rt; } WORD cIconGridDialog::GetPositionForCell(WORD cellX, WORD cellY) { return (cellY)*m_nCol+(cellX); } BOOL cIconGridDialog::IsAddable(WORD cellX,WORD cellY,cIcon* pIcon) { if(m_pIconGridCell[cellY*m_nCol+cellX].use == USE) return FALSE; if(!(pIcon->GetIconType() & m_acceptableIconType)) return FALSE; return TRUE; } BOOL cIconGridDialog::AddIcon(WORD cellX, WORD cellY, cIcon * icon) { return AddIcon(cellX+cellY*m_nCol, icon); } BOOL cIconGridDialog::MoveIcon(WORD cellX, WORD cellY, cIcon * icon) { //KES 040511 에러리턴 수정 if( !IsAddable( GetPositionForCell( cellX, cellY ) ) ) return FALSE; cIconGridDialog* pBeforeGrid = (cIconGridDialog*)icon->GetParent(); WORD wOldCellX = icon->GetCellX(); WORD wOldCellY = icon->GetCellY(); if( pBeforeGrid->DeleteIcon(icon) == FALSE ) return FALSE; if( AddIcon( cellX, cellY, icon ) ) { return TRUE; } else { pBeforeGrid->AddIcon( wOldCellX, wOldCellY, icon ); return FALSE; } } BOOL cIconGridDialog::DeleteIcon(cIcon * icon) { WORD x = icon->GetCellX(); WORD y = icon->GetCellY(); cIcon * dummy; return DeleteIcon(x, y, &dummy); } BOOL cIconGridDialog::DeleteIcon(WORD pos, cIcon ** icon) { ASSERT(pos < m_nCol*m_nRow); if(m_pIconGridCell[pos].use == NOTUSE) { if( icon ) *icon = NULL; //ASSERT(0); return FALSE; } if( icon ) *icon = m_pIconGridCell[pos].icon; m_pIconGridCell[pos].icon->SetCellPosition(0,0); m_pIconGridCell[pos].icon->SetDepend(FALSE); m_pIconGridCell[pos].icon = NULL; m_pIconGridCell[pos].use = NOTUSE; return TRUE; } BOOL cIconGridDialog::DeleteIcon(WORD cellX, WORD cellY, cIcon ** iconOut) { return DeleteIcon(cellY*m_nCol+cellX, iconOut); } void cIconGridDialog::SetDisable( BOOL val ) { cDialog::SetDisable( val ); for(int i = 0 ; i < m_nRow*m_nCol ; i++) { if( m_pIconGridCell[i].icon ) m_pIconGridCell[i].icon->SetDisable( val ); } } BOOL cIconGridDialog::IsDragOverDraw() { if( !WINDOWMGR->IsDragWindow() ) return FALSE; cDialog* pDlg = WINDOWMGR->GetDragDlg(); if( pDlg ) if( pDlg->GetType() == m_nIconType ) return TRUE; return FALSE; }
[ "lixeon.lij@gmail.com" ]
lixeon.lij@gmail.com
8baea03f4f4f5dd692edacf32684d752b69577f4
3fbe8a583c440bbe9467cf64bf01ead18903f937
/plasma-with-examples/ch5/ZR/PotentialSolver.h
5dac88f8e2b4480c44fcd415f466b2bd42d24098
[]
no_license
athulpg007/magsail-deorbit
778de5b019972de0ab8177327bc0bfc0a6765cd4
e95d88b7da890e55b06dab0ecd31f71654e6e4b3
refs/heads/main
2023-03-18T01:59:52.687242
2021-02-26T20:06:59
2021-02-26T20:06:59
341,635,931
0
0
null
null
null
null
UTF-8
C++
false
false
2,949
h
#ifndef _SOLVER_H #define _SOLVER_H #include <assert.h> #include "World.h" //structure to hold data for a single row template <int S> struct Row { Row() {for (int i=0;i<S;i++) {a[i]=0;col[i]=-1;}} void operator= (const Row &o) {for (int i=0;i<S;i++) {a[i] = o.a[i];col[i]=o.col[i];}} double a[S]; //coefficients int col[S]; }; /*matrix with up to seven non zero diagonals*/ class Matrix { public: Matrix(int nr):nu{nr} {rows=new Row<nvals>[nr];} Matrix(const Matrix &o):Matrix(o.nu) { for (int r=0;r<nu;r++) rows[r] = o.rows[r]; }; //copy constructor ~Matrix() {if (rows) delete[] rows;} dvector operator*(dvector &v); //matrix-vector multiplication double& operator() (int r, int c); //reference to A[r,c] value in a full matrix void clearRow(int r) {rows[r]=Row<nvals>();} //reinitializes a row Matrix diagSubtract(dvector &P); //subtracts a vector from the diagonal Matrix invDiagonal(); //returns a matrix containing inverse of our diagonal double multRow(int r, dvector &x); //multiplies row r with vector x static constexpr int nvals = 5; //maximum 7 non-zero values const int nu; //number of rows (unknowns) protected: Row<nvals> *rows; //row data }; enum SolverType {GS, PCG, QN}; class PotentialSolver { public: /*constructor*/ PotentialSolver(World &world, SolverType type, int max_it, double tol): world(world), solver_type(type), A(world.ni*world.nj), max_solver_it(max_it), tolerance(tol) { buildMatrix(); } /*sets reference values*/ void setReferenceValues(double phi0, double Te0, double n0) { this->phi0 = phi0; this->Te0 = Te0; this->n0 = n0; } /*computes electric field = -gradient(phi)*/ void computeEF(); /*builds the "A" matrix for linear potential solver*/ void buildMatrix(); //calls the appropriate potential solver bool solve() { switch(solver_type) { case GS: return solveNR(); case PCG: return solveNR(); case QN: return solveQN(); default: return false; } } protected: World &world; SolverType solver_type; Matrix A; //system matrix for the linear equation enum NodeType {REG,NEUMANN,DIRICHLET}; std::vector<NodeType> node_type; //flag for different node types unsigned max_solver_it; //maximum number of solver iterations double tolerance; //solver tolerance double phi0 = 0; //reference plasma potential double n0 = 1e12; //reference electron density double Te0 = 1.5; //reference electron temperature in eV /*computes potential using quasineutral boltzmann model*/ bool solveQN(); /*solves non-linear potential using Gauss-Seidel*/ bool solveGS(); /*linear PCG solver for Ax=b system*/ bool linearSolvePCG(Matrix &A, dvector &x, dvector &b); /*linear GS solver for Ax=b system*/ bool linearSolveGS(Matrix &A, dvector &x, dvector &b); /*Newton Raphson solver for a nonlinear system, uses PCG for the linear solve*/ bool solveNR(); }; #endif
[ "athulpg007@gmail.com" ]
athulpg007@gmail.com
1bb70383c68bdabae837724fea259f389986d389
dba68ca53ce02985ed1b49f6813d578d24e94b27
/ProjectsServer/GameServer/FieldServer/InfinityManager.cpp
b018bdb7c7268f191f1be405ebd50bc322326ecf
[]
no_license
DeathRivals/OpenAo
afd6c1fe6ddc00e3765c290f485805a7b3e0db59
bf6be4ee29b1f08588fe7fd12c02c8df94d705f5
refs/heads/master
2021-02-15T18:23:37.814569
2020-03-04T14:39:38
2020-03-04T14:39:38
244,919,960
2
2
null
2020-03-04T14:22:07
2020-03-04T14:22:07
null
UHC
C++
false
false
82,182
cpp
// InfinityManager.cpp: implementation of the CInfinityManager class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "InfinityManager.h" #include "FieldGlobal.h" #include "InfinityTickManager.h" #include "FieldIOCPSocket.h" // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CInfinityManager::CInfinityManager() { InitializeCriticalSection(&m_criticalSectionCreate); // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 this->InitInfinityManager(); } CInfinityManager::~CInfinityManager() { DeleteCriticalSection(&m_criticalSectionCreate); // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 m_pTickManager->CleanThread(); util::del(m_pTickManager); } void CInfinityManager::InitInfinityManager() { m_vectInfiModeInfo.clear(); m_vectInfiMonsterInfo.clear(); m_mtvectInfiBossRush.clear(); m_mtvectInfiDefence.clear(); m_mtvectInfiMShipBattle.clear(); // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 m_nInfinityCreateUID = 1; m_mtInfinityDisConnectUserList.clearLock(); // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리 m_pTickManager = new CInfinityTickManager(this); } void CInfinityManager::SetInfinityMapManagerW(CFieldMapWorkspace * i_pFieldMapWorkspace) { this->m_InfiMapManager.SetInfinityMapManager(i_pFieldMapWorkspace); } BOOL CInfinityManager::SetDBManager(CAtumFieldDBManager * i_pAtumDBManager) { if(NULL == i_pAtumDBManager) { return FALSE; } m_pAtumDBManager = i_pAtumDBManager; return TRUE; } void CInfinityManager::SetCinemaInfoW(vectorCinemaInfo * i_pVectCinemaInfo) { this->m_Cinema.SetCinemaInfo(i_pVectCinemaInfo); } void CInfinityManager::SetRevisionInfoW(vectorRevisionInfo * i_pVectRevisionInfo) { this->m_Revision.SetRevisionInfo(i_pVectRevisionInfo); } void CInfinityManager::SetDBInfinityModeInfo(vectorInfinityModeInfo * i_pVectInfiModeInfo) { if(i_pVectInfiModeInfo) { m_vectInfiModeInfo.clear(); m_vectInfiModeInfo.assign(i_pVectInfiModeInfo->begin(), i_pVectInfiModeInfo->end()); m_InfiMapManager.InitInfinityMapInfoList(&m_vectInfiModeInfo); } } void CInfinityManager::SetDBInfinityMonsterInfo(vectorInfinityMonsterInfo * i_pVectInfiMonsterInfo) { if(i_pVectInfiMonsterInfo) { m_vectInfiMonsterInfo.clear(); m_vectInfiMonsterInfo.assign(i_pVectInfiMonsterInfo->begin(), i_pVectInfiMonsterInfo->end()); } } void CInfinityManager::GetInfinityModeInfo(vectorInfinityModeInfo * o_pCopyVectInfiModeInfo) { if(o_pCopyVectInfiModeInfo) { o_pCopyVectInfiModeInfo->clear(); o_pCopyVectInfiModeInfo->assign(m_vectInfiModeInfo.begin(), m_vectInfiModeInfo.end()); } } INT CInfinityManager::MakeMsgInfinityPlayingList(INFINITY_READY_LIST * o_pInfinityPlayingList, MapIndex_t i_nInfinityMapIdx, eINFINITY_MODE i_nInfinityMode, BYTE i_byInfluenceType) { if( NULL == o_pInfinityPlayingList ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return FALSE; } INT PlayingListCount = 0; switch (i_nInfinityMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for( ; itr != m_mtvectInfiBossRush.end(); itr++ ) { if(SIZE_MAX_PACKET < MSG_SIZE(MSG_FC_INFINITY_READY_LIST_OK) + sizeof(INFINITY_READY_LIST) * (PlayingListCount+1)) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 break; } if( i_nInfinityMapIdx == (*itr)->GetInfinityMapIndex() && INFINITY_STATE_UNPREPARED == (*itr)->GetInfinityState() && i_byInfluenceType == (*itr)->GetInfluenceType() ) { o_pInfinityPlayingList[PlayingListCount].InfinityCreateUID = (*itr)->GetInfinityCreateUID(); o_pInfinityPlayingList[PlayingListCount].PlayingRoomMemberCount = (*itr)->GetPlayerListSize(); o_pInfinityPlayingList[PlayingListCount].MaxMemberCount = (*itr)->GetMaxPlayerSize(); util::strncpy(o_pInfinityPlayingList[PlayingListCount].MasterName, (*itr)->GetMasterPlayerName(), SIZE_MAX_CHARACTER_NAME); util::strncpy(o_pInfinityPlayingList[PlayingListCount].InfinityTeamName, (*itr)->GetInfinityTeamName(), SIZE_MAX_PARTY_NAME); // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) o_pInfinityPlayingList[PlayingListCount].DifficultLevel = (*itr)->GetDifficultyLevel(); PlayingListCount++; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for( ; itr != m_mtvectInfiDefence.end(); itr++ ) { if( SIZE_MAX_PACKET < MSG_SIZE(MSG_FC_INFINITY_READY_LIST_OK) + sizeof(INFINITY_READY_LIST) * (PlayingListCount+1)) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 break; } if( i_nInfinityMapIdx == (*itr)->GetInfinityMapIndex() && INFINITY_STATE_UNPREPARED == (*itr)->GetInfinityState() && i_byInfluenceType == (*itr)->GetInfluenceType() ) { o_pInfinityPlayingList[PlayingListCount].InfinityCreateUID = (*itr)->GetInfinityCreateUID(); o_pInfinityPlayingList[PlayingListCount].PlayingRoomMemberCount = (*itr)->GetPlayerListSize(); o_pInfinityPlayingList[PlayingListCount].MaxMemberCount = (*itr)->GetMaxPlayerSize(); util::strncpy(o_pInfinityPlayingList[PlayingListCount].MasterName, (*itr)->GetMasterPlayerName(), SIZE_MAX_CHARACTER_NAME); util::strncpy(o_pInfinityPlayingList[PlayingListCount].InfinityTeamName, (*itr)->GetInfinityTeamName(), SIZE_MAX_PARTY_NAME); // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) o_pInfinityPlayingList[PlayingListCount].DifficultLevel = (*itr)->GetDifficultyLevel(); PlayingListCount++; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 case INFINITY_MODE_MSHIPBATTLE: { mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for( ; itr != m_mtvectInfiMShipBattle.end(); itr++ ) { if( SIZE_MAX_PACKET < MSG_SIZE(MSG_FC_INFINITY_READY_LIST_OK) + sizeof(INFINITY_READY_LIST) * (PlayingListCount+1)) { break; } if( i_nInfinityMapIdx == (*itr)->GetInfinityMapIndex() && INFINITY_STATE_UNPREPARED == (*itr)->GetInfinityState() && i_byInfluenceType == (*itr)->GetInfluenceType() ) { o_pInfinityPlayingList[PlayingListCount].InfinityCreateUID = (*itr)->GetInfinityCreateUID(); o_pInfinityPlayingList[PlayingListCount].PlayingRoomMemberCount = (*itr)->GetPlayerListSize(); o_pInfinityPlayingList[PlayingListCount].MaxMemberCount = (*itr)->GetMaxPlayerSize(); util::strncpy(o_pInfinityPlayingList[PlayingListCount].MasterName, (*itr)->GetMasterPlayerName(), SIZE_MAX_CHARACTER_NAME); util::strncpy(o_pInfinityPlayingList[PlayingListCount].InfinityTeamName, (*itr)->GetInfinityTeamName(), SIZE_MAX_PARTY_NAME); o_pInfinityPlayingList[PlayingListCount].DifficultLevel = (*itr)->GetDifficultyLevel(); PlayingListCount++; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; // end 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 } return PlayingListCount; } BOOL CInfinityManager::CheckInfinityModeLevel(InfiModeUID_t i_nInfinityModeUID, Lv_t i_Lv) { vectorInfinityModeInfo::iterator itr = m_vectInfiModeInfo.begin(); for(; itr != m_vectInfiModeInfo.end(); itr++) { if(i_nInfinityModeUID == itr->InfinityModeUID) { if(i_Lv >= itr->MinLv && i_Lv <= itr->MaxLv) { return TRUE; } else { return FALSE; } } } return FALSE; } // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - BOOL CInfinityManager::CheckEntranceCount(InfiModeUID_t i_nInfinityModeUID, EntranceCount_t i_EntranceCount, int i_nAddLimiteCnt/*=0*/) { vectorInfinityModeInfo::iterator itr = m_vectInfiModeInfo.begin(); for(; itr != m_vectInfiModeInfo.end(); itr++) { if(i_nInfinityModeUID == itr->InfinityModeUID) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크, 밑과 같이 수정 // if(i_EntranceCount <= itr->EntranceCount) { if(i_EntranceCount < itr->EntranceCount + i_nAddLimiteCnt) // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - 추가 카운트 { return TRUE; } else { return FALSE; } } } return FALSE; } // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) /****************************************************************************************************************** ** ** 인피니티 방 생성. ** ** Create Info : ??. ??. ?? ** ** Update Info : 2010. 05. 28. by hsLee. - 인피니티 난이도 조절 관련, 방 생성시 넘겨 받을 방 난이도 인자 추가. ** *******************************************************************************************************************/ //BOOL CInfinityManager::CreateInfinity(MSG_FC_INFINITY_CREATE * i_pInfinityCreateInfo, CFieldIOCPSocket * i_pFISoc, InfinityCreateUID_t * o_pCreateUID) BOOL CInfinityManager::CreateInfinity(MSG_FC_INFINITY_CREATE * i_pInfinityCreateInfo, CFieldIOCPSocket * i_pFISoc, InfinityCreateUID_t * o_pCreateUID , INT * o_nInfinityDifficultyLevel ) // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) { if(NULL == i_pInfinityCreateInfo || NULL == i_pFISoc || NULL == o_pCreateUID // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) || NULL == o_nInfinityDifficultyLevel // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return FALSE; } BOOL CheckInvalidInputValue = FALSE; INFINITY_MODEINFO InfinityModeInfo; util::zero(&InfinityModeInfo, sizeof(INFINITY_MODEINFO)); vectorInfinityModeInfo::iterator itr = m_vectInfiModeInfo.begin(); for(; itr != m_vectInfiModeInfo.end(); itr++) { // 유효한 입력 값인지 체크하고 생성하려고 하는 인피 모드 정보를 가져온다. if(itr->InfinityModeUID == i_pInfinityCreateInfo->InfinityModeUID && itr->MapIdx == i_pInfinityCreateInfo->MapIndex && itr->ModeTypeNum == i_pInfinityCreateInfo->InfinityMode) { InfinityModeInfo = *itr; CheckInvalidInputValue = TRUE; break; } } if(FALSE == CheckInvalidInputValue) { return FALSE; } // Cinema, Revision 정보 여기서 만들기 vectorCinemaInfo CinemaInfoList; util::zero(&CinemaInfoList, sizeof(vectorCinemaInfo)); EnterCriticalSection(&m_criticalSectionCreate); // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 switch (i_pInfinityCreateInfo->InfinityMode) { case INFINITY_MODE_BOSSRUSH: { g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::CreateInfinity# BossRush Created !, MapIdx(%d) \r\n", m_nInfinityCreateUID); CInfinityBossrush * InfiBossRush = new CInfinityBossrush(); InfiBossRush->SetInfinityCreateUID(m_nInfinityCreateUID); InfiBossRush->SetModeInfo(&InfinityModeInfo); InfiBossRush->SetCinemaInfo(this->m_Cinema.GetCinemaInfo(InfinityModeInfo.CinemaNum, &CinemaInfoList)); InfiBossRush->SetInfinityTeamName(i_pInfinityCreateInfo->InfinityTeamName); InfiBossRush->InitMasterPlayer(i_pFISoc); // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) - 방의 난이도 레벨 설정. InfiBossRush->SetDifficultyLevel ( i_pInfinityCreateInfo->InfinityDifficultyLevel ); *o_nInfinityDifficultyLevel = InfiBossRush->GetDifficultyLevel(); // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) - 방의 난이도 레벨 설정. mt_auto_lock mta(&m_mtvectInfiBossRush); m_mtvectInfiBossRush.push_back(InfiBossRush); mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::CreateInfinity# Defence Created !, MapIdx(%d) \r\n", m_nInfinityCreateUID, InfinityModeInfo.MapIdx); CInfinityDefence * InfiDefence = new CInfinityDefence(); InfiDefence->SetInfinityCreateUID(m_nInfinityCreateUID); InfiDefence->SetModeInfo(&InfinityModeInfo); InfiDefence->SetCinemaInfo(this->m_Cinema.GetCinemaInfo(InfinityModeInfo.CinemaNum, &CinemaInfoList)); InfiDefence->SetInfinityTeamName(i_pInfinityCreateInfo->InfinityTeamName); InfiDefence->InitMasterPlayer(i_pFISoc); // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) - 방의 난이도 레벨 설정. InfiDefence->SetDifficultyLevel ( i_pInfinityCreateInfo->InfinityDifficultyLevel ); *o_nInfinityDifficultyLevel = InfiDefence->GetDifficultyLevel(); // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) - 방의 난이도 레벨 설정. mt_auto_lock mta(&m_mtvectInfiDefence); m_mtvectInfiDefence.push_back(InfiDefence); mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 case INFINITY_MODE_MSHIPBATTLE: { #ifdef S_INFINITY3_HSKIM // ON/OFF 기능 구현 #else LeaveCriticalSection(&m_criticalSectionCreate); return FALSE; #endif g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::CreateInfinity# MShipBattle Created !, MapIdx(%d) \r\n", m_nInfinityCreateUID, InfinityModeInfo.MapIdx); CInfinityMShipBattle * InfiMShipBattle = new CInfinityMShipBattle(); InfiMShipBattle->SetInfinityCreateUID(m_nInfinityCreateUID); InfiMShipBattle->SetModeInfo(&InfinityModeInfo); InfiMShipBattle->SetCinemaInfo(this->m_Cinema.GetCinemaInfo(InfinityModeInfo.CinemaNum, &CinemaInfoList)); InfiMShipBattle->SetInfinityTeamName(i_pInfinityCreateInfo->InfinityTeamName); InfiMShipBattle->InitMasterPlayer(i_pFISoc); InfiMShipBattle->SetDifficultyLevel ( i_pInfinityCreateInfo->InfinityDifficultyLevel ); *o_nInfinityDifficultyLevel = InfiMShipBattle->GetDifficultyLevel(); mt_auto_lock mta(&m_mtvectInfiMShipBattle); m_mtvectInfiMShipBattle.push_back(InfiMShipBattle); mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; // end 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 default : { LeaveCriticalSection(&m_criticalSectionCreate); // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return FALSE; } // default } *o_pCreateUID = m_nInfinityCreateUID; m_nInfinityCreateUID++; LeaveCriticalSection(&m_criticalSectionCreate); // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return TRUE; } Err_t CInfinityManager::JoinCheckInfinity(MSG_FC_INFINITY_JOIN * i_pInfinityJoinRequestInfo, CFieldIOCPSocket * i_pFISoc) { if(NULL == i_pInfinityJoinRequestInfo || NULL == i_pFISoc) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 인피 가입 전 체크 사항 switch (i_pInfinityJoinRequestInfo->InfinityMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_pInfinityJoinRequestInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->JoinCheck(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_pInfinityJoinRequestInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->JoinCheck(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_pInfinityJoinRequestInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->JoinCheck(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } Err_t CInfinityManager::JoinInfinity(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, CFieldIOCPSocket * i_pFISoc) { if(NULL == i_pFISoc) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 인피 가입 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Join(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Join(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Join(i_pFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } void CInfinityManager::GetPlayerListW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, vectCFieldIOCPSocket * o_pInfinityMemberList, ClientIndex_t * o_pMasterUserClientIdx) { if(NULL == o_pInfinityMemberList || NULL == o_pMasterUserClientIdx) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return; } switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->GetPlayerList(o_pInfinityMemberList, o_pMasterUserClientIdx); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->GetPlayerList(o_pInfinityMemberList, o_pMasterUserClientIdx); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->GetPlayerList(o_pInfinityMemberList, o_pMasterUserClientIdx); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return; } // default } return; } Err_t CInfinityManager::ChangeMasterUserW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, CFieldIOCPSocket * i_pChangeMasterUserFISoc) { if(NULL == i_pChangeMasterUserFISoc) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->ChangeMasterUser(i_pChangeMasterUserFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->ChangeMasterUser(i_pChangeMasterUserFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->ChangeMasterUser(i_pChangeMasterUserFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } Err_t CInfinityManager::LeaveInfinity(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, CFieldIOCPSocket * i_pFISoc) { if(NULL == i_pFISoc) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 인피 탈퇴 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Leave(i_pFISoc); if(0 >= (*itr)->GetPlayerListSize()) { // 2010-04-02 by cmkwon, 인피2차 추가 수정 - g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::LeaveInfinity# BossRush Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itr)->GetInfinityCreateUID(), (*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); // 마지막 유저였다면 방 삭제 this->m_InfiMapManager.ResetInfinityMap((*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); util::del(*itr); itr = m_mtvectInfiBossRush.erase(itr); } return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Leave(i_pFISoc); if(0 >= (*itr)->GetPlayerListSize()) { // 2010-04-02 by cmkwon, 인피2차 추가 수정 - g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::LeaveInfinity# Defence Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itr)->GetInfinityCreateUID(), (*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); // 마지막 유저였다면 방 삭제 this->m_InfiMapManager.ResetInfinityMap((*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); util::del(*itr); itr = m_mtvectInfiDefence.erase(itr); } return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Leave(i_pFISoc); if(0 >= (*itr)->GetPlayerListSize()) { g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::LeaveInfinity# MShipBattle Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itr)->GetInfinityCreateUID(), (*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); this->m_InfiMapManager.ResetInfinityMap((*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); util::del(*itr); itr = m_mtvectInfiMShipBattle.erase(itr); } return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } Err_t CInfinityManager::BanInfinity(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, CFieldIOCPSocket * i_pBanFISoc) { if(NULL == i_pBanFISoc) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 인피 추방 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Ban(i_pBanFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Ban(i_pBanFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { Err_t errCode = (*itr)->Ban(i_pBanFISoc); return errCode; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } Err_t CInfinityManager::StartInfinity(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, CFieldIOCPSocket * i_pFISoc) { if(NULL == i_pFISoc || FALSE == i_pFISoc->IsValidCharacter(FALSE)) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 인피 시작 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_CreateUID); if(pInfinity) { Err_t errCode = pInfinity->Start(i_pFISoc, this->m_InfiMapManager.CreateInfinityMap(pInfinity->GetInfinityMapIndex())); return errCode; } } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_CreateUID); if(pInfinity) { Err_t errCode = pInfinity->Start(i_pFISoc, this->m_InfiMapManager.CreateInfinityMap(pInfinity->GetInfinityMapIndex())); return errCode; } } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_CreateUID); if(pInfinity) { Err_t errCode = pInfinity->Start(i_pFISoc, this->m_InfiMapManager.CreateInfinityMap(pInfinity->GetInfinityMapIndex())); return errCode; } } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } BOOL CInfinityManager::GetRevisionInfoW(REVISIONINFO * o_pRevisionInfo, InfiModeUID_t i_InfinityModeUID, INT i_nUnitKind) { if(NULL == o_pRevisionInfo) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return FALSE; } // 보정치 가져오기 vectorInfinityModeInfo::iterator itr = m_vectInfiModeInfo.begin(); for(; itr != m_vectInfiModeInfo.end(); itr++) { if(i_InfinityModeUID == itr->InfinityModeUID) { if(this->m_Revision.GetRevisionInfo(o_pRevisionInfo, itr->RevisionNum, i_nUnitKind)) { return TRUE; } return FALSE; } } return FALSE; } Err_t CInfinityManager::UserMapLoadedComplete(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, MapIndex_t i_MapIndex) { // 인피 맵 생성 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_CreateUID); if(pInfinity) { return pInfinity->CreateMap(NULL); } } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_CreateUID); if(pInfinity) { return pInfinity->CreateMap(NULL); } } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_CreateUID); if(pInfinity) { return pInfinity->CreateMap(NULL); } } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } void CInfinityManager::StartTick() { m_pTickManager->InitThread(); } void CInfinityManager::DoSecondlyWorkInfinity(ATUM_DATE_TIME *pDateTime) { // Tick { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); while (itr != m_mtvectInfiBossRush.end()) { if((*itr)->CheckDestory()) { // 2010-04-02 by cmkwon, 인피2차 추가 수정 - g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::DoSecondlyWorkInfinity# BossRush Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itr)->GetInfinityCreateUID(), (*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); this->m_InfiMapManager.ResetInfinityMap((*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); util::del(*itr); itr = m_mtvectInfiBossRush.erase(itr); continue; } (*itr)->DoSecondlyWorkInfinity(pDateTime); itr++; } mta.auto_unlock_cancel(); } mt_auto_lock mtD(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); while (itrD != m_mtvectInfiDefence.end()) { if((*itrD)->CheckDestory()) { // 2010-04-02 by cmkwon, 인피2차 추가 수정 - g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::DoSecondlyWorkInfinity# Defence Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itrD)->GetInfinityCreateUID(), (*itrD)->GetInfinityMapIndex(), (*itrD)->GetInfinityChannelIndex()); this->m_InfiMapManager.ResetInfinityMap((*itrD)->GetInfinityMapIndex(), (*itrD)->GetInfinityChannelIndex()); util::del(*itrD); itrD = m_mtvectInfiDefence.erase(itrD); continue; } (*itrD)->DoSecondlyWorkInfinity(pDateTime); itrD++; } mtD.auto_unlock_cancel(); { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); while (itr != m_mtvectInfiMShipBattle.end()) { if((*itr)->CheckDestory()) { g_pFieldGlobal->WriteSystemLogEX(TRUE, "[Notify] [Infinity][%I64d] CInfinityManager::DoSecondlyWorkInfinity# MShipBattle Call CInfinityMapManager::ResetInfinityMap# !, MapInfo<%d(%d)> \r\n" , (*itr)->GetInfinityCreateUID(), (*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); this->m_InfiMapManager.ResetInfinityMap((*itr)->GetInfinityMapIndex(), (*itr)->GetInfinityChannelIndex()); util::del(*itr); itr = m_mtvectInfiMShipBattle.erase(itr); continue; } (*itr)->DoSecondlyWorkInfinity(pDateTime); itr++; } mta.auto_unlock_cancel(); } } void CInfinityManager::CreateKeyMonster_DeadForNextStepW(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx, MonIdx_t i_CreateMonsterIdx) { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_MapIndex == (*itr)->GetInfinityMapIndex() && i_ChannelIdx == (*itr)->GetInfinityChannelIndex()) { (*itr)->CreateKeyMonster_DeadForNextStep(i_CreateMonsterIdx); return; } } mta.auto_unlock_cancel(); mt_auto_lock mtD(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); for(; itrD != m_mtvectInfiDefence.end(); itrD++) { if(i_MapIndex == (*itrD)->GetInfinityMapIndex() && i_ChannelIdx == (*itrD)->GetInfinityChannelIndex()) { (*itrD)->CreateKeyMonster_DeadForNextStep(i_CreateMonsterIdx); return; } } mtD.auto_unlock_cancel(); mt_auto_lock mtT(&m_mtvectInfiMShipBattle); // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mtvectInfiMShipBattle::iterator itrT = m_mtvectInfiMShipBattle.begin(); for(; itrT != m_mtvectInfiMShipBattle.end(); itrT++) { if(i_MapIndex == (*itrT)->GetInfinityMapIndex() && i_ChannelIdx == (*itrT)->GetInfinityChannelIndex()) { (*itrT)->CreateKeyMonster_DeadForNextStep(i_CreateMonsterIdx); return; } } mtT.auto_unlock_cancel(); } // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - 리턴값이 키몬스터 보상 처리 여부 플래그 void CInfinityManager::DeleteKeyMonster_DeadForNextStepW(BOOL *o_pbCompensationFlag, MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx, MonIdx_t i_DeadMonsterIdx) { // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - // mt_auto_lock mta(&m_mtvectInfiBossRush); // mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); // for(; itr != m_mtvectInfiBossRush.end(); itr++) { // if(i_MapIndex == (*itr)->GetInfinityMapIndex() // && i_ChannelIdx == (*itr)->GetInfinityChannelIndex()) { // (*itr)->DeleteKeyMonster_DeadForNextStep(i_DeadMonsterIdx); // return; // } // } // mta.auto_unlock_cancel(); // // mt_auto_lock mtD(&m_mtvectInfiDefence); // mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); // for(; itrD != m_mtvectInfiDefence.end(); itrD++) { // if(i_MapIndex == (*itrD)->GetInfinityMapIndex() // && i_ChannelIdx == (*itrD)->GetInfinityChannelIndex()) { // (*itrD)->DeleteKeyMonster_DeadForNextStep(i_DeadMonsterIdx); // return; // } // } // mtD.auto_unlock_cancel(); /////////////////////////////////////////////////////////////////////////////// // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - { mt_auto_lock mtA(&m_mtvectInfiBossRush); CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { pInfinity->DeleteKeyMonster_DeadForNextStep(o_pbCompensationFlag, i_DeadMonsterIdx); return; } } { mt_auto_lock mtA(&m_mtvectInfiDefence); CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { pInfinity->DeleteKeyMonster_DeadForNextStep(o_pbCompensationFlag, i_DeadMonsterIdx); return; } } { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mtA(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { pInfinity->DeleteKeyMonster_DeadForNextStep(o_pbCompensationFlag, i_DeadMonsterIdx); return; } } } Err_t CInfinityManager::ChoiceTenderItemW(DiceCnt_t *o_pDiceResult, MSG_FC_INFINITY_TENDER_PUT_IN_TENDER * i_pPutInTenderInfo, ClientIndex_t i_PlayerClientIdx) { switch (i_pPutInTenderInfo->InfinityMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_pPutInTenderInfo->InfinityCreateUID); if(pInfinity) { return pInfinity->ChoiceTenderItem(o_pDiceResult, i_PlayerClientIdx, i_pPutInTenderInfo->ItemFieldIndex, i_pPutInTenderInfo->GiveUp); } } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_pPutInTenderInfo->InfinityCreateUID); if(pInfinity) { return pInfinity->ChoiceTenderItem(o_pDiceResult, i_PlayerClientIdx, i_pPutInTenderInfo->ItemFieldIndex, i_pPutInTenderInfo->GiveUp); } } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_pPutInTenderInfo->InfinityCreateUID); if(pInfinity) { return pInfinity->ChoiceTenderItem(o_pDiceResult, i_PlayerClientIdx, i_pPutInTenderInfo->ItemFieldIndex, i_pPutInTenderInfo->GiveUp); } } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } void CInfinityManager::ProcessingInfinityPenalty(char * i_szCharacterName, eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID) { if(NULL == i_szCharacterName) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return; } // 2009-09-09 ~ 2010-01-13 by dhjin, 인피니티 - 죽은 유저 이름 정보 전송 추가, // 인피니티 - 인피 사망시 패널티 추가 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->CalcLimitTimeByUserDeath(i_szCharacterName); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->CalcAliveForGameClearMonsterHPByUserDeath(i_szCharacterName); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->CalcLimitTimeByUserDeath(i_szCharacterName); // 패널티 적용 (제한 시간) (*itr)->CalcAliveForGameClearMonsterHPByUserDeath(i_szCharacterName); // 패널티 적용 (아군 모선 HP) return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return; } // default } return; } void CInfinityManager::SendInfinityTeamChatW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, BYTE * i_pDATA, int i_nSize) { // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 인피 채팅 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SendInfinityTeamChat(i_pDATA, i_nSize); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SendInfinityTeamChat(i_pDATA, i_nSize); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SendInfinityTeamChat(i_pDATA, i_nSize); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return; } // default } return; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - /// \author cmkwon /// \date 2010-04-05 ~ 2010-04-05 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// Err_t CInfinityManager::ImputeInfinityW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID) { // 인피 맵 생성 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_CreateUID); if(pInfinity) { return pInfinity->ImputeInfinity(); } } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_CreateUID); if(pInfinity) { return pInfinity->ImputeInfinity(); } } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_CreateUID); if(pInfinity) { return pInfinity->ImputeInfinity(); } } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) /****************************************************************************************************************** ** ** 인피니티 - 방에 난이도 레벨 변경. ** ** Create Info : 2010. 05. 26. by hsLee. ** ** Update Info : ** *******************************************************************************************************************/ Err_t CInfinityManager :: ChangeInfinityDifficultyLevel ( const INT i_cst_ChangeDifficultyLevel , eINFINITY_MODE i_eInfiMode , InfinityCreateUID_t i_CreateUID , CFieldIOCPSocket * i_pMasterUserFISoc ) { if( NULL == i_pMasterUserFISoc ) return ERR_INFINITY_NULL_VALUE; switch ( i_eInfiMode ) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta ( &m_mtvectInfiBossRush ); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for( ; itr != m_mtvectInfiBossRush.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->ChangeDifficultyLevel( i_pMasterUserFISoc , i_cst_ChangeDifficultyLevel ); } } mta.auto_unlock_cancel(); } break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta ( &m_mtvectInfiDefence ); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for( ; itr != m_mtvectInfiDefence.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->ChangeDifficultyLevel ( i_pMasterUserFISoc , i_cst_ChangeDifficultyLevel ); } } mta.auto_unlock_cancel(); } break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta ( &m_mtvectInfiMShipBattle ); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for( ; itr != m_mtvectInfiMShipBattle.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->ChangeDifficultyLevel ( i_pMasterUserFISoc , i_cst_ChangeDifficultyLevel ); } } mta.auto_unlock_cancel(); } break; } return ERR_INFINITY_DIFFICULTY_LEVEL_INVALID; } // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) // 2010. 07. 27 by hsLee 인피니티 2차 거점 방어 시네마 연출 스킵 처리. /****************************************************************************************************************************** ** ** 인피니티 엔딩 시네마 연출 스킵 활성화. ** ** Create Info : 2010. 07. 27. by hsLee. ** ** Update Info : 시네마 연출 스킵 처리에 정상 연출 종료에 대한 처리 추가. 'a_bNormalEnding' 2010. 08. 26. by hsLee. ** *******************************************************************************************************************************/ Err_t CInfinityManager :: InfinitySkipEndingCinema ( eINFINITY_MODE i_eInfiMode , InfinityCreateUID_t i_CreateUID , CFieldIOCPSocket * i_pPlayerFISoc , const bool a_bNormalEnding /*= false*/ ) { if( NULL == i_pPlayerFISoc ) return ERR_INFINITY_NULL_VALUE; switch ( i_eInfiMode ) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta ( &m_mtvectInfiBossRush ); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for( ; itr != m_mtvectInfiBossRush.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->SkipEndingCinema ( i_pPlayerFISoc , a_bNormalEnding ); } } mta.auto_unlock_cancel(); } break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta ( &m_mtvectInfiDefence ); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for( ; itr != m_mtvectInfiDefence.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->SkipEndingCinema ( i_pPlayerFISoc , a_bNormalEnding ); } } mta.auto_unlock_cancel(); } break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta ( &m_mtvectInfiMShipBattle ); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for( ; itr != m_mtvectInfiMShipBattle.end(); itr++ ) { if ( i_CreateUID == (*itr)->GetInfinityCreateUID() ) { return (*itr)->SkipEndingCinema ( i_pPlayerFISoc , a_bNormalEnding ); } } mta.auto_unlock_cancel(); } break; } return ERR_INFINITY_MISMATCH_CREATEUID; } void CInfinityManager::SetDisConnectUserInfo(INFINITY_DISCONNECTUSER_INFO * i_pDisConnectUserInfo) { if ( NULL == i_pDisConnectUserInfo ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return; } // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 mt_auto_lock mta(&m_mtInfinityDisConnectUserList); mtvectorInfinityDisConnectUser::iterator itr = m_mtInfinityDisConnectUserList.begin(); for(; itr != m_mtInfinityDisConnectUserList.end(); itr++) { if ( 0 == strnicmp(i_pDisConnectUserInfo->CharacterName, itr->CharacterName, SIZE_MAX_CHARACTER_NAME) ) { // 만약 기존에 팅긴 정보가 존재한다면!! 업뎃해주자~~!~!!! itr->InfinityCreateUID = i_pDisConnectUserInfo->InfinityCreateUID; itr->InfinityMode = i_pDisConnectUserInfo->InfinityMode; return; } } // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리, 인피 튕긴 유저일 경우 정보 저장. m_mtInfinityDisConnectUserList.push_back(*i_pDisConnectUserInfo); } Err_t CInfinityManager::DisConnectUserReStart(char * i_DisConnectUserName, INFINITY_PLAYING_INFO * o_pInfinityPlayingInfo) { if( NULL == i_DisConnectUserName || NULL == o_pInfinityPlayingInfo ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리, 인피 튕긴 유저 시작 처리 mt_auto_lock mta(&m_mtInfinityDisConnectUserList); mtvectorInfinityDisConnectUser::iterator itr = m_mtInfinityDisConnectUserList.begin(); for(; itr != m_mtInfinityDisConnectUserList.end(); itr++) { if ( 0 == strnicmp(i_DisConnectUserName, itr->CharacterName, SIZE_MAX_CHARACTER_NAME) ) { o_pInfinityPlayingInfo->InfinityCreateUID = itr->InfinityCreateUID; o_pInfinityPlayingInfo->ModeTypeNum = itr->InfinityMode; return this->CheckIsCreateInfinityUID(o_pInfinityPlayingInfo); } } return ERR_INFINITY_CANNOT_SUCH_TEAM; } Err_t CInfinityManager::CheckIsCreateInfinityUID(INFINITY_PLAYING_INFO * o_pInfinityPlayingInfo) { if ( NULL == o_pInfinityPlayingInfo ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return ERR_INFINITY_NULL_VALUE; } // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리 switch ( o_pInfinityPlayingInfo->ModeTypeNum ) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta ( &m_mtvectInfiBossRush ); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if ( o_pInfinityPlayingInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { o_pInfinityPlayingInfo->MapIdx = (*itr)->GetInfinityMapIndex(); return ERR_NO_ERROR; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta ( &m_mtvectInfiDefence ); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if( o_pInfinityPlayingInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { o_pInfinityPlayingInfo->MapIdx = (*itr)->GetInfinityMapIndex(); return ERR_NO_ERROR; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta ( &m_mtvectInfiMShipBattle ); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if( o_pInfinityPlayingInfo->InfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { o_pInfinityPlayingInfo->MapIdx = (*itr)->GetInfinityMapIndex(); return ERR_NO_ERROR; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : return ERR_INFINITY_CANNOT_SUCH_TEAM; } return ERR_INFINITY_CANNOT_SUCH_TEAM; } BOOL CInfinityManager::DeleteDisConnectUserInfo(char * i_DisConnectUserName) { if ( NULL == i_DisConnectUserName ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return FALSE; } // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리, 인피 튕긴 유저일 경우 정보 삭제. mt_auto_lock mta(&m_mtInfinityDisConnectUserList); mtvectorInfinityDisConnectUser::iterator itr = m_mtInfinityDisConnectUserList.begin(); for(; itr != m_mtInfinityDisConnectUserList.end(); itr++) { if( 0 == strnicmp(i_DisConnectUserName, itr->CharacterName, SIZE_MAX_CHARACTER_NAME) ) { m_mtInfinityDisConnectUserList.erase(itr); return TRUE; } } return FALSE; } void CInfinityManager::ReStartDisConnectUserW(InfinityCreateUID_t i_nInfinityCreateUID, eINFINITY_MODE i_eInfiMode, CFieldIOCPSocket * i_pUserFISoc) { if ( NULL == i_pUserFISoc ) { // 2009-09-09 ~ 2010-01 by dhjin, 인피니티 - 소스 체크 return; } // 2009-09-09 ~ 2010 by dhjin, 인피니티 - 팅긴 유저 재접속 처리 고고씽 switch ( i_eInfiMode ) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta( &m_mtvectInfiBossRush ); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if( i_nInfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { (*itr)->ReStartDisConnectUser(i_pUserFISoc); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta( &m_mtvectInfiDefence ); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if( i_nInfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { (*itr)->ReStartDisConnectUser( i_pUserFISoc ); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta( &m_mtvectInfiMShipBattle ); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if( i_nInfinityCreateUID == (*itr)->GetInfinityCreateUID() ) { (*itr)->ReStartDisConnectUser( i_pUserFISoc ); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; default : return; } return; } void CInfinityManager::CreateKeyMonster_AliveForGameClearW(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx, MonIdx_t i_CreateMonsterIdx) { mt_auto_lock mtD(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); for(; itrD != m_mtvectInfiDefence.end(); itrD++) { if(i_MapIndex == (*itrD)->GetInfinityMapIndex() && i_ChannelIdx == (*itrD)->GetInfinityChannelIndex()) { (*itrD)->CreateKeyMonster_AliveForGameClear(i_CreateMonsterIdx); return; } } mtD.auto_unlock_cancel(); // start 2011-06-05 by hskim, 인피니티 3차 - 키몬스터 삭제시 종료 처리 mt_auto_lock mtT(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itrT = m_mtvectInfiMShipBattle.begin(); for(; itrT != m_mtvectInfiMShipBattle.end(); itrT++) { if(i_MapIndex == (*itrT)->GetInfinityMapIndex() && i_ChannelIdx == (*itrT)->GetInfinityChannelIndex()) { (*itrT)->CreateKeyMonster_AliveForGameClear(i_CreateMonsterIdx); return; } } mtT.auto_unlock_cancel(); // end 2011-06-05 by hskim, 인피니티 3차 - 키몬스터 삭제시 종료 처리 } void CInfinityManager::DeleteKeyMonster_AliveForGameClearW(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx, MonIdx_t i_DeadMonsterIdx) { mt_auto_lock mtD(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); for(; itrD != m_mtvectInfiDefence.end(); itrD++) { if(i_MapIndex == (*itrD)->GetInfinityMapIndex() && i_ChannelIdx == (*itrD)->GetInfinityChannelIndex()) { (*itrD)->DeleteKeyMonster_AliveForGameClear(i_DeadMonsterIdx); return; } } mtD.auto_unlock_cancel(); // start 2011-06-05 by hskim, 인피니티 3차 - 키몬스터 삭제시 종료 처리 mt_auto_lock mtT(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itrT = m_mtvectInfiMShipBattle.begin(); for(; itrT != m_mtvectInfiMShipBattle.end(); itrT++) { if(i_MapIndex == (*itrT)->GetInfinityMapIndex() && i_ChannelIdx == (*itrT)->GetInfinityChannelIndex()) { (*itrT)->DeleteKeyMonster_AliveForGameClear(i_DeadMonsterIdx); return; } } mtT.auto_unlock_cancel(); // end 2011-06-05 by hskim, 인피니티 3차 - 키몬스터 삭제시 종료 처리 } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - /// \author cmkwon /// \date 2010-03-23 ~ 2010-03-23 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// Err_t CInfinityManager::SendFtoA_INFINITY_START_CHECK_W(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID) { switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->SendFtoA_INFINITY_START_CHECK(); } } mta.auto_unlock_cancel(); }// case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->SendFtoA_INFINITY_START_CHECK(); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->SendFtoA_INFINITY_START_CHECK(); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - /// \author cmkwon /// \date 2010-03-23 ~ 2010-03-23 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CFieldIOCPSocket *CInfinityManager::GetMasterPlayerW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID) { switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->GetMasterPlayer(); } } mta.auto_unlock_cancel(); }// case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->GetMasterPlayer(); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->GetMasterPlayer(); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return NULL; } // default } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - /// \author cmkwon /// \date 2010-03-23 ~ 2010-03-23 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// BOOL CInfinityManager::CheckInfinityStartCheckAckW(eINFINITY_STATE *o_pInfiRoomState, MSG_FtoA_INFINITY_START_CHECK_ACK *i_pStartCheckAck) { switch (i_pStartCheckAck->InfinityMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_pStartCheckAck->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->CheckInfinityStartCheckAck(o_pInfiRoomState, i_pStartCheckAck); } } mta.auto_unlock_cancel(); }// case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_pStartCheckAck->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->CheckInfinityStartCheckAck(o_pInfiRoomState, i_pStartCheckAck); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_pStartCheckAck->InfinityCreateUID == (*itr)->GetInfinityCreateUID()) { return (*itr)->CheckInfinityStartCheckAck(o_pInfiRoomState, i_pStartCheckAck); } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return FALSE; } // default } return FALSE; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-03-23 by cmkwon, 인피니티 입장 캐쉬 아이템 구현 - /// \author cmkwon /// \date 2010-03-23 ~ 2010-03-23 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// void CInfinityManager::SetAllPlayerStateW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, eINFINITY_STATE i_InfiState) { switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itr = m_mtvectInfiBossRush.begin(); for(; itr != m_mtvectInfiBossRush.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SetAllPlayerState(i_InfiState); return; } } mta.auto_unlock_cancel(); }// case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itr = m_mtvectInfiDefence.begin(); for(; itr != m_mtvectInfiDefence.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SetAllPlayerState(i_InfiState); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mta(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itr = m_mtvectInfiMShipBattle.begin(); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { if(i_CreateUID == (*itr)->GetInfinityCreateUID()) { (*itr)->SetAllPlayerState(i_InfiState); return; } } mta.auto_unlock_cancel(); } // case INFINITY_MODE_MSHIPBATTLE break; default : { return; } // default } return; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief /// \author cmkwon /// \date 2010-04-05 ~ 2010-04-05 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityBossrush *CInfinityManager::FindBossrushNoLock(InfinityCreateUID_t i_CreateUID) { mtvectInfiBossRush::iterator itr(m_mtvectInfiBossRush.begin()); for(; itr != m_mtvectInfiBossRush.end(); itr++) { CInfinityBossrush *pInfinity = *itr; if(i_CreateUID == pInfinity->GetInfinityCreateUID()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief /// \author cmkwon /// \date 2010-04-05 ~ 2010-04-05 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityDefence *CInfinityManager::FindDefenceNoLock(InfinityCreateUID_t i_CreateUID) { mtvectInfiDefence::iterator itr(m_mtvectInfiDefence.begin()); for(; itr != m_mtvectInfiDefence.end(); itr++) { CInfinityDefence *pInfinity = *itr; if(i_CreateUID == pInfinity->GetInfinityCreateUID()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 /// \author hskim /// \date 2011-02-18 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityMShipBattle *CInfinityManager::FindMShipBattleNoLock(InfinityCreateUID_t i_CreateUID) { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mtvectInfiMShipBattle::iterator itr(m_mtvectInfiMShipBattle.begin()); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { CInfinityMShipBattle *pInfinity = *itr; if(i_CreateUID == pInfinity->GetInfinityCreateUID()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - /// \author cmkwon /// \date 2010-04-09 ~ 2010-04-09 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityBossrush *CInfinityManager::FindBossrushNoLock(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx) { mtvectInfiBossRush::iterator itr(m_mtvectInfiBossRush.begin()); for(; itr != m_mtvectInfiBossRush.end(); itr++) { CInfinityBossrush *pInfinity = *itr; if(i_MapIndex == pInfinity->GetInfinityMapIndex() && i_ChannelIdx == pInfinity->GetInfinityChannelIndex()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - /// \author cmkwon /// \date 2010-04-09 ~ 2010-04-09 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityDefence *CInfinityManager::FindDefenceNoLock(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx) { mtvectInfiDefence::iterator itr(m_mtvectInfiDefence.begin()); for(; itr != m_mtvectInfiDefence.end(); itr++) { CInfinityDefence *pInfinity = *itr; if(i_MapIndex == pInfinity->GetInfinityMapIndex() && i_ChannelIdx == pInfinity->GetInfinityChannelIndex()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) -> 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 /// \author hskim /// \date 2011-02-18 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// CInfinityMShipBattle *CInfinityManager::FindMShipBattleNoLock(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx) { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mtvectInfiMShipBattle::iterator itr(m_mtvectInfiMShipBattle.begin()); for(; itr != m_mtvectInfiMShipBattle.end(); itr++) { CInfinityMShipBattle *pInfinity = *itr; if(i_MapIndex == pInfinity->GetInfinityMapIndex() && i_ChannelIdx == pInfinity->GetInfinityChannelIndex()) { return pInfinity; } } return NULL; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - /// \author cmkwon /// \date 2010-04-12 ~ 2010-04-12 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// Err_t CInfinityManager::PushTenderItemW(MapIndex_t i_MapIndex, ChannelIndex_t i_ChannelIdx, CTenderItemInfo *i_pTenderItemInfo) { /////////////////////////////////////////////////////////////////////////////// // 2010-04-09 by cmkwon, 인피2차 추가 수정(단계별 보상 추가) - { mt_auto_lock mtA(&m_mtvectInfiBossRush); CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { return pInfinity->PushTenderItem(i_pTenderItemInfo); } } { mt_auto_lock mtA(&m_mtvectInfiDefence); CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { return pInfinity->PushTenderItem(i_pTenderItemInfo); } } { // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 mt_auto_lock mtA(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_MapIndex, i_ChannelIdx); if(pInfinity) { return pInfinity->PushTenderItem(i_pTenderItemInfo); } } return ERR_INFINITY_CREATEUID; } /////////////////////////////////////////////////////////////////////////////// /// \fn /// \brief // 2010-04-06 by cmkwon, 인피2차 추가 수정 - /// \author cmkwon /// \date 2010-04-06 ~ 2010-04-06 /// \warning /// /// \param /// \return /////////////////////////////////////////////////////////////////////////////// Err_t CInfinityManager::CheckInfinityAllPlayerStateW(eINFINITY_MODE i_eInfiMode, InfinityCreateUID_t i_CreateUID, eINFINITY_STATE i_infiState) { // 인피 시작 switch (i_eInfiMode) { case INFINITY_MODE_BOSSRUSH: { mt_auto_lock mta(&m_mtvectInfiBossRush); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityBossrush *pInfinity = this->FindBossrushNoLock(i_CreateUID); if(pInfinity) { // g_pFieldGlobal->WriteSystemLogEX(TRUE, "[TEMP] [Infinity][%I64d] CInfinityManager::CheckInfinityAllPlayerStateW# 10000 !, InfiState(%d) Cnt(%d) \r\n" // , pInfinity->GetInfinityCreateUID(), pInfinity->GetInfinityState(), pInfinity->GetPlayerListSize()); // 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if( FALSE == pInfinity->CheckInfinityMinAdmission() ) { return ERR_INFINITY_MIN_ADMISSIONCNT; } // end 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if(FALSE == pInfinity->CheckInfinityAllPlayerState(i_infiState)) { return ERR_INFINITY_NOT_ALL_READY; } return ERR_NO_ERROR; } } // case INFINITY_MODE_BOSSRUSH break; case INFINITY_MODE_DEFENCE: { mt_auto_lock mta(&m_mtvectInfiDefence); /////////////////////////////////////////////////////////////////////////////// // 2010-04-05 by cmkwon, 인피 재입장 카드 관련 시스템 수정 - CInfinityDefence *pInfinity = this->FindDefenceNoLock(i_CreateUID); if(pInfinity) { // g_pFieldGlobal->WriteSystemLogEX(TRUE, "[TEMP] [Infinity][%I64d] CInfinityManager::CheckInfinityAllPlayerStateW# 20000 !, InfiState(%d) Cnt(%d) \r\n" // , pInfinity->GetInfinityCreateUID(), pInfinity->GetInfinityState(), pInfinity->GetPlayerListSize()); // 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if( FALSE == pInfinity->CheckInfinityMinAdmission() ) { return ERR_INFINITY_MIN_ADMISSIONCNT; } // end 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if(FALSE == pInfinity->CheckInfinityAllPlayerState(i_infiState)) { return ERR_INFINITY_NOT_ALL_READY; } return ERR_NO_ERROR; } } // case INFINITY_MODE_DEFENCE break; case INFINITY_MODE_MSHIPBATTLE: // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mta(&m_mtvectInfiMShipBattle); CInfinityMShipBattle *pInfinity = this->FindMShipBattleNoLock(i_CreateUID); if(pInfinity) { // 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if( FALSE == pInfinity->CheckInfinityMinAdmission() ) { return ERR_INFINITY_MIN_ADMISSIONCNT; } // end 2012-07-17 by hskim, 인피니티 인원수 부족할대 START 할경우 예외 처리 if(FALSE == pInfinity->CheckInfinityAllPlayerState(i_infiState)) { return ERR_INFINITY_NOT_ALL_READY; } return ERR_NO_ERROR; } } // case INFINITY_MODE_MSHIPBATTLE break; default : { return ERR_INFINITY_MODE; } // default } return ERR_INFINITY_CREATEUID; } // 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) /************************************************************************************************ ** ** 인피니티 난이도 조절 - 유저에게 보여줄 난이도 정보 가져오기 ** ** Create Info : 2010-05-13 by shcho ** ** Update Infi : 인자 포인터로 변경, 결과 값 리턴하도록 수정. 2010. 05. 24. by hsLee. ** *************************************************************************************************/ BOOL CInfinityManager::Get_Difficulty_BonusInfo_ListData(vectorInfinity_DifficultyInfo_Bonus *p_vecInfinity_DifficulytList) { if ( NULL == p_vecInfinity_DifficulytList ) return FALSE; p_vecInfinity_DifficulytList->clear(); p_vecInfinity_DifficulytList->assign( m_vecInfinityDifficultyBonusInfo.begin() , m_vecInfinityDifficultyBonusInfo.end() ); return TRUE; } /********************************************************************************************** ** ** 인피니티 난이도 조절 - 보너스 정보를 저장하기 ** ** Create Info : 2010-05-13 by shcho ** ** Update Info : 인자명 변경, 결과 값 리턴하도록 수정. 2010. 05. 24. by hsLee. ** ***********************************************************************************************/ BOOL CInfinityManager::Set_Difficulty_BonusInfo_ListData(vectorInfinity_DifficultyInfo_Bonus *p_vecListInfo) { if ( NULL == p_vecListInfo ) return FALSE; m_vecInfinityDifficultyBonusInfo.clear(); m_vecInfinityDifficultyBonusInfo.assign( p_vecListInfo->begin(), p_vecListInfo->end() ); return TRUE; } /********************************************************************************************** ** ** 인피니티 난이도 조절 - 보너스 정보를 찾는다. ** ** Create Info : 2010-05-13 by shcho ** ** Update Info : 인자명 변경, 내부 처리 구현. 2010. 05. 24. by hsLee. ** ***********************************************************************************************/ const INFINITY_DIFFICULTY_BONUS_INFO *CInfinityManager :: Get_Difficulty_BonusInfo ( const int a_iStep ) { vectorInfinity_DifficultyInfo_Bonus::iterator it = m_vecInfinityDifficultyBonusInfo.begin(); while ( it != m_vecInfinityDifficultyBonusInfo.end() ) { if ( it->iIncreaseStep == a_iStep ) return &*it; ++it; } return NULL; } /********************************************************************************************** ** ** 인피니티 난이도 조절 - 몬스터 밸런스 정보를 찾는다. ** ** Create Info : 2010-05-13 by shcho ** ** Update Info : 인자명 변경, 내부 처리 구현. 2010. 05. 24. by hsLee. ** ***********************************************************************************************/ const INFINITY_DIFFICULTY_MONSTER_SETTING_INFO *CInfinityManager::Get_Difficulty_MonsterInfo(int iStep) { vectorInfinity_DifficultyInfo_Monster::iterator iter = m_vecInfinityDifficultyMonsterInfo.begin(); // 스텝에 따른 정보를 찾는다. while ( iter != m_vecInfinityDifficultyMonsterInfo.end() ) { if ( iter->iIncreaseStep == iStep ) return &*iter; ++iter; } return NULL; } /********************************************************************************************** ** ** 인피니티 난이도 조절 - 몬스터 밸런스 정보를 저장한다. ** ** Create Info : 2010-05-13 by shcho ** ** Update Info : 인자명 변경. 2010. 05. 24. by hsLee. ** ***********************************************************************************************/ BOOL CInfinityManager::Set_Difficulty_MonsterInfo_ListData(vectorInfinity_DifficultyInfo_Monster* p_vecListInfo) { if ( NULL == p_vecListInfo ) return FALSE; m_vecInfinityDifficultyMonsterInfo.clear(); m_vecInfinityDifficultyMonsterInfo.assign( p_vecListInfo->begin() , p_vecListInfo->end() ); return TRUE; } // End 2010. 05. 19 by hsLee 인피니티 필드 2차 난이도 조절. (신호처리 + 몬스터 처리(서버) ) // 2010. 06. 04 by hsLee 인티피니 필드 2차 난이도 조절. (GM 명령어 추가. /nextscene(다음 시네마 씬 호출.) ) - GM 다음 씨네마 바로 호출. /************************************************************************************************************************************************** ** ** 인피니티 : GM의 다음 시네마 바로 호출 처리. ** ** Create Info : 2010. 06. 04 by hsLee. ** ** Update Info : 인자명 변경. 2010. 05. 24. by hsLee. ** ** 한번 호출로 갱신 가능한 시네마 개수 지정 가능 처리. ( nUpdateSceneCount ) 2010. 08. 20. by hsLee. ** ***************************************************************************************************************************************************/ void CInfinityManager :: UpdateNextSceneProc ( eINFINITY_MODE i_eInfiMode , InfinityCreateUID_t i_CreateUID , CFieldIOCPSocket * i_pMasterFISoc , int nUpdateSceneCount /*= 1*/ ) { if (!i_pMasterFISoc) return; nUpdateSceneCount = max ( nUpdateSceneCount , 1 ); switch ( i_eInfiMode ) { case INFINITY_MODE_BOSSRUSH : { mt_auto_lock mtR(&m_mtvectInfiBossRush); mtvectInfiBossRush::iterator itrR = m_mtvectInfiBossRush.begin(); while ( itrR != m_mtvectInfiBossRush.end() ) { if ( (*itrR)->GetInfinityCreateUID() == i_CreateUID ) { (*itrR)->ProcessingCinema( i_pMasterFISoc , nUpdateSceneCount ); break; } itrR++; } mtR.auto_unlock_cancel(); } break; case INFINITY_MODE_DEFENCE : { mt_auto_lock mtD(&m_mtvectInfiDefence); mtvectInfiDefence::iterator itrD = m_mtvectInfiDefence.begin(); while ( itrD != m_mtvectInfiDefence.end() ) { if ( (*itrD)->GetInfinityCreateUID() == i_CreateUID ) { (*itrD)->ProcessingCinema ( i_pMasterFISoc , nUpdateSceneCount ); break; } itrD++; } mtD.auto_unlock_cancel(); } break; case INFINITY_MODE_MSHIPBATTLE : // 2011-02-18 by hskim, 인피니티 3차 - 방 생성 작업 { mt_auto_lock mtD(&m_mtvectInfiMShipBattle); mtvectInfiMShipBattle::iterator itrD = m_mtvectInfiMShipBattle.begin(); while ( itrD != m_mtvectInfiMShipBattle.end() ) { if ( (*itrD)->GetInfinityCreateUID() == i_CreateUID ) { (*itrD)->ProcessingCinema ( i_pMasterFISoc , nUpdateSceneCount ); break; } itrD++; } mtD.auto_unlock_cancel(); } break; } } // End 2010. 06. 04 by hsLee 인티피니 필드 2차 난이도 조절. (GM 명령어 추가. /nextscene(다음 시네마 씬 호출.) ) - GM 다음 씨네마 바로 호출.
[ "guss@nemerian.fr" ]
guss@nemerian.fr
377467d3b3d07e6ea04ed0ba54ccb7ced31c7597
c9e21a642e00c306f6b47c3393327a1796fc76ca
/huskyTech1/ht_types.h
14346d8e5c495f02a6e527bf10daf4c0548d989a
[ "MIT" ]
permissive
floppydiskette/huskytech1
95cbb6e176859d8acb18dfa288cc0c5964ac3639
42458984cfca68e88f1cbfd2d63e5d14a7f51726
refs/heads/main
2023-07-21T14:15:18.444866
2021-08-25T05:25:53
2021-08-25T05:25:53
398,931,265
0
0
null
null
null
null
UTF-8
C++
false
false
83
h
#pragma once #include <string> #include "Sprite.h" struct Point { float x, y; };
[ "77258311+floppydiskette@users.noreply.github.com" ]
77258311+floppydiskette@users.noreply.github.com
76c2f5c166e9f124b914389fbc28537bbf4e3a73
5042b6aa6b3d12239e3c9f7ce7f93088f0591cd8
/lab8/InsertASM/InsertASM/Source.cpp
9495ca5e689e37a90fab0d86a778c411531a1d51
[]
no_license
Neroben/Assembler
02674fc16d285c0ba25bda34d53356941d4933bc
cc4eb0b4c463df6805f53bbd1df4f7bd7e4a290d
refs/heads/master
2021-03-29T09:20:14.124375
2020-03-17T10:34:42
2020-03-17T10:34:42
247,941,306
1
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include <iostream> int* sort(int* a, int start, int end, int* res); void swap(int* a, int index); int main() { int a[10] = { 10,9,8,7,6,5,4,3,2,1 }; int res[10]; sort(a, 0, 9, res); for (int i = 0; i < 10; i++) std::cout << res[i] << " "; } int* sort(int *a, int start, int end, int *res) { int index = 0; for (int i = start; i <= end; i++) { res[index++] = a[i]; } bool flag; for (int i = 1; i < (end - start + 1); i++) { flag = true; index = i; while (index > 0 && flag) { if (res[index] < res[index - 1]) swap(res, index--); else flag = !flag; } } return res; } void swap(int *a, int index) { int path = a[index - 1]; a[index - 1] = a[index]; a[index] = path; }
[ "s.dontsow39@gmail.com" ]
s.dontsow39@gmail.com
46897dd0b432b2e5c036e366cc49f92116196cdd
73023c191f3afc1f13b39dffea22b7f65a664f7d
/MatrixEngine/Classes/MCocoStudio/Native/ScriptBind_UICheckBox.cpp
c924a079ce5c9d70a74c60ba05d37e27ad180d71
[]
no_license
ugsgame/Matrix
0a2c2abb3be9966c3cf7a4164799ed107c8f2920
1311b77bd9a917ec770e428efb9530ee6038617a
refs/heads/master
2020-09-05T15:45:45.973221
2019-11-07T07:20:38
2019-11-07T07:20:38
220,145,853
0
0
null
null
null
null
GB18030
C++
false
false
3,383
cpp
//#include "stdneb.h" #include "cocos2d.h" #include "cocos-ext.h" #include "ScriptBind_UICheckBox.h" USING_NS_CC; using namespace cocos2d::ui; class CheckBoxEvent:public CCObject { public: CheckBoxEvent(){} ~CheckBoxEvent(){} static CheckBoxEvent* Create(IMonoObject* obj) { CheckBoxEvent* event = new CheckBoxEvent(); event->setMonoObject(obj); //c#层没有计数,native层也不计了 event->ObjectCount--; return event; } //TODO 回调c#函数中第一个参数 应该传入c#的对像,而不是指针 void SelectedStateEvent(CCObject *pSender, CheckBoxEventType type) { CCAssert(p_MonoObject,""); //TODO //pScript->CallMethod("TouchEvent",IMonoObject object,(int)type); p_MonoObject->CallMethod("SelectedStateEvent",(int)type); } }; ScriptBind_UICheckBox::ScriptBind_UICheckBox() { REGISTER_METHOD(Create); REGISTER_METHOD(LoadTextures); REGISTER_METHOD(LoadTextureBackGround); REGISTER_METHOD(LoadTextureBackGroundSelected); REGISTER_METHOD(LoadTextureFrontCross); REGISTER_METHOD(LoadTextureBackGroundDisabled); REGISTER_METHOD(LoadTextureFrontCrossDisabled); REGISTER_METHOD(SetSelectedState); REGISTER_METHOD(GetSelectedState); REGISTER_METHOD(AddEventListenerCheckBox); } ScriptBind_UICheckBox::~ScriptBind_UICheckBox() { } CheckBox* ScriptBind_UICheckBox::Create() { return CheckBox::create(); } void ScriptBind_UICheckBox::LoadTextures(CheckBox * checkbox,mono::string backGround,mono::string backGroundSelected,\ mono::string cross,mono::string backGroundDisabled,mono::string frontCrossDisabled,TextureResType textType) { checkbox->loadTextures(ToMatrixString(backGround).c_str(),ToMatrixString(backGroundSelected).c_str(),ToMatrixString(cross).c_str(),ToMatrixString(backGroundDisabled).c_str(),ToMatrixString(frontCrossDisabled).c_str(), textType); } void ScriptBind_UICheckBox::LoadTextureBackGround(CheckBox * checkbox,mono::string backGround,TextureResType textType) { checkbox->loadTextureBackGround(ToMatrixString(backGround).c_str(), textType); } void ScriptBind_UICheckBox::LoadTextureBackGroundSelected(CheckBox * checkbox,mono::string backGroundSelected,TextureResType textType) { checkbox->loadTextureBackGroundSelected(ToMatrixString(backGroundSelected).c_str(), textType); } void ScriptBind_UICheckBox::LoadTextureFrontCross(CheckBox * checkbox,mono::string cross,TextureResType textType) { checkbox->loadTextureFrontCross(ToMatrixString(cross).c_str(), textType); } void ScriptBind_UICheckBox::LoadTextureBackGroundDisabled(CheckBox * checkbox,mono::string backGroundDisabled,TextureResType textType) { checkbox->loadTextureBackGroundDisabled(ToMatrixString(backGroundDisabled).c_str(), textType); } void ScriptBind_UICheckBox::LoadTextureFrontCrossDisabled(CheckBox * checkbox,mono::string frontCrossDisabled,TextureResType textType) { checkbox->loadTextureFrontCrossDisabled(ToMatrixString(frontCrossDisabled).c_str(), textType); } void ScriptBind_UICheckBox::SetSelectedState(CheckBox * checkbox,bool state) { checkbox->setSelectedState(state); } bool ScriptBind_UICheckBox::GetSelectedState(CheckBox * checkbox) { return checkbox->getSelectedState(); } void ScriptBind_UICheckBox::AddEventListenerCheckBox(CheckBox * checkbox,mono::object obj) { checkbox->addEventListenerCheckBox(CheckBoxEvent::Create(*obj),checkboxselectedeventselector(CheckBoxEvent::SelectedStateEvent)); }
[ "670563380@qq.com" ]
670563380@qq.com
eb1d810aacb32bbe84ca28d5290b665d5871f3d3
49e022421f4474fd505ec1d01beb8dd470a1f274
/test.cpp
96b4151baab118aab26bca7a1e484edb9fdf4c7e
[]
no_license
azure1995/codeforces
569741eb7c4a167e81d5155fbe1421b62974173f
358ae4b1db420dac161b6c2d998bc4b00375f03c
refs/heads/master
2020-05-06T15:36:11.582099
2019-05-09T20:35:59
2019-05-09T20:35:59
180,198,784
0
1
null
null
null
null
UTF-8
C++
false
false
1,477
cpp
#include <bits/stdc++.h> using namespace std; // #define what_is(x) cout << #x << " is " << x << "\n"; // #define rep(i, begin, end) \ // for (__typeof(end) i = (begin) - ((begin) > (end)); \ // i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) // template <typename T> // T _max(T a) { // return a; // } // #define eb emplace_back // #define mt make_tuple // template <typename T, typename... Args> // T _max(T a, Args... args) { // return max(a, _max(args...)); // } // int sum() { return 0; } // template <typename T, typename... Args> // T sum(T a, Args... args) { // return a + sum(args...); // } // long long operator"" _km(unsigned long long literal) { return literal * 1000; // } int main(int argc, char const *argv[]) { // vector<int> v{7, 2, 3, 5}; // vector<int> n; // for (int a : v) { // n.eb(a + 1); // } // v = move(n); // rep(it, v.begin(), v.end()) cout << *it << " "; // rep(it, n.begin(), n.end()) cout << *it << " "; // cout << R"(Hello\tWorld\n)" // << "\n"; // regex email_pattern(R"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"); // string valid_email("swift@codeforces.com"); // if (regex_match(valid_email, email_pattern)) // cout << valid_email << " is valid\n"; // else // cout << valid_email << " is invalid\n"; // cout << 120_km << "meters \n"; // tuple<int, int> t{1, 2}; queue<int> que({1, 2, 3}); cout << que.back() << "\n"[1]; }
[ "gzg19950308@gmail.com" ]
gzg19950308@gmail.com
8fe4653dbede6b394b141a989fb41e36d387455c
c6cff4b194fe2ab1a0d5a3449c6ff361927d198f
/Prog_lab4_z2.cpp
e99f6c30bf794b89c9a067b6591cc2abc22277be
[]
no_license
Sidenko-M-E/MyCRepo
9850d80527447193140caaa24c28f69986f1cb86
b1aade165c95ae5f707f565903b0a8ea7f3e4df3
refs/heads/master
2023-07-18T12:52:37.529521
2021-09-06T10:11:40
2021-09-06T10:11:40
403,558,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,119
cpp
#define _CRT_SECURE_NO_WARNINGS #define PI 3.14159265 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <locale.h> #include <conio.h> void prt(double x, double y, double e) { printf("Значение переменной - %lf\n", x); printf("Значение функции - %lf\n", y); printf("Значение точности - %lf\n", e); } double fact(double n) { double rez = 1; double i = 1; while (i <= n) { rez = rez * i; i++; } return(rez); } double erf(double x, double e) { double y = 0; double an = 1; double n = -1; while (fabs(an) > e) { n++; an = (2 * pow(x, 2 * n + 1) * pow(-1, n)) / (sqrt(PI) * fact(n) * (2 * n + 1)); y += an; } return (y); } double ln(double x, double e) { double y = 0; double an = 1; double n = 0; while (fabs(an) > e) { n++; an = pow(x - 1, n) * pow(-1, n + 1) / n; y += an; } return (y); } double calcul(double x, double e, double (*fp)(double x, double e)) { double rez; rez = (*fp)(x, e); return(rez); } int main() { setlocale(LC_ALL, "RUS"); double x, e, y; int n; do { system("cls"); do { printf("Введите значения X, E, N - номер вызываемой функции.\n"); printf("Учтите, что ряд для определения логарифма сходится только при 0<x<=2. \n"); scanf("%lf %lf %d", &x, &e, &n); while (getchar() != '\n'); if ((n == 2 && ((x <= 0) || (x > 2))) || ((n != 1) && (n != 2)) || (e <= 0)) printf("\nНеправильный ввод.\n"); } while ((n == 2 && ((x <= 0) || (x > 2))) || ((n != 1) && (n != 2)) || (e <= 0)); if (n == 1) { printf("\nВычисляется значение функции erf(x)\n"); y = calcul(x, e, erf); } if (n == 2) { printf("\nВычисляется значение функции ln(x)\n"); y = calcul(x, e, ln); } prt(x, y, e); printf("\nВыполнение программы закончено. Повторить выполнение?\n"); printf("<да> - любая клавиша / <esc> - нет\n"); } while (_getch() != 27); }
[ "matvey.sidenko@mail.ru" ]
matvey.sidenko@mail.ru
754b247a94d09344d83d21ca824268e814ad7d56
225e224f2d06bf34d30bb221d3a513527a6d123f
/framework/protocol_buffers/varint.inl
f6eb76667bbd3af7373429fb2a652a472da74222
[ "MIT" ]
permissive
molw5/framework
68763ceb6ba52c43262d7084530953d436ef98b9
4ebb4ff15cc656f60bd61626a0893c02e5f3bbcd
refs/heads/master
2021-01-10T21:33:59.970104
2013-04-10T23:15:31
2013-04-11T00:44:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,183
inl
// Copyright (C) 2013 iwg molw5 // For conditions of distribution and use, see copyright notice in COPYING /** * \file * \brief Varint mutator. * * \copyright * Copyright &copy; 2013 iwg molw5<br> * For conditions of distribution and use, see copyright notice in COPYING */ namespace framework { namespace protocol_buffers { namespace detail { template <std::size_t Size, std::size_t Index = 0> struct varint_unroll { FRAMEWORK_ALWAYS_INLINE static bool read (char const* begin, char const* end, char const*& it, uint64_t& out) { enum{ shift = 7*Index }; if (FRAMEWORK_EXPECT_FALSE(begin == end)) return false; auto const block = static_cast <uint8_t> (*(begin++)); if (FRAMEWORK_EXPECT_TRUE(!(block & 0x80))) { out |= uint64_t(block) << shift; it = begin; return true; } out |= uint64_t(block & 0x7F) << shift; return varint_unroll <Size, Index+1>::read(begin, end, it, out); } template <typename Input> FRAMEWORK_ALWAYS_INLINE static bool read (Input& in, uint64_t& out) { enum{ shift = 7*Index }; uint8_t block {}; if (FRAMEWORK_EXPECT_FALSE(!serializable::stream_read(in, &block, 1))) return false; if (FRAMEWORK_EXPECT_TRUE(!(block & 0x80))) { out |= uint64_t(block) << shift; return true; } out |= uint64_t(block & 0x7F) << shift; return varint_unroll <Size, Index+1>::read(in, out); } FRAMEWORK_ALWAYS_INLINE static bool write (uint64_t in, char* begin, char* end, char*& it) { assert(begin != end); auto const block = static_cast <uint8_t> (in); if (FRAMEWORK_EXPECT_TRUE(!(in >>= 7))) { *(begin++) = static_cast <char> (block); it = begin; return true; } *(begin++) = static_cast <char> (block | 0x80); return varint_unroll <Size, Index+1>::write(in, begin, end, it); } template <typename Output> FRAMEWORK_ALWAYS_INLINE static bool write (uint64_t in, Output& out) { auto block = static_cast <uint8_t> (in); if (FRAMEWORK_EXPECT_TRUE(!(in >>= 7))) { if (FRAMEWORK_EXPECT_FALSE(!serializable::stream_write(out, &block, 1))) return false; return true; } block |= 0x80; if (FRAMEWORK_EXPECT_FALSE(!serializable::stream_write(out, &block, 1))) return false; return varint_unroll <Size, Index+1>::write(in, out); } }; template <std::size_t Size> struct varint_unroll <Size, Size> { FRAMEWORK_ALWAYS_INLINE static bool read (char const*, char const*, char const*&, uint64_t&) { return false; } template <typename Input> FRAMEWORK_ALWAYS_INLINE static bool read (Input&, uint64_t&) { return false; } FRAMEWORK_ALWAYS_INLINE static bool write (uint64_t, char*, char*, char*&) { return false; } template <typename Output> FRAMEWORK_ALWAYS_INLINE static bool write (uint64_t, Output&) { return false; } }; template <std::size_t Size, typename Indices = make_indices <Size - 1>> struct fixed_length_impl; template <std::size_t Size, typename... Indices> struct fixed_length_impl <Size, pack_container <Indices...>> { template <typename Output> FRAMEWORK_ALWAYS_INLINE static bool run (std::size_t value, Output&& out) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshift-count-overflow" #endif uint8_t const raw[Size] = { static_cast <uint8_t> ((value >> (Indices::value*7)) | 0x80)..., static_cast <uint8_t> ((value >> ((1+Size)*7)) & 0x7F)}; #ifdef __clang__ #pragma clang diagnostic pop #endif return serializable::stream_write <Size> (out, reinterpret_cast <char const*> (&raw[0])); } FRAMEWORK_ALWAYS_INLINE static bool run (std::size_t value, char* begin, char* end, char*& it) { (void)end; // suppress warnings #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshift-count-overflow" #endif uint8_t const raw[Size] = { static_cast <uint8_t> ((value >> (Indices::value*7)) | 0x80)..., static_cast <uint8_t> ((value >> ((1+Size)*7)) & 0x7F)}; #ifdef __clang__ #pragma clang diagnostic pop #endif assert(static_cast <std::size_t> (end - begin) >= Size); memcpy(begin, &raw[0], Size); it = begin + Size; return true; } }; } template <std::size_t Size, typename Output> bool fixed_length (std::size_t value, Output&& out) { static_assert(Size > 0 && Size <= 10, "Invalid fixed varint size"); enum{ max_size = (2ull << (7*Size)) - 1 }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" #endif if (FRAMEWORK_EXPECT_FALSE(value > max_size)) return false; #ifdef __clang__ #pragma clang diagnostic pop #endif return detail::fixed_length_impl <Size>::run(value, std::forward <Output> (out)); } template <std::size_t Size> FRAMEWORK_ALWAYS_INLINE bool fixed_length (std::size_t value, char* begin, char* end, char*& it) { static_assert(Size > 0 && Size <= 10, "Invalid fixed varint size"); enum{ max_size = (2ull << (7*Size)) - 1 }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" #endif if (FRAMEWORK_EXPECT_FALSE(value > max_size)) return false; #ifdef __clang__ #pragma clang diagnostic pop #endif return detail::fixed_length_impl <Size>::run(value, begin, end, it); } //-------------------------- // Stream dispatch functions //-------------------------- template < typename T, typename Input, typename Output> static bool read_dispatch ( varint <T>*, Input&& in, Output&& out) { using serializable::type_extractor; enum{ max_size = std::is_signed <T>::value ? 10 : (8*sizeof(type_extractor <T>) + 6) / 7 }; uint64_t x {}; if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::read(in, x))) return false; out = static_cast <type_extractor <T>> (x); return true; } template < typename T, typename Input, typename Output> static typename std::enable_if < !std::is_same <Output, max_size_frame>::value, bool >::type write_dispatch ( varint <T>*, Input&& in, Output&& out) { using serializable::type_extractor; enum{ max_size = std::is_signed <T>::value ? 10 : (8*sizeof(type_extractor <T>) + 6) / 7 }; auto const x = static_cast <uint64_t> (in); return detail::varint_unroll <max_size>::write(x, out); } template < typename T, typename Input> FRAMEWORK_ALWAYS_INLINE bool write_dispatch ( varint <T>*, Input&&, max_size_frame& out) { out.skip(10); return true; } template < typename T, typename Input, typename Output> static bool read_dispatch ( zig_zag <T>*, Input&& in, Output&& out) { using serializable::type_extractor; enum{ max_size = (8*sizeof(type_extractor <T>) + 1 + 6) / 7 }; uint64_t x{}; if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::read(in, x))) return false; out = x & 1 ? -static_cast <type_extractor <T>> (x >> 1) : static_cast <type_extractor <T>> (x >> 1); return true; } template < typename T, typename Input, typename Output> static bool write_dispatch ( zig_zag <T>*, Input&& in, Output&& out) { using serializable::type_extractor; enum{ max_size = (8*sizeof(type_extractor <T>) + 1 + 6) / 7 }; auto const x = in >= 0 ? (static_cast <uint64_t> (in) << 1) : ((static_cast <uint64_t> (-in) << 1) | 1); if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::write(x, out))) return false; return true; } //-------------------------- // Raw dispatch functions //-------------------------- template < typename T, typename Output> FRAMEWORK_ALWAYS_INLINE static bool read_dispatch ( varint <T>*, char const* begin, char const* end, char const*& it, Output&& out) { using serializable::type_extractor; enum{ max_size = std::is_signed <T>::value ? 10 : (8*sizeof(type_extractor <T>) + 6) / 7 }; uint64_t x {}; if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::read(begin, end, it, x))) return false; out = static_cast <type_extractor <T>> (x); return true; } template < typename T, typename Input> FRAMEWORK_ALWAYS_INLINE static bool write_dispatch ( varint <T>*, Input&& in, char* begin, char* end, char*& it) { using serializable::type_extractor; enum{ max_size = std::is_signed <T>::value ? 10 : (8*sizeof(type_extractor <T>) + 6) / 7 }; auto const x = static_cast <uint64_t> (in); if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::write(x, begin, end, begin))) return false; it = begin; return true; } template < typename T, typename Output> FRAMEWORK_ALWAYS_INLINE static bool read_dispatch ( zig_zag <T>*, char const* begin, char const* end, char const*& it, Output&& out) { using serializable::type_extractor; enum{ max_size = (8*sizeof(type_extractor <T>) + 1 + 6) / 7 }; uint64_t x{}; if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::read(begin, end, it, x))) return false; out = x & 1 ? -static_cast <type_extractor <T>> (x >> 1) : static_cast <type_extractor <T>> (x >> 1); return true; } template < typename T, typename Input> FRAMEWORK_ALWAYS_INLINE static bool write_dispatch ( zig_zag <T>*, Input&& in, char* begin, char* end, char*& it) { using serializable::type_extractor; enum{ max_size = (8*sizeof(type_extractor <T>) + 1 + 6) / 7 }; auto const x = in >= 0 ? (static_cast <uint64_t> (in) << 1) : ((static_cast <uint64_t> (-in) << 1) | 1); if (FRAMEWORK_EXPECT_FALSE(!detail::varint_unroll <max_size>::write(x, begin, end, it))) return false; return true; } } }
[ "iwg.molw5@gmail.com" ]
iwg.molw5@gmail.com
2f5b5059e1b775cfd0b615c03052af394f4d6a9d
7f92683ba382a8242597277afb72aa97c40818b3
/Temp/il2cppOutput/il2cppOutput/AssemblyU2DCSharp_BezierCurve4194209710.h
ae39cf444899b384829a0a5afb1234a6540f44b8
[]
no_license
pramit46/game-off-2016
5833734908123bbfcc1ee41c16a7f33fdc9640cc
e9a98c27e6848d3f2109a952a921643a6a9300c8
refs/heads/master
2021-01-11T08:38:36.810368
2016-11-28T19:42:15
2016-11-28T19:42:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,399
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // BezierPoint[] struct BezierPointU5BU5D_t1242557692; #include "UnityEngine_UnityEngine_MonoBehaviour1158329972.h" #include "UnityEngine_UnityEngine_Color2020392075.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // BezierCurve struct BezierCurve_t4194209710 : public MonoBehaviour_t1158329972 { public: // System.Int32 BezierCurve::resolution int32_t ___resolution_2; // System.Boolean BezierCurve::<dirty>k__BackingField bool ___U3CdirtyU3Ek__BackingField_3; // UnityEngine.Color BezierCurve::drawColor Color_t2020392075 ___drawColor_4; // System.Boolean BezierCurve::_close bool ____close_5; // System.Single BezierCurve::_length float ____length_6; // BezierPoint[] BezierCurve::points BezierPointU5BU5D_t1242557692* ___points_7; public: inline static int32_t get_offset_of_resolution_2() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ___resolution_2)); } inline int32_t get_resolution_2() const { return ___resolution_2; } inline int32_t* get_address_of_resolution_2() { return &___resolution_2; } inline void set_resolution_2(int32_t value) { ___resolution_2 = value; } inline static int32_t get_offset_of_U3CdirtyU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ___U3CdirtyU3Ek__BackingField_3)); } inline bool get_U3CdirtyU3Ek__BackingField_3() const { return ___U3CdirtyU3Ek__BackingField_3; } inline bool* get_address_of_U3CdirtyU3Ek__BackingField_3() { return &___U3CdirtyU3Ek__BackingField_3; } inline void set_U3CdirtyU3Ek__BackingField_3(bool value) { ___U3CdirtyU3Ek__BackingField_3 = value; } inline static int32_t get_offset_of_drawColor_4() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ___drawColor_4)); } inline Color_t2020392075 get_drawColor_4() const { return ___drawColor_4; } inline Color_t2020392075 * get_address_of_drawColor_4() { return &___drawColor_4; } inline void set_drawColor_4(Color_t2020392075 value) { ___drawColor_4 = value; } inline static int32_t get_offset_of__close_5() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ____close_5)); } inline bool get__close_5() const { return ____close_5; } inline bool* get_address_of__close_5() { return &____close_5; } inline void set__close_5(bool value) { ____close_5 = value; } inline static int32_t get_offset_of__length_6() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ____length_6)); } inline float get__length_6() const { return ____length_6; } inline float* get_address_of__length_6() { return &____length_6; } inline void set__length_6(float value) { ____length_6 = value; } inline static int32_t get_offset_of_points_7() { return static_cast<int32_t>(offsetof(BezierCurve_t4194209710, ___points_7)); } inline BezierPointU5BU5D_t1242557692* get_points_7() const { return ___points_7; } inline BezierPointU5BU5D_t1242557692** get_address_of_points_7() { return &___points_7; } inline void set_points_7(BezierPointU5BU5D_t1242557692* value) { ___points_7 = value; Il2CppCodeGenWriteBarrier(&___points_7, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "adamstox@gmail.com" ]
adamstox@gmail.com
be4f2ca6f5608cb3abb386ca697b539977d325a2
d93159d0784fc489a5066d3ee592e6c9563b228b
/HLTrigger/HLTanalyzers/test/rates/OHltTree.cpp
04f1032f3693089901e7ae36caa11a61757d3576
[]
permissive
simonecid/cmssw
86396e31d41a003a179690f8c322e82e250e33b2
2559fdc9545b2c7e337f5113b231025106dd22ab
refs/heads/CAallInOne_81X
2021-08-15T23:25:02.901905
2016-09-13T08:10:20
2016-09-13T08:53:42
176,462,898
0
1
Apache-2.0
2019-03-19T08:30:28
2019-03-19T08:30:24
null
UTF-8
C++
false
false
28,089
cpp
#define OHltTree_cxx #include "OHltTree.h" #include <TH2.h> #include <TStyle.h> #include <TCanvas.h> #include <TLeaf.h> #include <TFormula.h> #include <TMath.h> #include <iostream> #include <iomanip> #include <string> using namespace std; void OHltTree::Loop(vector<int> * iCount, vector<int> * sPureCount, vector<int> * pureCount ,vector< vector<int> > * overlapCount ,vector<TString> trignames ,map<TString,int> map_pathHLTPrescl ,int NEntries ,bool doMuonCut,bool doElecCut ,double muonPt, double muonDr) { // To read only selected branches, Insert statements like: // METHOD1: // fChain->SetBranchStatus("*",0); // disable all branches // fChain->SetBranchStatus("branchname",1); // activate branchname // METHOD2: replace line // fChain->GetEntry(jentry); //read all branches //by b_branchname->GetEntry(ientry); //read only this branch if (fChain == 0) return; Long64_t nentries = (Long64_t)NEntries; if (NEntries <= 0) nentries = fChain->GetEntries(); vector<int> iCountNoPrescale; for (int it = 0; it < Ntrig; it++){ iCountNoPrescale.push_back(0); } Long64_t nbytes = 0, nb = 0; //int tempFlag; //TBranch *tempBranch; for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; // if (Cut(ientry) < 0) continue; if (jentry%10000 == 0) cout<<"Processing entry "<<jentry<<"/"<<nentries<<"\r"<<flush<<endl; // 1. Loop to check which Bit fired // Triggernames are assigned to trigger cuts in unambigous way! // If you define a new trigger also define a new unambigous name! SetMapBitOfStandardHLTPath(); // Cut on muon quality // init for (int i=0;i<10;i++) { NL1OpenMu = 0; L1OpenMuPt[i] = -999.; L1OpenMuE[i] = -999.; L1OpenMuEta[i] = -999.; L1OpenMuPhi[i] = -999.; L1OpenMuIsol[i] = -999; L1OpenMuMip[i] = -999; L1OpenMuFor[i] = -999; L1OpenMuRPC[i] = -999; L1OpenMuQal[i] = -999; } for (int i=0;i<NL1Mu;i++) { if ( L1MuQal[i]==2 || L1MuQal[i]==3 || L1MuQal[i]==4 || L1MuQal[i]==5 || L1MuQal[i]==6 || L1MuQal[i]==7 ) { L1OpenMuPt[NL1OpenMu] = L1MuPt[i]; L1OpenMuE[NL1OpenMu] = L1MuE[i]; L1OpenMuEta[NL1OpenMu] = L1MuEta[i]; L1OpenMuPhi[NL1OpenMu] = L1MuPhi[i]; L1OpenMuIsol[NL1OpenMu] = L1MuIsol[i]; L1OpenMuMip[NL1OpenMu] = L1MuMip[i]; L1OpenMuFor[NL1OpenMu] = L1MuFor[i]; L1OpenMuRPC[NL1OpenMu] = L1MuRPC[i]; L1OpenMuQal[NL1OpenMu] = L1MuQal[i]; NL1OpenMu++; } } // init for (int i=0;i<10;i++) { NL1GoodSingleMu = 0; L1GoodSingleMuPt[i] = -999.; L1GoodSingleMuE[i] = -999.; L1GoodSingleMuEta[i] = -999.; L1GoodSingleMuPhi[i] = -999.; L1GoodSingleMuIsol[i] = -999; L1GoodSingleMuMip[i] = -999; L1GoodSingleMuFor[i] = -999; L1GoodSingleMuRPC[i] = -999; L1GoodSingleMuQal[i] = -999; } // Cut on muon quality for (int i=0;i<NL1Mu;i++) { if ( L1MuQal[i]==4 || L1MuQal[i]==5 || L1MuQal[i]==6 || L1MuQal[i]==7 ) { L1GoodSingleMuPt[NL1GoodSingleMu] = L1MuPt[i]; L1GoodSingleMuE[NL1GoodSingleMu] = L1MuE[i]; L1GoodSingleMuEta[NL1GoodSingleMu] = L1MuEta[i]; L1GoodSingleMuPhi[NL1GoodSingleMu] = L1MuPhi[i]; L1GoodSingleMuIsol[NL1GoodSingleMu] = L1MuIsol[i]; L1GoodSingleMuMip[NL1GoodSingleMu] = L1MuMip[i]; L1GoodSingleMuFor[NL1GoodSingleMu] = L1MuFor[i]; L1GoodSingleMuRPC[NL1GoodSingleMu] = L1MuRPC[i]; L1GoodSingleMuQal[NL1GoodSingleMu] = L1MuQal[i]; NL1GoodSingleMu++; } } // init for (int i=0;i<10;i++) { NL1GoodDoubleMu = 0; L1GoodDoubleMuPt[i] = -999.; L1GoodDoubleMuE[i] = -999.; L1GoodDoubleMuEta[i] = -999.; L1GoodDoubleMuPhi[i] = -999.; L1GoodDoubleMuIsol[i] = -999; L1GoodDoubleMuMip[i] = -999; L1GoodDoubleMuFor[i] = -999; L1GoodDoubleMuRPC[i] = -999; L1GoodDoubleMuQal[i] = -999; } // Cut on muon quality for (int i=0;i<NL1Mu;i++) { if ( L1MuQal[i]==3 || L1MuQal[i]==5 || L1MuQal[i]==6 || L1MuQal[i]==7 ) { L1GoodDoubleMuPt[NL1GoodDoubleMu] = L1MuPt[i]; L1GoodDoubleMuE[NL1GoodDoubleMu] = L1MuE[i]; L1GoodDoubleMuEta[NL1GoodDoubleMu] = L1MuEta[i]; L1GoodDoubleMuPhi[NL1GoodDoubleMu] = L1MuPhi[i]; L1GoodDoubleMuIsol[NL1GoodDoubleMu] = L1MuIsol[i]; L1GoodDoubleMuMip[NL1GoodDoubleMu] = L1MuMip[i]; L1GoodDoubleMuFor[NL1GoodDoubleMu] = L1MuFor[i]; L1GoodDoubleMuRPC[NL1GoodDoubleMu] = L1MuRPC[i]; L1GoodDoubleMuQal[NL1GoodDoubleMu] = L1MuQal[i]; NL1GoodDoubleMu++; } } ////////////////////////////////////////////////////////////////// // Loop over HLT paths and do rate counting ////////////////////////////////////////////////////////////////// for (int it = 0; it < Ntrig; it++){ triggerBit[it] = false; triggerBitNoPrescale[it] = false; previousBitsFired[it] = false; allOtherBitsFired[it] = false; if ( doMuonCut && MCmu3!=0 ) continue; if( doElecCut && MCel3!=0 ) continue; ////////////////////////////////////////////////////////////////// // Standard paths if ( (map_BitOfStandardHLTPath.find(trignames[it])->second==1) ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } ////////////////////////////////////////////////////////////////// // All others incl. OpenHLT from here: /* ***************************** */ /* ****** Taus start here ****** */ /* ***************************** */ else if (trignames[it].CompareTo("OpenHLT2TauPixel") == 0) { if ( L1_DoubleTauJet40==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=2) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("HighPtTauMET") == 0) { if ( L1_SingleTauJet80==1 ) { // L1 Seed if(OpenHltTauPassed(20.,5.,3.,1,20.,0)>=1 && recoMetCal>=65.) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("TauMET") == 0) { if ( L1_TauJet30_ETM30==1 ) { // L1 Seed if(OpenHltTauPassed(20.,5.,3.,1,15.,0)>=1 && recoMetCal>=35.) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("TauMET_NoSi") == 0) { if ( L1_TauJet30_ETM30==1 ) { // L1 Seed if(OpenHltTauPassed(20.,5.,0.,0,0.,0)>=1 && recoMetCal>=35.) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("DiTau") == 0) { if ( L1_DoubleTauJet40==1 ) { // L1 Seed //PrintOhltVariables(3,tau); if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=2) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("DiTau_NoSi") == 0) { if ( L1_DoubleTauJet40==1 ) { // L1 Seed //PrintOhltVariables(3,tau); if(OpenHltTauPassed(15.,5.,0.,0,0.,0)>=2) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("MuonTau") == 0) { if ( L1_Mu5_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=1 && OpenHlt1MuonPassed(5.,0.,0.,2.,1)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("MuonTau_NoSi") == 0) { if ( L1_Mu5_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,0.,0,0.,0)>=1 && OpenHlt1MuonPassed(5.,0.,0.,2.,1)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("MuonTau_NoL1") == 0) { if ( L1_Mu5_Jet15==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=1 && OpenHlt1MuonPassed(5.,0.,0.,2.,1)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("MuonTau_NoL2") == 0) { if ( L1_Mu5_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(0.,999.,3.,1,0.,0)>=1 && OpenHlt1MuonPassed(5.,0.,0.,2.,1)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("MuonTau_NoL25") == 0) { if ( L1_Mu5_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,0.,0,0.,0)>=1 && OpenHlt1MuonPassed(5.,0.,5.,2.,1)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronTau") == 0) { if ( L1_IsoEG10_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=1 && OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronTau_NoL1") == 0) { if ( L1_IsoEG10_Jet15==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,3.,1,0.,0)>=1 && OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronTau_NoL2") == 0) { if ( L1_IsoEG10_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(0.,999.,3.,1,0.,0)>=1 && OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronTau_NoL25") == 0) { if ( L1_IsoEG10_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,0.,0,0.,0)>=1 && OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronTau_NoSi") == 0) { if ( L1_IsoEG10_TauJet20==1 ) { // L1 Seed if(OpenHltTauPassed(15.,5.,0.,0,0.,0)>=1 && OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 ) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("ElectronMET") == 0) { if ( L1_SingleIsoEG12==1 ) { // L1 Seed if(OpenHlt1ElectronPassed(10.,1,0.06,3.)>=1 && recoMetCal>=35.) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } /* ****** Taus end here ****** */ /* ********************************** */ /* ****** Electrons start here ****** */ /* ********************************** */ else if (trignames[it].CompareTo("OpenHLT1Electron") == 0) { if ( L1_SingleIsoEG12==1 ) { // L1 Seed //PrintOhltVariables(3,electron); if(OpenHlt1ElectronPassed(15.,1,0.06,3.)>=1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } /* ****** Electrons end here ****** */ /* ******************************** */ /* ****** Photons start here ****** */ /* ******************************** */ else if (trignames[it].CompareTo("OpenHLT1Photon") == 0) { if ( L1_SingleIsoEG12==1 ) { // L1 Seed //PrintOhltVariables(3,photon); if(OpenHlt1PhotonPassed(30.,1,0,1.5,6.,4.)>=1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } /* ****** Photons end here ****** */ /* ******************************** */ /* ****** Muons start here ****** */ /* ******************************** */ else if (trignames[it].CompareTo("OpenHLT1MuonNonIso") == 0) { if( L1_SingleMu7==1) { // L1 Seed //PrintOhltVariables(1,muon); //PrintOhltVariables(2,muon); //PrintOhltVariables(3,muon); if(OpenHlt1MuonPassed(7.,16.,16.,2.,0)>=1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("OpenHLT1MuonIso") == 0) { if( L1_SingleMu7==1) { // L1 Seed //PrintOhltVariables(1,muon); //PrintOhltVariables(2,muon); //PrintOhltVariables(3,muon); if(OpenHlt1MuonPassed(7.,11.,11.,2.,1)>=1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } else if (trignames[it].CompareTo("OpenHLT2MuonNonIso") == 0) { if( L1_SingleMu3==1) { // L1 Seed if(OpenHlt2MuonPassed(3.,3.,3.,2.,0)>1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } /* ****** Muons end here ****** */ /* ******************************** */ /* ****** Jets start here ****** */ /* ******************************** */ else if (trignames[it].CompareTo("OpenHLT1jet") == 0) { if( L1_SingleJet150==1) { // L1 Seed if(OpenHlt1JetPassed(200)>=1) { triggerBitNoPrescale[it] = true; if ((iCountNoPrescale[it]) % map_pathHLTPrescl.find(trignames[it])->second == 0) { triggerBit[it] = true; } } } } /* ****** Jets end here ****** */ } /* ******************************** */ // 2. Loop to check overlaps for (int it = 0; it < Ntrig; it++){ if (triggerBitNoPrescale[it]) { (iCountNoPrescale[it])++; } if (triggerBit[it]) { (iCount->at(it))++; for (int it2 = 0; it2 < Ntrig; it2++){ if ( (it2<it) && triggerBit[it2] ) previousBitsFired[it] = true; if ( (it2!=it) && triggerBit[it2] ) allOtherBitsFired[it] = true; if (triggerBit[it2]) (overlapCount->at(it))[it2] += 1; } if (not previousBitsFired[it]) (sPureCount->at(it))++; if (not allOtherBitsFired[it]) (pureCount->at(it))++; } } /* ******************************** */ } } void OHltTree::PrintOhltVariables(int level, int type) { cout << "Run " << Run <<", Event " << Event << endl; switch(type) { case muon: if(level == 3) { cout << "Level 3: number of muons = " << NohMuL3 << endl; for (int i=0;i<NohMuL3;i++) { cout << "ohMuL3Pt["<<i<<"] = " << ohMuL3Pt[i] << endl; cout << "ohMuL3PtErr["<<i<<"] = " << ohMuL3PtErr[i] << endl; cout << "ohMuL3Pt+Err["<<i<<"] = " << ohMuL3Pt[i]+2.2*ohMuL3PtErr[i]*ohMuL3Pt[i] << endl; cout << "ohMuL3Phi["<<i<<"] = " << ohMuL3Phi[i] << endl; cout << "ohMuL3Eta["<<i<<"] = " << ohMuL3Eta[i] << endl; cout << "ohMuL3Chg["<<i<<"] = " << ohMuL3Chg[i] << endl; cout << "ohMuL3Iso["<<i<<"] = " << ohMuL3Iso[i] << endl; cout << "ohMuL3Dr["<<i<<"] = " << ohMuL3Dr[i] << endl; cout << "ohMuL3Dz["<<i<<"] = " << ohMuL3Dz[i] << endl; cout << "ohMuL3L2idx["<<i<<"] = " << ohMuL3L2idx[i] << endl; } } else if(level == 2) { cout << "Level 2: number of muons = " << NohMuL2 << endl; for (int i=0;i<NohMuL2;i++) { cout << "ohMuL2Pt["<<i<<"] = " << ohMuL2Pt[i] << endl; cout << "ohMuL2PtErr["<<i<<"] = " << ohMuL2PtErr[i] << endl; cout << "ohMuL2Pt+Err["<<i<<"] = " << ohMuL2Pt[i]+3.9*ohMuL2PtErr[i]*ohMuL2Pt[i] << endl; cout << "ohMuL2Phi["<<i<<"] = " << ohMuL2Phi[i] << endl; cout << "ohMuL2Eta["<<i<<"] = " << ohMuL2Eta[i] << endl; cout << "ohMuL2Chg["<<i<<"] = " << ohMuL2Chg[i] << endl; cout << "ohMuL2Iso["<<i<<"] = " << ohMuL2Iso[i] << endl; cout << "ohMuL2Dr["<<i<<"] = " << ohMuL2Dr[i] << endl; cout << "ohMuL2Dz["<<i<<"] = " << ohMuL2Dz[i] << endl; } } else if(level == 1) { for(int i=0;i<NL1OpenMu;i++) { cout << "L1MuPt["<<i<<"] = " << L1MuPt[i] << endl; cout << "L1MuEta["<<i<<"] = " << L1MuEta[i] << endl; cout << "L1MuPhi["<<i<<"] = " << L1MuPhi[i] << endl; cout << "L1MuIsol["<<i<<"] = " << L1MuIsol[i] << endl; cout << "L1MuQal["<<i<<"] = " << L1MuQal[i] << endl; } } else { cout << "PrintOhltVariables: Ohlt has Muon variables only for L1, 2, and 3. Must provide one." << endl; } break; case electron: cout << "oh: number of electrons = " << NohEle << endl; for (int i=0;i<NohEle;i++) { cout << "ohEleEt["<<i<<"] = " << ohEleEt[i] << endl; cout << "ohElePhi["<<i<<"] = " << ohElePhi[i] << endl; cout << "ohEleEta["<<i<<"] = " << ohEleEta[i] << endl; cout << "ohEleE["<<i<<"] = " << ohEleE[i] << endl; cout << "ohEleP["<<i<<"] = " << ohEleP[i] << endl; cout << "ohElePt["<<i<<"] =" << ohEleP[i] * TMath::Sin(2*TMath::ATan(TMath::Exp(-1*ohEleEta[i]))) << endl; cout << "ohEleHiso["<<i<<"] = " << ohEleHiso[i] << endl; cout << "ohEleTiso["<<i<<"] = " << ohEleTiso[i] << endl; cout << "ohEleL1iso["<<i<<"] = " << ohEleL1iso[i] << endl; cout << "recoElecE["<<i<<"] = " << recoElecE[i] << endl; cout << "recoElecEt["<<i<<"] = " << recoElecEt[i] << endl; cout << "recoElecPt["<<i<<"] = " << recoElecPt[i] << endl; cout << "recoElecPhi["<<i<<"] = " << recoElecPhi[i] << endl; cout << "recoElecEta["<<i<<"] = " << recoElecEta[i] << endl; } break; case photon: cout << "oh: number of photons = " << NohPhot << endl; for (int i=0;i<NohPhot;i++) { cout << "ohPhotEt["<<i<<"] = " << ohPhotEt[i] << endl; cout << "ohPhotPhi["<<i<<"] = " << ohPhotPhi[i] << endl; cout << "ohPhotEta["<<i<<"] = " << ohPhotEta[i] << endl; cout << "ohPhotEiso["<<i<<"] = " << ohPhotEiso[i] << endl; cout << "ohPhotHiso["<<i<<"] = " << ohPhotHiso[i] << endl; cout << "ohPhotTiso["<<i<<"] = " << ohPhotTiso[i] << endl; cout << "ohPhotL1iso["<<i<<"] = " << ohPhotL1iso[i] << endl; cout << "recoPhotE["<<i<<"] = " << recoPhotE[i] << endl; cout << "recoPhotEt["<<i<<"] = " << recoPhotEt[i] << endl; cout << "recoPhotPt["<<i<<"] = " << recoPhotPt[i] << endl; cout << "recoPhotPhi["<<i<<"] = " << recoPhotPhi[i] << endl; cout << "recoPhotEta["<<i<<"] = " << recoPhotEta[i] << endl; } break; case jet: cout << "oh: number of recoJetCal = " << NrecoJetCal << endl; for (int i=0;i<NrecoJetCal;i++) { cout << "recoJetCalE["<<i<<"] = " << recoJetCalE[i] << endl; cout << "recoJetCalEt["<<i<<"] = " << recoJetCalEt[i] << endl; cout << "recoJetCalPt["<<i<<"] = " << recoJetCalPt[i] << endl; cout << "recoJetCalPhi["<<i<<"] = " << recoJetCalPhi[i] << endl; cout << "recoJetCalEta["<<i<<"] = " << recoJetCalEta[i] << endl; } break; case tau: cout << "oh: number of taus = " << NohTau1 << endl; for (int i=0;i<NohTau1;i++) { cout<<"ohTauEt["<<i<<"] = " <<ohTau1Pt[i]<<endl; cout<<"ohTauEiso["<<i<<"] = " <<ohTau1Eiso[i]<<endl; cout<<"ohTauL25Tpt["<<i<<"] = " <<ohTau1L25Tpt[i]<<endl; cout<<"ohTauL25Tiso["<<i<<"] = " <<ohTau1L25Tiso[i]<<endl; cout<<"ohTauL3Tpt["<<i<<"] = " <<ohTau1L3Tpt[i]<<endl; cout<<"ohTauL3Tiso["<<i<<"] = " <<ohTau1L3Tiso[i]<<endl; } break; default: cout << "PrintOhltVariables: You did not provide correct object type." <<endl; break; } } int OHltTree::OpenHltTauPassed(float Et,float Eiso, float L25Tpt, int L25Tiso, float L3Tpt, int L3Tiso) { int rc = 0; // Loop over all oh electrons for (int i=0;i<NohTau1;i++) { if (ohTau1Pt[i] >= Et) { if (ohTau1Eiso[i] <= Eiso) if (ohTau1L25Tpt[i] >= L25Tpt) if (ohTau1L25Tiso[i] >= L25Tiso) if (ohTau1L3Tpt[i] >= L3Tpt) if (ohTau1L3Tiso[i] >= L3Tiso) rc++; } } return rc; } int OHltTree::OpenHlt1ElectronPassed(float Et, int L1iso, float Tiso, float Hiso) { int rc = 0; // Loop over all oh electrons for (int i=0;i<NohEle;i++) { if ( ohEleEt[i] > Et) { if ( ohEleHiso[i] < Hiso || ohEleHiso[i]/ohEleEt[i] < 0.05) if (ohEleNewSC[i]==1) if (ohElePixelSeeds[i]>0) if ( ohEleTiso[i] < Tiso && ohEleTiso[i] != -999.) if ( ohEleL1iso[i] >= L1iso ) // L1iso is 0 or 1 rc++; } } return rc; } int OHltTree::OpenHlt1PhotonPassed(float Et, int L1iso, float Tiso, float Eiso, float HisoBR, float HisoEC) { int rc = 0; // Loop over all oh photons for (int i=0;i<NohPhot;i++) { if ( ohPhotEt[i] > Et) if ( ohPhotL1iso[i] >= L1iso ) if( ohPhotTiso[i]<=Tiso ) if( ohPhotEiso[i] < Eiso ) { if( (TMath::Abs(ohPhotEta[i]) < 1.5 && ohPhotHiso[i] < HisoBR ) || (1.5 < TMath::Abs(ohPhotEta[i]) && TMath::Abs(ohPhotEta[i]) < 2.5 && ohPhotHiso[i] < HisoEC ) ) rc++; } } return rc; } int OHltTree::OpenHlt1MuonPassed(double ptl1, double ptl2, double ptl3, double dr, int iso) { // This example implements the new (CMSSW_2_X) flat muon pT cuts. // To emulate the old behavior, the cuts should be written // L2: ohMuL2Pt[i]+3.9*ohMuL2PtErr[i]*ohMuL2Pt[i] // L3: ohMuL3Pt[i]+2.2*ohMuL3PtErr[i]*ohMuL3Pt[i] int rcL1 = 0; int rcL2 = 0; int rcL3 = 0; int rcL1L2L3 = 0; int NL1Mu = 8; int L1MinimalQuality = 4; int L1MaximalQuality = 7; // Loop over all oh L3 muons and apply cuts for (int i=0;i<NohMuL3;i++) { int bestl1l2drmatchind = -1; double bestl1l2drmatch = 999.0; if( fabs(ohMuL3Eta[i]) < 2.5 ) { // L3 eta cut if(ohMuL3Pt[i] > ptl3) { // L3 pT cut if(ohMuL3Dr[i] < dr) { // L3 DR cut if(ohMuL3Iso[i] >= iso) { // L3 isolation rcL3++; // Begin L2 muons here. // Get best L2<->L3 match, then // begin applying cuts to L2 int j = ohMuL3L2idx[i]; // Get best L2<->L3 match if ( (fabs(ohMuL2Eta[j])<2.5) ) { // L2 eta cut if( ohMuL2Pt[j] > ptl2 ) { // L2 pT cut rcL2++; // Begin L1 muons here. // Require there be an L1Extra muon Delta-R // matched to the L2 candidate, and that it have // good quality and pass nominal L1 pT cuts for(int k = 0;k < NL1Mu;k++) { if( (L1MuPt[k] < ptl1) ) // L1 pT cut continue; double deltaphi = fabs(ohMuL2Phi[j]-L1MuPhi[k]); if(deltaphi > 3.14159) deltaphi = (2.0 * 3.14159) - deltaphi; double deltarl1l2 = sqrt((ohMuL2Eta[j]-L1MuEta[k])*(ohMuL2Eta[j]-L1MuEta[k]) + (deltaphi*deltaphi)); if(deltarl1l2 < bestl1l2drmatch) { bestl1l2drmatchind = k; bestl1l2drmatch = deltarl1l2; } } // End loop over L1Extra muons // Cut on L1<->L2 matching and L1 quality if((bestl1l2drmatch > 0.3) || (L1MuQal[bestl1l2drmatchind] < L1MinimalQuality) || (L1MuQal[bestl1l2drmatchind] > L1MaximalQuality)) { rcL1 = 0; } else { rcL1++; rcL1L2L3++; } // End L1 matching and quality cuts } // End L2 pT cut } // End L2 eta cut } // End L3 isolation cut } // End L3 DR cut } // End L3 pT cut } // End L3 eta cut } // End loop over L3 muons return rcL1L2L3; } int OHltTree::OpenHlt2MuonPassed(double ptl1, double ptl2, double ptl3, double dr, int iso) { // Note that the dimuon paths generally have different L1 requirements than // the single muon paths. Therefore this example is implemented in a separate // function. // // This example implements the new (CMSSW_2_X) flat muon pT cuts. // To emulate the old behavior, the cuts should be written // L2: ohMuL2Pt[i]+3.9*ohMuL2PtErr[i]*ohMuL2Pt[i] // L3: ohMuL3Pt[i]+2.2*ohMuL3PtErr[i]*ohMuL3Pt[i] int rcL1 = 0; int rcL2 = 0; int rcL3 = 0; int rcL1L2L3 = 0; int NL1Mu = 8; int L1MinimalQuality = 3; int L1MaximalQuality = 7; // Loop over all oh L3 muons and apply cuts for (int i=0;i<NohMuL3;i++) { int bestl1l2drmatchind = -1; double bestl1l2drmatch = 999.0; if( fabs(ohMuL3Eta[i]) < 2.5 ) { // L3 eta cut if(ohMuL3Pt[i] > ptl3) { // L3 pT cut if(ohMuL3Dr[i] < dr) { // L3 DR cut if(ohMuL3Iso[i] >= iso) { // L3 isolation rcL3++; // Begin L2 muons here. // Get best L2<->L3 match, then // begin applying cuts to L2 int j = ohMuL3L2idx[i]; // Get best L2<->L3 match if ( (fabs(ohMuL2Eta[j])<2.5) ) { // L2 eta cut if( ohMuL2Pt[j] > ptl2 ) { // L2 pT cut rcL2++; // Begin L1 muons here. // Require there be an L1Extra muon Delta-R // matched to the L2 candidate, and that it have // good quality and pass nominal L1 pT cuts for(int k = 0;k < NL1Mu;k++) { if( (L1MuPt[k] < ptl1) ) // L1 pT cut continue; double deltaphi = fabs(ohMuL2Phi[j]-L1MuPhi[k]); if(deltaphi > 3.14159) deltaphi = (2.0 * 3.14159) - deltaphi; double deltarl1l2 = sqrt((ohMuL2Eta[j]-L1MuEta[k])*(ohMuL2Eta[j]-L1MuEta[k]) + (deltaphi*deltaphi)); if(deltarl1l2 < bestl1l2drmatch) { bestl1l2drmatchind = k; bestl1l2drmatch = deltarl1l2; } } // End loop over L1Extra muons // Cut on L1<->L2 matching and L1 quality if((bestl1l2drmatch > 0.3) || (L1MuQal[bestl1l2drmatchind] < L1MinimalQuality) || (L1MuQal[bestl1l2drmatchind] > L1MaximalQuality)) { rcL1 = 0; } else { rcL1++; rcL1L2L3++; } // End L1 matching and quality cuts } // End L2 pT cut } // End L2 eta cut } // End L3 isolation cut } // End L3 DR cut } // End L3 pT cut } // End L3 eta cut } // End loop over L3 muons return rcL1L2L3; } int OHltTree::OpenHlt1JetPassed(double pt) { int rc = 0; // Loop over all oh photons for (int i=0;i<NrecoJetCal;i++) { if(recoJetCalPt[i]>pt) { // Jet pT cut rc++; } } return rc; }
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
f57b014465c52b8f35f27648dd25253029815f33
d8fb09c5c748528be73e18456ceb951a45228f03
/circle_V2/circle_V2.ino
01dfbeacdd7578532ea065fc1e47c8ddcc986d97
[]
no_license
noob-master147/Electronics-basics
382d419ed7a6a399d52d161daf4255e0b4c892b0
58fab5bd9032ff43de9d3f41dfd345bc7a6fbfd1
refs/heads/master
2020-05-20T23:02:54.431593
2020-04-17T18:54:56
2020-04-17T18:54:56
185,794,264
0
2
null
2019-10-01T08:01:20
2019-05-09T12:26:10
C++
UTF-8
C++
false
false
895
ino
#include<Servo.h> Servo s1; Servo s2; Servo s3; void setup() { pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); s1.attach(8); s1.write(90); s2.attach(9); s2.write(90); s3.attach(10); s3.write(90); delay(5000); // s1.write(60); // s2.write(90); // s3.write(120); } void loop() { cycle2(); cycle3(); cycle4(); cycle1(); } void cycle1() { for(int i=0; i<30; i++) { s1.write(90-i); s2.write(60+i); s3.write(90+i); delay(5); } } void cycle2() { for(int i=0; i<30; i++) { s1.write(60+i); s2.write(90+i); s3.write(120-i); delay(5); } } void cycle3() { for(int i=0; i<30; i++) { s1.write(90+i); s2.write(120-i); s3.write(90-i); delay(5); } } void cycle4() { for(int i=0; i<30; i++) { s1.write(120-i); s2.write(90-i); s3.write(60+1); delay(5); } }
[ "divyanshkhandelwal147@gmail.com" ]
divyanshkhandelwal147@gmail.com
e5eb340d3c7f87feb4b463d9842388d832df849b
c93f0772d1ed25fc575f989d46ff2cf3427a98c7
/ImageToolBox/ImageToolBox.cpp
37a7724bcf80b4d5e9fcd3e9e0f8b47a3ab3b1ed
[]
no_license
datakun/ImageToolBox
97c315bafc53530636f9a5c7623e7f4ec3a5193a
1d8e54e0da04fbe7eb1de6e3eedb562010e2db5b
refs/heads/master
2021-01-22T08:48:43.894931
2013-12-11T18:07:34
2013-12-11T18:07:34
15,259,154
2
0
null
null
null
null
UTF-8
C++
false
false
6,124
cpp
// ImageToolBox.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "ImageToolBox.h" #include "MainFrm.h" #include "ChildFrm.h" #include "ImageToolBoxDoc.h" #include "ImageToolBoxView.h" #include "Dib.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CImageToolBoxApp BEGIN_MESSAGE_MAP(CImageToolBoxApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CImageToolBoxApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup) ON_COMMAND(ID_EDIT_PASTE, &CImageToolBoxApp::OnEditPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, &CImageToolBoxApp::OnUpdateEditPaste) END_MESSAGE_MAP() // CImageToolBoxApp construction CImageToolBoxApp::CImageToolBoxApp() : m_pNewDib(NULL) { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("ImageToolBox.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CImageToolBoxApp object CImageToolBoxApp::~CImageToolBoxApp() { if (m_pNewDib != NULL) delete m_pNewDib; } CImageToolBoxApp theApp; // CImageToolBoxApp initialization BOOL CImageToolBoxApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_ImageToolBoxTYPE, RUNTIME_CLASS(CImageToolBoxDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CImageToolBoxView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // call DragAcceptFiles only if there's a suffix // In an MDI app, this should occur immediately after setting m_pMainWnd // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Don't Open if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } int CImageToolBoxApp::ExitInstance() { //TODO: handle additional resources you may have added AfxOleTerm(FALSE); return CWinApp::ExitInstance(); } // CImageToolBoxApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CImageToolBoxApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CImageToolBoxApp message handlers void AfxNewImage(CDib& dib) { CImageToolBoxApp* pApp = (CImageToolBoxApp*)AfxGetApp(); pApp->m_pNewDib = &dib; AfxGetMainWnd()->SendMessage(WM_COMMAND, ID_FILE_NEW); } void CImageToolBoxApp::OnEditPaste() { // TODO: Add your command handler code here CDib dib; dib.PasteFromClipboard(); AfxNewImage(dib); } void CImageToolBoxApp::OnUpdateEditPaste(CCmdUI *pCmdUI) { // TODO: Add your command update UI handler code here pCmdUI->Enable(IsClipboardFormatAvailable(CF_DIB)); }
[ "sigmadream@gmail.com" ]
sigmadream@gmail.com
cbb4ab04908a7f07322ac4f752533d43cb79f21f
23ba742dbd55d9d2cef68e624f2d23e4fd76e8a3
/src/saiga/opengl/query/gpuTimer.h
9d2c587984a72bce5fec1b5579e1a0450d502390
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
darglein/saiga
a4026b86e7397266e5036294a6435d85657f39ee
7617871a8ccdde58847e4f6871bd527f32652a79
refs/heads/master
2023-08-17T03:33:44.387706
2023-08-15T14:54:47
2023-08-15T14:54:47
97,219,629
135
26
MIT
2023-02-13T16:24:21
2017-07-14T09:55:50
C++
UTF-8
C++
false
false
2,691
h
/** * Copyright (c) 2021 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #pragma once #include "saiga/opengl/query/timeStampQuery.h" #include "saiga/core/time/timer.h" namespace Saiga { /** * Asynchronous OpenGL GPU timer. * * Meassuers the time of the OpenGL calls between startTimer and stopTimer. * These calls do not empty the GPU command queue and return immediately. * * startTimer and stopTimer can only be called once per frame. * startTimer and stopTimer from multiple GPUTimers CAN be interleaved. * * The difference between GPUTimer and TimerQuery is, that GPUTimer uses internally GL_TIMESTAMP queries, * while TimerQuery uses GL_TIME_ELAPSED queries. GL_TIME_ELAPSED queries can not be interleaved, so * GPUTimer is the recommended way of OpenGL performance meassurment. * * Core since version 3.3 * */ class SAIGA_OPENGL_API MultiFrameOpenGLTimer : public TimestampTimer { public: MultiFrameOpenGLTimer(bool use_time_stamps = true); ~MultiFrameOpenGLTimer(); /** * Creates the underlying OpenGL objects. */ void create(); void Start(); void Stop(); float getTimeMS(); double getTimeMSd(); uint64_t getTimeNS(); std::pair<uint64_t, uint64_t> LastMeasurement() { return {begin_time, end_time}; } private: QueryObject queries[2][2]; int queryBackBuffer = 0, queryFrontBuffer = 1; uint64_t elapsed_time = 0; uint64_t end_time = 0; uint64_t begin_time = 0; bool use_time_stamps; void swapQueries(); }; /** * Exponentially filtered GPUTimer. * time = alpha * newTime + (1-alpha) * oldTime; */ class SAIGA_OPENGL_API FilteredMultiFrameOpenGLTimer : public MultiFrameOpenGLTimer { public: double alpha = 0.05; void stopTimer(); float getTimeMS(); double getTimeMSd(); private: double currentTimeMS = 0; }; class SAIGA_OPENGL_API OpenGLTimer { public: OpenGLTimer(); void start(); GLuint64 stop(); float getTimeMS(); protected: QueryObject queries[2]; GLuint64 time; }; template <typename T> class SAIGA_OPENGL_API ScopedOpenGLTimer : public OpenGLTimer { public: T* target; ScopedOpenGLTimer(T* target) : target(target) { start(); } ScopedOpenGLTimer(T& target) : target(&target) { start(); } ~ScopedOpenGLTimer() { stop(); T time = static_cast<T>(getTimeMS()); *target = time; } }; class SAIGA_OPENGL_API ScopedOpenGLTimerPrint : public OpenGLTimer { public: std::string name; ScopedOpenGLTimerPrint(const std::string& name); ~ScopedOpenGLTimerPrint(); }; } // namespace Saiga
[ "darius.rueckert@fau.de" ]
darius.rueckert@fau.de
dce34cd35bcbe13dc27a70a1b5e2a30f81b2fab0
c03615f53093643e3c1e323b83cbe77970966575
/PRT/3rdParty/cgal/cgal/include/CGAL/internal/Surface_mesh_deformation/Spokes_and_rims_iterator.h
3432cca51e1050c3ea859f65c21cdf9f08327fad
[]
no_license
fangguanya/PRT
0925b28671e756a6e9431fd57149cf2eebc94818
77c1b8e5f3a7a149825ad0cc3ef6002816222622
refs/heads/master
2021-06-08T20:54:22.954395
2016-11-24T07:38:11
2016-11-24T07:38:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
h
// Copyright (c) 2014 GeometryFactory // All rights reserved. // // This file is part of CGAL (www.cgal.org). // 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. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // $URL:$ // $Id:$ // // Author(s) : Ilker O. Yaz #ifndef CGAL_SURFACE_MODELING_SPOKES_AND_RIMS_ITERATOR_H #define CGAL_SURFACE_MODELING_SPOKES_AND_RIMS_ITERATOR_H /// @cond CGAL_DOCUMENT_INTERNAL namespace CGAL { namespace internal { /** * Currently this class is not used by surface modeling package, just leave it for possible future need. * Provide simple functionality for iterating over spoke and rim edges * - use get_descriptor() to obtain active edge * - get_iterator() always holds spoke edges */ /// \code /// // how to use Spokes_and_rims_iterator /// boost::tie(e_begin, e_end) = out_edges(vertex, halfedge_graph); /// Spokes_and_rims_iterator<HalfedgeGraph> rims_it(e_begin, halfedge_graph); /// /// for ( ; rims_it.get_iterator() != e_end; ++rims_it ) /// { /// halfedge_descriptor active_hedge = rims_it.get_descriptor(); /// // use active_edge as you like /// } /// \endcode template<class HalfedgeGraph> class Spokes_and_rims_iterator { public: typedef typename boost::graph_traits<HalfedgeGraph>::out_edge_iterator out_edge_iterator; typedef typename boost::graph_traits<HalfedgeGraph>::halfedge_descriptor halfedge_descriptor; Spokes_and_rims_iterator(out_edge_iterator edge_iterator, HalfedgeGraph& halfedge_graph) : is_current_rim(false), iterator(edge_iterator), descriptor(halfedge(*edge_iterator)), halfedge_graph(halfedge_graph) { } /// descriptor will be assigned to next valid edge, note that iterator might not change Spokes_and_rims_iterator<HalfedgeGraph>& operator++() { // loop through one spoke then one rim edge if(!is_current_rim && !is_border(descriptor, halfedge_graph)) // it is rim edge's turn { is_current_rim = true; descriptor = next(descriptor, halfedge_graph); } else // if current edge is rim OR there is no rim edge (current spoke edge is boudary) { // then iterate to next spoke edge is_current_rim = false; descriptor = halfedge(*(++iterator)); } return *this; } out_edge_iterator get_iterator() { return iterator; } edge_descriptor get_descriptor() { return descriptor; } private: bool is_current_rim; ///< current descriptor is rim or spoke out_edge_iterator iterator; ///< holds spoke edges (i.e. descriptor is not always = *iterator) halfedge_descriptor descriptor; ///< current active halfedge descriptor for looping HalfedgeGraph& halfedge_graph; }; }//namespace internal /// @endcond }//namespace CGAL #endif //CGAL_SURFACE_MODELING_SPOKES_AND_RIMS_ITERATOR_H
[ "succeed.2009@163.com" ]
succeed.2009@163.com
3403070d584048fcbac169c13567a56c440e8b11
0e5ea03c2455b34a2f416c6c94c1669d7fe26e37
/_2017_11_28 Kinect 2048/MainTitle.h
cd84b83d43dbbcb8dc18acda8181b611c41ccda5
[]
no_license
Arroria/__old_project
8682652fac9a95898b41eff5b4fdfab023cda699
efb655b2356bd95744ba19093f25ab266a625722
refs/heads/master
2020-09-05T08:02:44.806509
2019-11-06T18:01:23
2019-11-06T18:01:23
220,033,980
1
1
null
null
null
null
UTF-8
C++
false
false
533
h
#pragma once #include "BaseScene.h" class SettingUI; class GameModeUI; class MainTitle : public BaseScene { private: //Render LPD3DXFONT m_titleFont; LPD3DXFONT m_menuFont; RECT_ex m_startPosition; RECT_ex m_optionPosition; RECT_ex m_exitPosition; //Menu int m_seletedMenu; GameModeUI* m_gameModeUI; SettingUI* m_settingUI; public: virtual void Activated()override; virtual void Update() override; virtual void Render() override; virtual void Disabled() override; public: MainTitle(); virtual ~MainTitle(); };
[ "mermerkwon@naver.com" ]
mermerkwon@naver.com
a74cf6e92ff56bd413af04a8d282731f6db8fede
1106985164494c361c6ef017189cd6f53f6009d4
/zzz_Unsorted/FileOperations.cpp
dbb81a131f08655ce7310a95ce53771dae8cb4ad
[]
no_license
SlickHackz/famous-problems-cpp-solutions
b7f0066a03404a20c1a4b483acffda021595c530
f954b4a8ca856cc749e232bd9d8894a672637ae2
refs/heads/master
2022-08-25T23:14:11.975270
2022-07-17T22:07:03
2022-07-17T22:07:03
71,126,427
1
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include<iostream> #include<fstream> using namespace std; int main() { int arr[] = {20,8,-1,-1,22,-1,-1}; int n = sizeof(arr)/sizeof(arr[0]); // (variable to file) ofstream fileobj_v2f; fileobj_v2f.open(); for(int i=0 ; i<=n-1 ; i++) { fprintf(fileobj_v2f,"%d",arr[i]); } cin.get(); cin.get(); return 0; }
[ "prasath17101990@gmail.com" ]
prasath17101990@gmail.com
d1b0adc0f3448adb1aaf0d8fcb97cad505b67dde
c28a6f2c8ce8f986b5c22fd602e7349e68af8f9c
/android/hardware/realtek/hwc/arbiter/ResourceArbiter.h
90abcf97e4a12e867d86937f70d78719a048002f
[]
no_license
BPI-SINOVOIP/BPI-1296-Android6
d6ade74367696c644a1b053b308d164ba53d3f8c
1ba45ab7555440dc3721d6acda3e831e7a3e3ff3
refs/heads/master
2023-02-24T18:23:02.110515
2019-08-09T04:01:16
2019-08-09T04:01:16
166,341,197
0
5
null
null
null
null
UTF-8
C++
false
false
3,328
h
#ifndef __RTK_HWC_RESOURCEARBITER_H_ #define __RTK_HWC_RESOURCEARBITER_H_ #include <hwc_utils.h> #include <utils/Vector.h> #define DEFAULT_PRIORITY 100 class ResourceArbiter { public: class Client { public: enum Sort { V1_Window = 0, V2_Window, OSD1_Window, SUB1_Window, SUB2_Window, NONE_Window, }; Client(uint32_t sort = NONE_Window, uint32_t priority = DEFAULT_PRIORITY) : mSort(sort), mPriority(priority), mResourceOwner(false), mService(NULL) {}; virtual ~Client() { if (mService!=NULL) mService->removeClient(this); }; /* Client Side */ void setResourceArbiter(ResourceArbiter * service) { if (service) service->registerClient(this); }; virtual bool getResourceState() { if (mService == NULL) return false; return isOwner(); }; virtual bool requestResource() { if (mService == NULL) return false; if (isOwner()) return true; return mService->requestResource(this); }; virtual void releaseResource() { if (mService!=NULL) mService->releaseResource(this); }; virtual uint32_t getSort() { return mSort; }; virtual void setPriority(uint32_t priority) { mPriority = priority; }; virtual void setSort(uint32_t sort) { if (sort != mSort) { if (mService != NULL) mService->changeSort(this, sort); else mSort = sort; } }; /*virtual*/ void dump(android::String8& buf, const char* prefix); enum NotifyEvent { RESOURCE_RECOVERY, RESOURCE_OWNER_CHANGE, }; virtual int ResourceEvent(int notify) = 0; private: friend class ResourceArbiter; /* Server Side */ bool isOwner() { return mResourceOwner; }; void setOwner() { mResourceOwner = true; }; void clearOwner() { mResourceOwner = false; }; void stopOwner() { ResourceEvent(RESOURCE_RECOVERY); clearOwner(); }; void notifyOwnerChange() { ResourceEvent(RESOURCE_OWNER_CHANGE); }; uint32_t getPriority() { return mPriority; }; uint32_t mSort; uint32_t mPriority; bool mResourceOwner; ResourceArbiter * mService; }; /* Server */ ResourceArbiter(); virtual ~ResourceArbiter(); virtual void registerClient(Client * client); virtual void removeClient(Client * client); virtual bool requestResource(Client * client); virtual void releaseResource(Client * client); virtual void changeSort(Client * client, uint32_t sort); virtual void dump(android::String8& buf, const char* prefix); private: bool isOwnedByUs(Client * client); pthread_mutex_t mLock; android::Vector<Client*> mList;; }; #endif /* End of __RTK_HWC_RESOURCEARBITER_H_ */
[ "Justin" ]
Justin
a28c451dc0fe8d9733f58b6ac280279146198c83
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/12/04/13.cpp
6920f2b2bda984c5d5d5b1e8c330629e564fbb19
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
12,232
cpp
#include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <cmath> #include <string> #include <vector> #include <map> #include <algorithm> #include <queue> #include <set> #define MAXN 40 #define eps 1e-09 using namespace std; struct coor { double x, y, z; }; int t, h, w, d, sol; int mei, mej; bool wall[MAXN][MAXN]; coor leftline; // = {0, -1, 1} coor rightline; // = {1, -1, 1}; coor topline; // = {1, 1, 1}; coor bottomline; // = {1, 0, 1}; bool pointonline(coor a, coor b) { double inner = a.x * b.x + a.y * b.y + a.z * b.z; if (abs(inner) < eps) return true; return false; } double dist(double x1, double y1, double x2, double y2) { double xdist = x2 - x1; double ydist = y2 - y1; return sqrt(xdist * xdist + ydist * ydist); } double dist(coor a, coor b) { double x1, y1, x2, y2; x1 = a.x / a.z; y1 = a.y / a.z; x2 = b.x / b.z; y2 = b.y / b.z; return dist(x1, y1, x2, y2); } coor makecoor(double a, double b, double c) { coor res; res.x = a; res.y = b; res.z = c; return res; } coor cross(coor a, coor b) { coor res; res.x = a.y * b.z - a.z * b.y; res.y = a.z * b.x - a.x * b.z; res.z = a.x * b.y - a.y * b.x; return res; } int gcd(int a, int b) { if (a < b) return gcd(b, a); if (b == 0) return a; return gcd(b, a % b); } void init() { for (int i = 0; i < MAXN; i++) for (int j = 0; j < MAXN; j++) wall[i][j] = 0; sol = mei = mej = 0; } void read() { string line; cin >> h >> w >> d; getline(cin, line); for (int i = 0; i < h; i++) { getline(cin, line); for (int j = 0; j < w; j++) if (line[j] == '#') wall[i][j] = true; else if (line[j] == 'X') { mei = i; mej = j; } } } void write(int casen) { cout << "Case #" << casen << ": " << sol << endl; } void solve() { double d1, d2, s1, s2, rem, inx, iny; int curi, curj; coor line, intersect; bool doright, dobottom; for (int dir1 = -200; dir1 <= 200; dir1++) for (int dir2 = -200; dir2 <= 200; dir2++) { if ((dir1 == 0 && abs(dir2) != 1) || (dir2 == 0 && abs(dir1) != 1) || (dir1 != 0 && dir2 != 0 && gcd(abs(dir1), abs(dir2)) != 1)) continue; curi = mei; curj = mej; rem = (double) d; d1 = (double) dir1; d2 = (double) dir2; s1 = 0.5; s2 = 0.5; while (true) { if (rem < eps) break; doright = dobottom = true; line = cross(makecoor(s1, s2, 1), makecoor(s1 + d1, s2 + d2, 1)); if (curi == mei && curj == mej && (s1 != 0.5 || s2 != 0.5)) // potential solution if (pointonline(makecoor(0.5, 0.5, 1), line)) if (dist(0.5, 0.5, s1, s2) < rem + eps) { sol++; break; } // intersect with leftline intersect = cross(line, leftline); if (abs(intersect.z) > eps) // not parallel { inx = intersect.x / intersect.z; iny = intersect.y / intersect.z; if (!(s1 == 0.5 && s2 == 0.5 && d1 > 0) && dist(inx, iny, s1, s2) > eps) { if (s1 == 0.5 && s2 == 0.5) doright = false; if (dist(inx, iny, 0, 0) < eps) // bottom leftline corner { rem -= dist(s1, s2, inx, iny); if (wall[curi + 1][curj] && wall[curi][curj - 1] && wall[curi + 1][curj - 1]) // reflect off corner { d1 = -d1; d2 = -d2; s1 = 0; s2 = 0; } else if (!wall[curi + 1][curj - 1]) // pass through corner { curi++; curj--; s1 = 1; s2 = 1; } else if (wall[curi + 1][curj] && !wall[curi][curj - 1]) // reflect off bottom { curj--; d2 = -d2; s1 = 1; s2 = 0; } else if (!wall[curi + 1][curj] && wall[curi][curj - 1]) // reflect off left { curi++; d1 = -d1; s1 = 0; s2 = 1; } else // else it should die rem = -1000; continue; } if (dist(inx, iny, 0, 1) < eps) // top leftline corner { rem -= dist(s1, s2, inx, iny); if (wall[curi - 1][curj] && wall[curi][curj - 1] && wall[curi - 1][curj - 1]) { d1 = -d1; d2 = -d2; s1 = 0; s2 = 1; } else if (!wall[curi - 1][curj - 1]) { curi--; curj--; s1 = 1; s2 = 0; } else if (wall[curi - 1][curj] && !wall[curi][curj - 1]) // reflect off top { curj--; d2 = -d2; s1 = 1; s2 = 1; } else if (!wall[curi - 1][curj] && wall[curi][curj - 1]) // reflect off left { curi--; d1 = -d1; s1 = 0; s2 = 0; } else rem = -1000; continue; } if (iny > 0 && iny < 1) // does intersect with leftline { rem -= dist(s1, s2, inx, iny); if (wall[curi][curj - 1]) { d1 = -d1; s1 = 0; s2 = iny; } else { curj--; s1 = 1; s2 = iny; } continue; } } } // intersect with rightline intersect = cross(line, rightline); if (abs(intersect.z) > eps) // not parallel { inx = intersect.x / intersect.z; iny = intersect.y / intersect.z; if (doright && dist(inx, iny, s1, s2) > eps) { if (dist(inx, iny, 1, 0) < eps) // bottom rightline corner { rem -= dist(s1, s2, inx, iny); if (wall[curi + 1][curj] && wall[curi][curj + 1] && wall[curi + 1][curj + 1]) // reflect off corner { d1 = -d1; d2 = -d2; s1 = 1; s2 = 0; } else if (!wall[curi + 1][curj + 1]) // pass through corner { curi++; curj++; s1 = 0; s2 = 1; } else if (wall[curi + 1][curj] && !wall[curi][curj + 1]) // reflect off bottom { curj++; d2 = -d2; s1 = 0; s2 = 0; } else if (!wall[curi + 1][curj] && wall[curi][curj + 1]) // reflect off right { curi++; d1 = -d1; s1 = 1; s2 = 1; } else // else it should die rem = -1000; continue; } if (dist(inx, iny, 1, 1) < eps) // top rightline corner { rem -= dist(s1, s2, inx, iny); if (wall[curi - 1][curj] && wall[curi][curj + 1] && wall[curi - 1][curj + 1]) { d1 = -d1; d2 = -d2; s1 = 1; s2 = 1; } else if (!wall[curi - 1][curj + 1]) { curi--; curj++; s1 = 0; s2 = 0; } else if (wall[curi - 1][curj] && !wall[curi][curj + 1]) // reflect off top { curj++; d2 = -d2; s1 = 0; s2 = 1; } else if (!wall[curi - 1][curj] && wall[curi][curj + 1]) // reflect off right { curi--; d1 = -d1; s1 = 1; s2 = 0; } else rem = -1000; continue; } if (iny > 0 && iny < 1) // does intersect with rightline { rem -= dist(s1, s2, inx, iny); if (wall[curi][curj + 1]) { d1 = -d1; s1 = 1; s2 = iny; } else { curj++; s1 = 0; s2 = iny; } continue; } } } // intersect with topline intersect = cross(line, topline); if (abs(intersect.z) > eps) // not parallel { inx = intersect.x / intersect.z; iny = intersect.y / intersect.z; if (!(s1 == 0.5 && s2 == 0.5 && d2 < 0) && dist(inx, iny, s1, s2) > eps) { if (s1 == 0.5 && s2 == 0.5) dobottom = false; if (inx > 0 && inx < 1) // does intersect with topline { rem -= dist(s1, s2, inx, iny); if (wall[curi - 1][curj]) { d2 = -d2; s1 = inx; s2 = 1; } else { curi--; s1 = inx; s2 = 0; } continue; } } } // intersect with bottomline intersect = cross(line, bottomline); if (abs(intersect.z) > eps) // not parallel { inx = intersect.x / intersect.z; iny = intersect.y / intersect.z; if (dobottom && dist(inx, iny, s1, s2) > eps) { if (inx > 0 && inx < 1) // does intersect with bottomline { rem -= dist(s1, s2, inx, iny); if (wall[curi + 1][curj]) { d2 = -d2; s1 = inx; s2 = 0; } else { curi++; s1 = inx; s2 = 1; } continue; } } } } } } int main() { leftline = cross(makecoor(0, 0, 1), makecoor(0, 1, 1)); rightline = cross(makecoor(1, 0, 1), makecoor(1, 1, 1)); topline = cross(makecoor(0, 1, 1), makecoor(1, 1, 1)); bottomline = cross(makecoor(0, 0, 1), makecoor(1, 0, 1)); cin >> t; for (int casen = 0; casen < t; casen++) { init(); read(); solve(); write(casen + 1); } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
382a6d96a4cfd1671830e99ee038d7ad76816332
76afd4f03b6067db1459648fa95af72e437bf010
/OpenGLCourseApp/Shader.h
06d2a2d8508b084e3f7f73c0c79a0ac3f0d23a91
[]
no_license
V1aD1/OpenGLCourseApp
ab9d871d17b86480a44061be16bcb20690487def
dc49512ab29031d5cc5ee472fcdb04faad743143
refs/heads/master
2020-04-08T17:24:09.493545
2019-01-05T11:06:05
2019-01-05T11:06:05
159,565,071
0
0
null
null
null
null
UTF-8
C++
false
false
2,136
h
#pragma once #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include <GL/glew.h> #include "DirectionalLight.h" #include "PointLight.h" #include "SpotLight.h" #include "CommonValues.h" class Shader { public: Shader(); void CreateFromString(const char* vertexCode, const char* fragmentCode); void CreateFromFiles(const char* vertexLocation, const char* fragmentLocation); std::string ReadFile(const char* fileLocation); GLuint GetProjectionLocation(); GLuint GetModelLocation(); GLuint GetViewLocation(); GLuint GetAmbientIntensityLocation(); GLuint GetAmbientColorLocation(); GLuint GetDiffuseIntensityLocation(); GLuint GetDirectionLocation(); GLuint GetSpecularIntensityLocation(); GLuint GetShininessLocation(); GLuint GetEyePositionLocation(); void SetDirectionalLght(DirectionalLight* dLight); void SetPointLights(PointLight* pLight, unsigned int lightCount); void SetSpotLights(SpotLight* sLight, unsigned int lightCount); void UseShader(); void ClearShader(); ~Shader(); private: int pointLightCount; int spotLightCount; GLuint shaderID, uniformProjection, uniformModel, uniformView, uniformEyePosition, uniformSpecularIntensity, uniformShininess; struct { GLuint uniformColor; GLuint uniformAmbientIntensity; GLuint uniformDiffuseIntensity; GLuint uniformDirection; } uniformDirectionalLight; GLuint uniformPointLightCount; GLuint uniformSpotLightCount; struct { GLuint uniformColor; GLuint uniformAmbientIntensity; GLuint uniformDiffuseIntensity; GLuint uniformPosition; GLuint uniformConstant; GLuint uniformLinear; GLuint uniformExponent; } uniformPointLights[MAX_POINT_LIGHTS]; struct { GLuint uniformColor; GLuint uniformAmbientIntensity; GLuint uniformDiffuseIntensity; GLuint uniformPosition; GLuint uniformConstant; GLuint uniformLinear; GLuint uniformExponent; GLuint uniformDirection; GLuint uniformEdge; } uniformSpotLights[MAX_SPOT_LIGHTS]; void CompileShader(const char* vertexCode, const char* fragmentCode); void AddShader(GLuint theProgram, const char* shaderCode, GLenum shaderType); };
[ "vladfriends@yahoo.ca" ]
vladfriends@yahoo.ca
c07e1692e5afa546ad9c7329c75ac053b027d5a4
0f1510c57ef15588f8fb6e4c444b075d43340887
/remesher/src/argparser.h
c54e919c05d3a7c7755cc756279ab529cad69e62
[]
no_license
graphics-rpi/oasis_dependencies
c553ee678ad9ccccb8b223afcc6c9ed4851d43a8
384553df4842c1b2868db344c48b1d7e88bfe873
refs/heads/master
2021-10-08T13:23:00.351524
2018-12-12T16:37:53
2018-12-12T16:37:53
123,350,193
0
0
null
null
null
null
UTF-8
C++
false
false
22,513
h
#ifndef __ARG_PARSER_H__ #define __ARG_PARSER_H__ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <fstream> #include <cassert> #include <glui.h> #include "mtrand.h" #include "OpenGLProjector.h" #include "vectors.h" #include "utils.h" class ArgParser { public: ArgParser() { DefaultValues(); } ArgParser(const std::vector<std::string> &command_line_args) { DefaultValues(); for (unsigned int i = 1; i < command_line_args.size(); i++) { // filenames if (command_line_args[i] == "-input" || command_line_args[i] == "-i") { i++; assert (i < command_line_args.size()); load_file = GLUI_String(command_line_args[i]); } else if (command_line_args[i] == "-flip_y_up") { load_flip_y_up = true; } else if (command_line_args[i] == "-no_remesh") { do_remesh = false; } else if (command_line_args[i] == "-test_color_calibration") { test_color_calibration = true; } else if (command_line_args[i] == "-puzzle_mode") { puzzle_mode = true; i++; assert (i < command_line_args.size()); puzzle_output_file = GLUI_String(command_line_args[i]); do_remesh = false; walls_create_arrangement = false; } else if (command_line_args[i] == "-graph_visualization_mode") { graph_visualization_mode = true; } else if (command_line_args[i] == "-single_projector_blending") { single_projector_blending = true; } else if (command_line_args[i] == "-shrink_projection_surfaces") { i++; assert (i < command_line_args.size()); shrink_projection_surfaces = atof(command_line_args[i].c_str()); // in meters } else if (command_line_args[i] == "-army_tweening") { triangle_textures_and_normals = true; do_remesh = true; gap_under_walls = false; //true; walls_create_arrangement = false; save_as_lsvmtl = false; army = true; TWEAK_WALLS = false; } else if (command_line_args[i] == "-army") { army = true; make_arrangement_images = true; camera_image_file = "army.ppm"; TWEAK_WALLS = false; } else if (command_line_args[i] == "-tweening") { triangle_textures_and_normals = true; do_remesh = false; //..true; //false; gap_under_walls = false; //true; walls_create_arrangement = false; save_as_lsvmtl = false; // output_floor_polys = true; } else if (command_line_args[i] == "-colors_file") { i++; assert (i < command_line_args.size()); colors_file = std::string(command_line_args[i]); } else if (command_line_args[i] == "-fillin_ceiling_only") { fillin_ceiling_only = true; } else if (command_line_args[i] == "-output" || command_line_args[i] == "-o") { i++; assert (i < command_line_args.size()); save_file = GLUI_String(command_line_args[i]); // } else if (command_line_args[i] == "-quads") || // command_line_args[i] == "-q")) { //save_as_quads = 1; } else if (command_line_args[i] == "-blending_subdivision") { i++; assert (i < command_line_args.size()); blending_subdivision = atof(command_line_args[i].c_str()); } else if (command_line_args[i] == "-no_blending_hack") { no_blending_hack = true; } else if (command_line_args[i] == "-blending") { i++; assert (i < command_line_args.size()); blending_file = GLUI_String(command_line_args[i]); } else if (command_line_args[i] == "-output_corners_file") { i++; assert (i < command_line_args.size()); output_corners_file = command_line_args[i]; } else if (command_line_args[i] == "-5_sided_cornell_emissive_wall") { //output_corners_file")) { five_sided_cornell_emissive_wall = true; } else if (command_line_args[i] == "-worst_angle") { i++; assert (i < command_line_args.size()); worst_angle_threshold = atof(command_line_args[i].c_str()); } else if (command_line_args[i] == "-extend_walls") { extend_walls = true; } else if (command_line_args[i] == "-physical_diffuse") { i++; assert (i < command_line_args.size()); physical_diffuse = command_line_args[i]; } else if (command_line_args[i] == "-virtual_scene") { i++; assert (i < command_line_args.size()); virtual_scene = command_line_args[i]; } else if (command_line_args[i] == "-normal_tolerance") { i++; assert (i < command_line_args.size()); remesh_normal_tolerance = atof(command_line_args[i].c_str()); } else if (command_line_args[i] == "-target_num_triangles" || command_line_args[i] == "-triangles" || command_line_args[i] == "-t") { i++; assert (i < command_line_args.size()); desired_tri_count = atoi(command_line_args[i].c_str()); } else if (command_line_args[i] == "-target_num_patches" || command_line_args[i] == "-patches") { i++; assert (i < command_line_args.size()); desired_patch_count = atoi(command_line_args[i].c_str()); initialize_patches = true; render_vis_mode = 1; render_EXTRA_elements = 0; ground_plane = 0; render_cluster_boundaries = 0; render_cull_ceiling = 0; } else if (command_line_args[i] == "-auto_sensors" ) { auto_sensor_placement = true; } else if (command_line_args[i] == "-noglui") { glui = false; } else if (command_line_args[i] == "-create_surface_cameras") { create_surface_cameras = true; } else if (command_line_args[i] == "-surface_cameras_fixed_size") { i++; assert (i < command_line_args.size()); surface_cameras_fixed_size = atoi(command_line_args[i].c_str()); assert (surface_cameras_fixed_size > 0); } else if (command_line_args[i] == "-floor_cameras_tiled") { i++; assert (i < command_line_args.size()); floor_cameras_tiled = atoi(command_line_args[i].c_str()); assert (floor_cameras_tiled > 0); } else if (command_line_args[i] == "-offline") { offline = 1; } else if (command_line_args[i] == "-offline_viewer") { offline_viewer = 1; } /* else if (command_line_args[i] == "-enclosed")) { i++; assert (i < command_line_args.size()); enclosed_threshhold = atof(command_line_args[i].c_str()); } */ else if (command_line_args[i] == "-non_zero_interior_area") { non_zero_interior_area = true; } /* else if (command_line_args[i] == "-not_closed")) { closed_model = 0; } */ else if (command_line_args[i] == "-fixed_seed") { i++; assert (i < command_line_args.size()); int seed = atoi(command_line_args[i].c_str()); mtrand = new MTRand((unsigned long)seed); } // window else if (command_line_args[i] == "-width") { i++; assert (i < command_line_args.size()); width2 = atoi(command_line_args[i].c_str()); } else if (command_line_args[i] == "-height") { i++; assert (i < command_line_args.size()); height2 = atoi(command_line_args[i].c_str()); } else if (command_line_args[i] == "-geometry") { i++; assert (i < command_line_args.size()); width2 = atoi(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); height2 = atoi(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); pos_x = atoi(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); pos_y = atoi(command_line_args[i].c_str()); } else if (command_line_args[i] == "-p") { i++; int count = atoi(command_line_args[i].c_str()); for (int j = 0; j < count; j++) { i++; assert (i < command_line_args.size()); projectors.push_back(OpenGLProjector(command_line_args[i].c_str())); projector_names.push_back(command_line_args[i]); //width = projector->getWidth(); //height = projector->getHeight(); } } else if (command_line_args[i] == "-projector_center_override") { assert (projectors.size() > 0); i++; assert (i < command_line_args.size()); std::string glcamfile = command_line_args[i]; double x,y,z; i++; assert (i < command_line_args.size()); x = atof(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); y = atof(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); z = atof(command_line_args[i].c_str()); bool found = false; for (unsigned int j = 0; j < projectors.size(); j++) { if (projector_names[j] == glcamfile) { found = true; std::cout << "FOUND PROJECTOR TO OVERRIDE " << glcamfile << std::endl; projectors[j].setVec3fCenterReplacement(Vec3f(x,y,z)); } } assert (found == true); } else if (command_line_args[i] == "-camera" || command_line_args[i] == "-c") { i++; assert (i < command_line_args.size()); glcam_camera = new OpenGLProjector(command_line_args[i].c_str()); } else if (command_line_args[i] == "-no_edges") { render_mode = 6; // render_vis_mode = 13; // blending weights render_wall_chains = 0; render_walls = 0; render_triangle_edges = 0; render_cluster_boundaries = 0; render_non_manifold_edges = 0; render_crease_edges = 0; render_zero_area_triangles = 0; render_bad_normal_triangles = 0; render_visibility_planes = 0; render_bad_neighbor_triangles = 0; ground_plane = 1; } else if (command_line_args[i] == "-make_arrangement_images") { i++; make_arrangement_images = true; assert (i < command_line_args.size()); camera_image_file = std::string(command_line_args[i]); } else if (command_line_args[i] == "-make_all_arrangement_images") { i++; make_arrangement_images = true; make_all_arrangement_images = true; assert (i < command_line_args.size()); camera_image_file = std::string(command_line_args[i]); } else if (command_line_args[i] == "-extra_length_multiplier") { i++; assert (i < command_line_args.size()); extra_length_multiplier = atof(command_line_args[i].c_str()); } else if (command_line_args[i] == "-cut_completely") { CUT_COMPLETELY = true; } else if (command_line_args[i] == "-num_curve_segments") { i++; assert (i < command_line_args.size()); num_curve_segments = atoi(command_line_args[i].c_str()); assert (num_curve_segments >= 1); } else if (command_line_args[i] == "-num_column_faces") { i++; assert (i < command_line_args.size()); num_column_faces = atoi(command_line_args[i].c_str()); assert (num_column_faces >= 4); if (num_column_faces % 2 == 1) num_column_faces++; } else if (command_line_args[i] == "-run_continuously") { run_continuously = true; } else if (command_line_args[i] == "-stop_after") { i++; assert (i < command_line_args.size()); stop_after = atoi(command_line_args[i].c_str()); } else if (command_line_args[i] == "-increment_filename") { increment_filename = true; } else if (command_line_args[i] == "-num_planes_to_cut") { i++; assert (i < command_line_args.size()); num_planes_to_cut = atoi(command_line_args[i].c_str()); assert (num_planes_to_cut >= 0); } else if (command_line_args[i] == "-walls_rotate_translate") { i++; assert (i < command_line_args.size()); walls_rotate_angle = atof(command_line_args[i].c_str())*M_PI/180.0; // argument in degrees! i++; assert (i < command_line_args.size()); walls_translate_x = atof(command_line_args[i].c_str()); i++; assert (i < command_line_args.size()); walls_translate_z = atof(command_line_args[i].c_str()); } else if (command_line_args[i] == "-floor_plan_walls_vis") { floor_plan_walls_vis = true; } else if (command_line_args[i] == "-use_locked_output_directory") { i++; assert (i < command_line_args.size()); locked_directory = command_line_args[i]; } else if (command_line_args[i] == "-all_walls_8_inches") { all_walls_8_inches = true; /* } else if (command_line_args[i] == "-make_correspondences_file")) { make_correspondences_file = true; i++; assert (i < command_line_args.size()); correspondences_a_file = command_line_args[i]; i++; assert (i < command_line_args.size()); correspondences_b_file = command_line_args[i]; i++; assert (i < command_line_args.size()); correspondences_out_file = command_line_args[i]; */ } else if (command_line_args[i] == "-level_of_detail_and_correspondences") { level_of_detail_and_correspondences = true; i++; assert (i < command_line_args.size()); int num_levels = atoi(command_line_args[i].c_str()); for (int j = 0; j < num_levels; j++) { i++; assert (i < command_line_args.size()); level_of_detail_desired_tri_count.push_back(atoi(command_line_args[i].c_str())); } } else if (command_line_args[i] == "-verbose") { verbose = true; } else if (command_line_args[i] == "-quiet") { verbose = false; } else { printf ("whoops error with command line argument %d: '%s'\n",i,command_line_args[i].c_str()); assert(0); exit(0); } } // std::cout<<"AP after load:"<<walls_create_arrangement<<std::endl; //cout << " ewm = " << extra_length_multiplier << endl; if (verbose) { output = &std::cout; } else { output = new std::ofstream("/dev/null"); } } void DefaultValues() { //std::cout<<"in default values"<<std::endl; triangle_textures_and_normals = false; gap_under_walls = false; //output_floor_polys = false; do_remesh = true; test_color_calibration = false; puzzle_mode = false; graph_visualization_mode = false; single_projector_blending = false; shrink_projection_surfaces = 0; no_blending_hack = false; //blending_subdivision = 20; // a hack.. //blending_subdivision = 30; // a hack.. blending_subdivision = 10; // a hack.. camera_image_file = ""; make_arrangement_images = false; make_all_arrangement_images = false; physical_diffuse = "default"; virtual_scene = "default"; create_surface_cameras = false; surface_cameras_fixed_size = -1; floor_cameras_tiled = 1; which_projector = 0; five_sided_cornell_emissive_wall = false; fillin_ceiling_only = false; output_corners_file = ""; worst_angle_threshold = -1; extend_walls = false; remesh_normal_tolerance = 0.99; // remesh_normal_tolerance = 0.98; //remesh_normal_tolerance = 0.90; cut_normal_tolerance = 1; //0.999; desired_tri_count = 1000; desired_patch_count = 100; preserve_volume = 1; equal_edge_and_area = 0; initialize_patches = false; auto_sensor_placement = true; // rendering rerender_scene_geometry = 1; rerender_select_geometry = 1; render_mode = 1; // triangles render_vis_mode = 0; // diffuse material render_which_projector = 0; render_flipped_edges = 0; render_short_edges = 0; render_concave_angles = 0; render_faux_true = 0; render_problems_as_clusters = 0; render_problems_as_planes = 0; render_walls = 0; render_wall_chains = 0; render_PROJECTION_elements = 1; render_FILLIN_elements = 1; render_EXTRA_elements = 1; render_normals = 0; render_cracks = 0; render_triangle_edges = 1; render_cluster_boundaries = 1; render_non_manifold_edges = 1; render_crease_edges = 1; render_zero_area_triangles = 1; render_bad_normal_triangles = 1; render_bad_neighbor_triangles = 1; render_cull_back_facing = 0; render_cull_ceiling = 1; render_visibility_planes = 0; render_cluster_seeds = 0; render_voronoi_edges = 0; render_triangle_vertices = 0; render_voronoi_centers = 0; render_inner_hull = 0; render_triangle_hanging_chain = 0; render_voronoi_hanging_chain = 0; render_triangle_hanging_surface = 0; render_voronoi_hanging_surface = 0; transparency = 0; ground_plane = 1; white_background = 1; two_sided_surface = 1; ground_height = 0.1; sphere_tess_horiz = 30; sphere_tess_vert = 20; non_zero_interior_area = false; //closed_model = 1; // window size width2 = 800; height2 = 800; pos_x = 600; pos_y = 0; gl_lighting = 1; clip_x = 0; clip_y = 0; clip_z = 1; min_clip = -1; max_clip = 1; clip_enabled = 0; glui = true; offline = 0; offline_viewer = 0; //enclosed_threshhold = 0.65; glcam_camera = NULL; use_glcam_camera = true; extra_length_multiplier = 4.0; load_flip_triangles = 0; load_flip_y_up = 0; model_units = "meters"; army = false; save_as_lsvmtl = true; // true = save as .lsvmtl, false = save as .mtl CUT_COMPLETELY = false; num_curve_segments = 7; num_column_faces = 10; run_continuously = false; stop_after = -1; increment_filename = false; num_planes_to_cut = -1; walls_rotate_angle = 0; walls_translate_x = 0; walls_translate_z = 0; floor_plan_walls_vis = false; locked_directory = ""; all_walls_8_inches = false; walls_create_arrangement = true; point_sampled_enclosure = 0; //false; mtrand = new MTRand(); // random seed!!! (use -fixed_seed otherwise... ) SPLIT_BASED_ON_ENCLOSURE_HISTOGRAM = true; REMESH_BEFORE_ENCLOSURE_SPLIT = true; TWEAK_WALLS = true; PARALLEL_ANGLE_THRESHHOLD = (5.0 * M_PI/180.0); // 5 degrees PERPENDICULAR_ANGLE_THRESHHOLD = (5.0 * M_PI/180.0); // 5 degrees WALL_THICKNESS = (3/8.0 * INCH_IN_METERS); ADJUSTABLE_D_OFFSET = (0.5 * INCH_IN_METERS * 3); //ADJUSTABLE_D_OFFSET = (1.5 * INCH_IN_METERS * 3); //make_correspondences_file = false; level_of_detail_and_correspondences = false; verbose = false; //true; } // return a random vector with each component from -1 -> 1 Vec3f RandomVector() { double x = (*mtrand)() * 2 - 1; double y = (*mtrand)() * 2 - 1; double z = (*mtrand)() * 2 - 1; return Vec3f(x,y,z); } Vec3f RandomColor() { double x,y,z; while (1) { x = (*mtrand)(); if (x<0) x=0; y = (*mtrand)(); if (y<0) y=0; z = (*mtrand)(); if (z<0) z=0; if (x > 0.2 || y > 0.2 || z > 0.2) return Vec3f(x,y,z); } } // ============== // REPRESENTATION // all public! (no accessors) // filenames GLUI_String load_file; std::string colors_file; GLUI_String materials_file; GLUI_String save_file; bool triangle_textures_and_normals; bool gap_under_walls; bool do_remesh; bool test_color_calibration; bool puzzle_mode; bool graph_visualization_mode; bool single_projector_blending; double shrink_projection_surfaces; std::string puzzle_output_file; GLUI_String blending_file; double blending_subdivision; bool no_blending_hack; GLUI_String save_density_file; GLUI_String save_voronoi_surface_file; GLUI_String save_full_voronoi_file; GLUI_String save_compressed_voronoi_file; GLUI_String save_gaudi_triangles_file; GLUI_String save_gaudi_voronoi_file; GLUI_String save_tiles_file; // fabrication int load_flip_triangles; int load_flip_y_up; std::string model_units; // "inches", "meters", "feet" std::string camera_image_file; bool make_arrangement_images; bool make_all_arrangement_images; bool five_sided_cornell_emissive_wall; bool fillin_ceiling_only; std::string output_corners_file; double worst_angle_threshold; bool extend_walls; // remeshing & painting float remesh_normal_tolerance; float cut_normal_tolerance; int desired_tri_count; int desired_patch_count; int preserve_volume; int equal_edge_and_area; bool initialize_patches; bool auto_sensor_placement; // rendering int rerender_scene_geometry; int rerender_select_geometry; int render_mode; int render_vis_mode; int render_which_projector; int render_flipped_edges; int render_short_edges; int render_concave_angles; int render_faux_true; int render_problems_as_clusters; int render_problems_as_planes; int render_walls; int render_wall_chains; int render_PROJECTION_elements; int render_FILLIN_elements; int render_EXTRA_elements; int render_normals; int render_cracks; int render_triangle_edges; int render_voronoi_edges; int render_cluster_boundaries; int render_non_manifold_edges; int render_crease_edges; int render_zero_area_triangles; int render_bad_normal_triangles; int render_bad_neighbor_triangles; int render_cull_back_facing; int render_cull_ceiling; int render_visibility_planes; int render_cluster_seeds; int render_triangle_vertices; int render_voronoi_centers; int render_inner_hull; int render_triangle_hanging_chain; int render_voronoi_hanging_chain; int render_triangle_hanging_surface; int render_voronoi_hanging_surface; int transparency; int ground_plane; int white_background; int two_sided_surface; float ground_height; bool non_zero_interior_area; //int closed_model; // window size int width2; int height2; int pos_x; int pos_y; int gl_lighting; float clip_x; float clip_y; float clip_z; float min_clip; float max_clip; int clip_enabled; int sphere_tess_horiz; int sphere_tess_vert; bool glui; int offline; int offline_viewer; //float enclosed_threshhold; OpenGLProjector *glcam_camera; bool use_glcam_camera; std::vector<OpenGLProjector> projectors; double extra_length_multiplier; std::string physical_diffuse; std::string virtual_scene; bool create_surface_cameras; int surface_cameras_fixed_size; int floor_cameras_tiled; int which_projector; std::vector<std::string> projector_names; //bool output_floor_polys; bool army; bool save_as_lsvmtl; // true = save as .lsvmtl, false = save as .mtl MTRand *mtrand; bool CUT_COMPLETELY; int num_curve_segments; int num_column_faces; bool walls_create_arrangement; int point_sampled_enclosure; bool run_continuously; int stop_after; bool increment_filename; int num_planes_to_cut; double walls_rotate_angle; double walls_translate_x; double walls_translate_z; bool floor_plan_walls_vis; std::string locked_directory; bool all_walls_8_inches; bool SPLIT_BASED_ON_ENCLOSURE_HISTOGRAM; bool REMESH_BEFORE_ENCLOSURE_SPLIT; bool TWEAK_WALLS; double PARALLEL_ANGLE_THRESHHOLD; double PERPENDICULAR_ANGLE_THRESHHOLD; double WALL_THICKNESS; double ADJUSTABLE_D_OFFSET; // bool make_correspondences_file; //std::string correspondences_a_file; //std::string correspondences_b_file; //std::string correspondences_out_file; bool level_of_detail_and_correspondences; std::vector<int> level_of_detail_desired_tri_count; bool verbose; std::ostream *output; // ======================================================== }; #endif
[ "sensen.chen7@gmail.com" ]
sensen.chen7@gmail.com
a8cbf6d6ee407bf25023c108f04880a5b557c48e
5a119bbe5544c4605f80acab39da9fdce05140b6
/Test_MetaProgramming/main.cpp
9acd38e5f13bd3e92308c503eb3511423ddaee19
[]
no_license
alevya/Test_MetaProgramming
55dfe9a5fd1a67a02a28fe4f27b9acd8f6b08b34
1dd61bb69dbe6b616007902900f5d1428ed24d1b
refs/heads/master
2021-02-17T19:14:31.330076
2020-03-05T13:33:44
2020-03-05T13:33:44
245,120,776
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> #include "template.h" using namespace std; int main() { unsigned const n = 5; // cout << "Input unsigner number:" << endl; // cin >> n; const unsigned result = factorial<n>::value; cout << n << "! = " << result << endl; return 0; }
[ "aleksei.viaznikov@monitoringcnc.ru" ]
aleksei.viaznikov@monitoringcnc.ru
467cf431b3f0cec171055bf4e3643be8407f7ccd
64eb45498720afa68aaeaf87a217e5ab8799060e
/src/algorithms/cpp/Divide_Two_Integers.cpp
ec0e53ac3fafe038f0cb82218ec9e2eac63fb2b5
[]
no_license
brickgao/leetcode
822be49c19b999684f60052f76faa606c0ab48c2
c55892c27abcd6f23a86a76e4c42351695470459
refs/heads/master
2021-01-21T04:54:22.532153
2016-06-01T04:16:24
2016-06-01T04:16:24
33,587,350
1
2
null
null
null
null
UTF-8
C++
false
false
949
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> #include <stack> #include <map> #include <set> using namespace std; #define out(v) cerr << #v << ": " << (v) << endl #define SZ(v) ((int)(v).size()) const int maxint = -1u>>1; template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;} template <class T> bool get_min(T& a, const T &b) {return b < a? a = b, 1: 0;} const int MAX_INT = 2147483647; class Solution { public: int divide(long long dividend, long long divisor) { if (divisor == 0) return MAX_INT; long long tmp = dividend / divisor; if (tmp >= - MAX_INT - 1 && tmp <= MAX_INT) { return tmp; } else { return MAX_INT; } } }; int main() { Solution solution = Solution(); cout << solution.divide(-2147483648, -1) << endl; return 0; }
[ "brickgao@gmail.com" ]
brickgao@gmail.com
8ee9e74d5444bd6d758e5cbe898a4d4f5f29e3fa
e63e4d24817724cbb7e5f49543779d351aee0b49
/test/Socket.cpp
2f45dc1f9e0bd258f847519cfc7cf910dfe134d1
[]
no_license
CasperBHansen/DN
4b14b9aa0c05b69b9bf7e698c9de0f78dfd18e81
1262cd66aaacaebdd8f65ddf24c70a9bb59a0a7e
refs/heads/master
2020-12-25T22:38:02.381377
2015-05-27T07:20:09
2015-05-27T07:20:09
17,723,189
0
0
null
null
null
null
UTF-8
C++
false
false
2,650
cpp
/* * Datanet * * Socket.cpp * */ #include "Socket.h" #include <iostream> #include <memory.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> Socket::Socket() : sock(-1) { memset (&addr, 0, sizeof(addr)); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) throw SocketException("Could not create server socket.");; int on = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on) ) == -1) throw SocketException("Could not create server socket."); } Socket::~Socket() { if (sock != -1) ::close(sock); } bool Socket::bind(const int port) { if (sock == -1) return false; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); return (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != -1); } bool Socket::listen() const { if (sock == -1) return false; return (::listen(sock, MAXCONNECTIONS) != -1); } bool Socket::accept(Socket& new_socket) const { int addr_length = sizeof(addr); new_socket.sock = ::accept(sock, (sockaddr *)&addr, (socklen_t *)&addr_length); return (new_socket.sock > 0); } bool Socket::send(const std::string str) const { int status = ::send(sock, str.c_str(), str.size(), MSG_NOSIGNAL); return (status != -1); } int Socket::receive(std::string& str) const { char buffer[MAXRECV + 1]; str = ""; memset(buffer, 0, MAXRECV + 1); int status = ::recv(sock, buffer, MAXRECV, 0); if (status == -1) { std::cout << "status == -1 errno == " << errno << " in Socket::recv\n"; return 0; } if (status != 0) str = buffer; return status; } bool Socket::connect(const std::string host, const int port) { if (sock == -1) return false; addr.sin_family = AF_INET; addr.sin_port = htons(port); int status = inet_pton(AF_INET, host.c_str(), &addr.sin_addr); if (errno == EAFNOSUPPORT) return false; status = ::connect(sock, (sockaddr *)&addr, sizeof(addr)); return !status; } void Socket::set_non_blocking(const bool b) { int opts = fcntl(sock, F_GETFL); if (opts < 0) return; opts = b ? (opts | O_NONBLOCK) : (opts & ~O_NONBLOCK); fcntl(sock, F_SETFL, opts); } const Socket& Socket::operator<<(const std::string& str) const { if (!send(str)) throw SocketException("Could not write to socket."); return (* this); } const Socket& Socket::operator>>(std::string& str) const { if (!receive(str)) throw SocketException("Could not read from socket."); return (* this); }
[ "fvx507@alumni.ku.dk" ]
fvx507@alumni.ku.dk
1ba2b55fd8c2ee56281fe1c91ecdb61a126d6daf
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/godot/2017/12/global_constants.cpp
b390590cf21c8b0f0bb70493823da8c17c0fae01
[ "MIT" ]
permissive
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
27,211
cpp
/*************************************************************************/ /* global_constants.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software") to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "global_constants.h" #include "object.h" #include "os/input_event.h" #include "os/keyboard.h" #include "variant.h" struct _GlobalConstant { #ifdef DEBUG_METHODS_ENABLED StringName enum_name; #endif const char *name; int value; _GlobalConstant() {} #ifdef DEBUG_METHODS_ENABLED _GlobalConstant(const StringName &p_enum_name, const char *p_name, int p_value) : enum_name(p_enum_name), name(p_name), value(p_value) { } #else _GlobalConstant(const char *p_name, int p_value) : name(p_name), value(p_value) { } #endif }; static Vector<_GlobalConstant> _global_constants; #ifdef DEBUG_METHODS_ENABLED #define BIND_GLOBAL_CONSTANT(m_constant) \ _global_constants.push_back(_GlobalConstant(StringName(), #m_constant, m_constant)); #define BIND_GLOBAL_ENUM_CONSTANT(m_constant) \ _global_constants.push_back(_GlobalConstant(__constant_get_enum_name(m_constant, #m_constant), #m_constant, m_constant)); #define BIND_GLOBAL_ENUM_CONSTANT_CUSTOM(m_custom_name, m_constant) \ _global_constants.push_back(_GlobalConstant(__constant_get_enum_name(m_constant, #m_constant), m_custom_name, m_constant)); #else #define BIND_GLOBAL_CONSTANT(m_constant) \ _global_constants.push_back(_GlobalConstant(#m_constant, m_constant)); #define BIND_GLOBAL_ENUM_CONSTANT(m_constant) \ _global_constants.push_back(_GlobalConstant(#m_constant, m_constant)); #define BIND_GLOBAL_ENUM_CONSTANT_CUSTOM(m_custom_name, m_constant) \ _global_constants.push_back(_GlobalConstant(m_custom_name, m_constant)); #endif VARIANT_ENUM_CAST(KeyList); VARIANT_ENUM_CAST(KeyModifierMask); VARIANT_ENUM_CAST(ButtonList); VARIANT_ENUM_CAST(JoystickList); void register_global_constants() { //{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace BIND_GLOBAL_ENUM_CONSTANT(MARGIN_LEFT); BIND_GLOBAL_ENUM_CONSTANT(MARGIN_TOP); BIND_GLOBAL_ENUM_CONSTANT(MARGIN_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(MARGIN_BOTTOM); BIND_GLOBAL_ENUM_CONSTANT(CORNER_TOP_LEFT); BIND_GLOBAL_ENUM_CONSTANT(CORNER_TOP_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(CORNER_BOTTOM_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(CORNER_BOTTOM_LEFT); BIND_GLOBAL_ENUM_CONSTANT(VERTICAL); BIND_GLOBAL_ENUM_CONSTANT(HORIZONTAL); BIND_GLOBAL_ENUM_CONSTANT(HALIGN_LEFT); BIND_GLOBAL_ENUM_CONSTANT(HALIGN_CENTER); BIND_GLOBAL_ENUM_CONSTANT(HALIGN_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(VALIGN_TOP); BIND_GLOBAL_ENUM_CONSTANT(VALIGN_CENTER); BIND_GLOBAL_ENUM_CONSTANT(VALIGN_BOTTOM); // hueg list of keys BIND_GLOBAL_CONSTANT(SPKEY); BIND_GLOBAL_ENUM_CONSTANT(KEY_ESCAPE); BIND_GLOBAL_ENUM_CONSTANT(KEY_TAB); BIND_GLOBAL_ENUM_CONSTANT(KEY_BACKTAB); BIND_GLOBAL_ENUM_CONSTANT(KEY_BACKSPACE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ENTER); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_ENTER); BIND_GLOBAL_ENUM_CONSTANT(KEY_INSERT); BIND_GLOBAL_ENUM_CONSTANT(KEY_DELETE); BIND_GLOBAL_ENUM_CONSTANT(KEY_PAUSE); BIND_GLOBAL_ENUM_CONSTANT(KEY_PRINT); BIND_GLOBAL_ENUM_CONSTANT(KEY_SYSREQ); BIND_GLOBAL_ENUM_CONSTANT(KEY_CLEAR); BIND_GLOBAL_ENUM_CONSTANT(KEY_HOME); BIND_GLOBAL_ENUM_CONSTANT(KEY_END); BIND_GLOBAL_ENUM_CONSTANT(KEY_LEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_UP); BIND_GLOBAL_ENUM_CONSTANT(KEY_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_DOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_PAGEUP); BIND_GLOBAL_ENUM_CONSTANT(KEY_PAGEDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_SHIFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_CONTROL); BIND_GLOBAL_ENUM_CONSTANT(KEY_META); BIND_GLOBAL_ENUM_CONSTANT(KEY_ALT); BIND_GLOBAL_ENUM_CONSTANT(KEY_CAPSLOCK); BIND_GLOBAL_ENUM_CONSTANT(KEY_NUMLOCK); BIND_GLOBAL_ENUM_CONSTANT(KEY_SCROLLLOCK); BIND_GLOBAL_ENUM_CONSTANT(KEY_F1); BIND_GLOBAL_ENUM_CONSTANT(KEY_F2); BIND_GLOBAL_ENUM_CONSTANT(KEY_F3); BIND_GLOBAL_ENUM_CONSTANT(KEY_F4); BIND_GLOBAL_ENUM_CONSTANT(KEY_F5); BIND_GLOBAL_ENUM_CONSTANT(KEY_F6); BIND_GLOBAL_ENUM_CONSTANT(KEY_F7); BIND_GLOBAL_ENUM_CONSTANT(KEY_F8); BIND_GLOBAL_ENUM_CONSTANT(KEY_F9); BIND_GLOBAL_ENUM_CONSTANT(KEY_F10); BIND_GLOBAL_ENUM_CONSTANT(KEY_F11); BIND_GLOBAL_ENUM_CONSTANT(KEY_F12); BIND_GLOBAL_ENUM_CONSTANT(KEY_F13); BIND_GLOBAL_ENUM_CONSTANT(KEY_F14); BIND_GLOBAL_ENUM_CONSTANT(KEY_F15); BIND_GLOBAL_ENUM_CONSTANT(KEY_F16); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_MULTIPLY); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_DIVIDE); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_SUBTRACT); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_PERIOD); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_ADD); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_0); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_1); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_2); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_3); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_4); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_5); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_6); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_7); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_8); BIND_GLOBAL_ENUM_CONSTANT(KEY_KP_9); BIND_GLOBAL_ENUM_CONSTANT(KEY_SUPER_L); BIND_GLOBAL_ENUM_CONSTANT(KEY_SUPER_R); BIND_GLOBAL_ENUM_CONSTANT(KEY_MENU); BIND_GLOBAL_ENUM_CONSTANT(KEY_HYPER_L); BIND_GLOBAL_ENUM_CONSTANT(KEY_HYPER_R); BIND_GLOBAL_ENUM_CONSTANT(KEY_HELP); BIND_GLOBAL_ENUM_CONSTANT(KEY_DIRECTION_L); BIND_GLOBAL_ENUM_CONSTANT(KEY_DIRECTION_R); BIND_GLOBAL_ENUM_CONSTANT(KEY_BACK); BIND_GLOBAL_ENUM_CONSTANT(KEY_FORWARD); BIND_GLOBAL_ENUM_CONSTANT(KEY_STOP); BIND_GLOBAL_ENUM_CONSTANT(KEY_REFRESH); BIND_GLOBAL_ENUM_CONSTANT(KEY_VOLUMEDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_VOLUMEMUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_VOLUMEUP); BIND_GLOBAL_ENUM_CONSTANT(KEY_BASSBOOST); BIND_GLOBAL_ENUM_CONSTANT(KEY_BASSUP); BIND_GLOBAL_ENUM_CONSTANT(KEY_BASSDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_TREBLEUP); BIND_GLOBAL_ENUM_CONSTANT(KEY_TREBLEDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_MEDIAPLAY); BIND_GLOBAL_ENUM_CONSTANT(KEY_MEDIASTOP); BIND_GLOBAL_ENUM_CONSTANT(KEY_MEDIAPREVIOUS); BIND_GLOBAL_ENUM_CONSTANT(KEY_MEDIANEXT); BIND_GLOBAL_ENUM_CONSTANT(KEY_MEDIARECORD); BIND_GLOBAL_ENUM_CONSTANT(KEY_HOMEPAGE); BIND_GLOBAL_ENUM_CONSTANT(KEY_FAVORITES); BIND_GLOBAL_ENUM_CONSTANT(KEY_SEARCH); BIND_GLOBAL_ENUM_CONSTANT(KEY_STANDBY); BIND_GLOBAL_ENUM_CONSTANT(KEY_OPENURL); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHMAIL); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHMEDIA); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH0); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH1); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH2); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH3); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH4); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH5); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH6); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH7); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH8); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCH9); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHA); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHB); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHC); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHD); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHE); BIND_GLOBAL_ENUM_CONSTANT(KEY_LAUNCHF); BIND_GLOBAL_ENUM_CONSTANT(KEY_UNKNOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_SPACE); BIND_GLOBAL_ENUM_CONSTANT(KEY_EXCLAM); BIND_GLOBAL_ENUM_CONSTANT(KEY_QUOTEDBL); BIND_GLOBAL_ENUM_CONSTANT(KEY_NUMBERSIGN); BIND_GLOBAL_ENUM_CONSTANT(KEY_DOLLAR); BIND_GLOBAL_ENUM_CONSTANT(KEY_PERCENT); BIND_GLOBAL_ENUM_CONSTANT(KEY_AMPERSAND); BIND_GLOBAL_ENUM_CONSTANT(KEY_APOSTROPHE); BIND_GLOBAL_ENUM_CONSTANT(KEY_PARENLEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_PARENRIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_ASTERISK); BIND_GLOBAL_ENUM_CONSTANT(KEY_PLUS); BIND_GLOBAL_ENUM_CONSTANT(KEY_COMMA); BIND_GLOBAL_ENUM_CONSTANT(KEY_MINUS); BIND_GLOBAL_ENUM_CONSTANT(KEY_PERIOD); BIND_GLOBAL_ENUM_CONSTANT(KEY_SLASH); BIND_GLOBAL_ENUM_CONSTANT(KEY_0); BIND_GLOBAL_ENUM_CONSTANT(KEY_1); BIND_GLOBAL_ENUM_CONSTANT(KEY_2); BIND_GLOBAL_ENUM_CONSTANT(KEY_3); BIND_GLOBAL_ENUM_CONSTANT(KEY_4); BIND_GLOBAL_ENUM_CONSTANT(KEY_5); BIND_GLOBAL_ENUM_CONSTANT(KEY_6); BIND_GLOBAL_ENUM_CONSTANT(KEY_7); BIND_GLOBAL_ENUM_CONSTANT(KEY_8); BIND_GLOBAL_ENUM_CONSTANT(KEY_9); BIND_GLOBAL_ENUM_CONSTANT(KEY_COLON); BIND_GLOBAL_ENUM_CONSTANT(KEY_SEMICOLON); BIND_GLOBAL_ENUM_CONSTANT(KEY_LESS); BIND_GLOBAL_ENUM_CONSTANT(KEY_EQUAL); BIND_GLOBAL_ENUM_CONSTANT(KEY_GREATER); BIND_GLOBAL_ENUM_CONSTANT(KEY_QUESTION); BIND_GLOBAL_ENUM_CONSTANT(KEY_AT); BIND_GLOBAL_ENUM_CONSTANT(KEY_A); BIND_GLOBAL_ENUM_CONSTANT(KEY_B); BIND_GLOBAL_ENUM_CONSTANT(KEY_C); BIND_GLOBAL_ENUM_CONSTANT(KEY_D); BIND_GLOBAL_ENUM_CONSTANT(KEY_E); BIND_GLOBAL_ENUM_CONSTANT(KEY_F); BIND_GLOBAL_ENUM_CONSTANT(KEY_G); BIND_GLOBAL_ENUM_CONSTANT(KEY_H); BIND_GLOBAL_ENUM_CONSTANT(KEY_I); BIND_GLOBAL_ENUM_CONSTANT(KEY_J); BIND_GLOBAL_ENUM_CONSTANT(KEY_K); BIND_GLOBAL_ENUM_CONSTANT(KEY_L); BIND_GLOBAL_ENUM_CONSTANT(KEY_M); BIND_GLOBAL_ENUM_CONSTANT(KEY_N); BIND_GLOBAL_ENUM_CONSTANT(KEY_O); BIND_GLOBAL_ENUM_CONSTANT(KEY_P); BIND_GLOBAL_ENUM_CONSTANT(KEY_Q); BIND_GLOBAL_ENUM_CONSTANT(KEY_R); BIND_GLOBAL_ENUM_CONSTANT(KEY_S); BIND_GLOBAL_ENUM_CONSTANT(KEY_T); BIND_GLOBAL_ENUM_CONSTANT(KEY_U); BIND_GLOBAL_ENUM_CONSTANT(KEY_V); BIND_GLOBAL_ENUM_CONSTANT(KEY_W); BIND_GLOBAL_ENUM_CONSTANT(KEY_X); BIND_GLOBAL_ENUM_CONSTANT(KEY_Y); BIND_GLOBAL_ENUM_CONSTANT(KEY_Z); BIND_GLOBAL_ENUM_CONSTANT(KEY_BRACKETLEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_BACKSLASH); BIND_GLOBAL_ENUM_CONSTANT(KEY_BRACKETRIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_ASCIICIRCUM); BIND_GLOBAL_ENUM_CONSTANT(KEY_UNDERSCORE); BIND_GLOBAL_ENUM_CONSTANT(KEY_QUOTELEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_BRACELEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_BAR); BIND_GLOBAL_ENUM_CONSTANT(KEY_BRACERIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_ASCIITILDE); BIND_GLOBAL_ENUM_CONSTANT(KEY_NOBREAKSPACE); BIND_GLOBAL_ENUM_CONSTANT(KEY_EXCLAMDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_CENT); BIND_GLOBAL_ENUM_CONSTANT(KEY_STERLING); BIND_GLOBAL_ENUM_CONSTANT(KEY_CURRENCY); BIND_GLOBAL_ENUM_CONSTANT(KEY_YEN); BIND_GLOBAL_ENUM_CONSTANT(KEY_BROKENBAR); BIND_GLOBAL_ENUM_CONSTANT(KEY_SECTION); BIND_GLOBAL_ENUM_CONSTANT(KEY_DIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_COPYRIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_ORDFEMININE); BIND_GLOBAL_ENUM_CONSTANT(KEY_GUILLEMOTLEFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_NOTSIGN); BIND_GLOBAL_ENUM_CONSTANT(KEY_HYPHEN); BIND_GLOBAL_ENUM_CONSTANT(KEY_REGISTERED); BIND_GLOBAL_ENUM_CONSTANT(KEY_MACRON); BIND_GLOBAL_ENUM_CONSTANT(KEY_DEGREE); BIND_GLOBAL_ENUM_CONSTANT(KEY_PLUSMINUS); BIND_GLOBAL_ENUM_CONSTANT(KEY_TWOSUPERIOR); BIND_GLOBAL_ENUM_CONSTANT(KEY_THREESUPERIOR); BIND_GLOBAL_ENUM_CONSTANT(KEY_ACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_MU); BIND_GLOBAL_ENUM_CONSTANT(KEY_PARAGRAPH); BIND_GLOBAL_ENUM_CONSTANT(KEY_PERIODCENTERED); BIND_GLOBAL_ENUM_CONSTANT(KEY_CEDILLA); BIND_GLOBAL_ENUM_CONSTANT(KEY_ONESUPERIOR); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASCULINE); BIND_GLOBAL_ENUM_CONSTANT(KEY_GUILLEMOTRIGHT); BIND_GLOBAL_ENUM_CONSTANT(KEY_ONEQUARTER); BIND_GLOBAL_ENUM_CONSTANT(KEY_ONEHALF); BIND_GLOBAL_ENUM_CONSTANT(KEY_THREEQUARTERS); BIND_GLOBAL_ENUM_CONSTANT(KEY_QUESTIONDOWN); BIND_GLOBAL_ENUM_CONSTANT(KEY_AGRAVE); BIND_GLOBAL_ENUM_CONSTANT(KEY_AACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ACIRCUMFLEX); BIND_GLOBAL_ENUM_CONSTANT(KEY_ATILDE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ADIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_ARING); BIND_GLOBAL_ENUM_CONSTANT(KEY_AE); BIND_GLOBAL_ENUM_CONSTANT(KEY_CCEDILLA); BIND_GLOBAL_ENUM_CONSTANT(KEY_EGRAVE); BIND_GLOBAL_ENUM_CONSTANT(KEY_EACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ECIRCUMFLEX); BIND_GLOBAL_ENUM_CONSTANT(KEY_EDIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_IGRAVE); BIND_GLOBAL_ENUM_CONSTANT(KEY_IACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ICIRCUMFLEX); BIND_GLOBAL_ENUM_CONSTANT(KEY_IDIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_ETH); BIND_GLOBAL_ENUM_CONSTANT(KEY_NTILDE); BIND_GLOBAL_ENUM_CONSTANT(KEY_OGRAVE); BIND_GLOBAL_ENUM_CONSTANT(KEY_OACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_OCIRCUMFLEX); BIND_GLOBAL_ENUM_CONSTANT(KEY_OTILDE); BIND_GLOBAL_ENUM_CONSTANT(KEY_ODIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_MULTIPLY); BIND_GLOBAL_ENUM_CONSTANT(KEY_OOBLIQUE); BIND_GLOBAL_ENUM_CONSTANT(KEY_UGRAVE); BIND_GLOBAL_ENUM_CONSTANT(KEY_UACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_UCIRCUMFLEX); BIND_GLOBAL_ENUM_CONSTANT(KEY_UDIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_YACUTE); BIND_GLOBAL_ENUM_CONSTANT(KEY_THORN); BIND_GLOBAL_ENUM_CONSTANT(KEY_SSHARP); BIND_GLOBAL_ENUM_CONSTANT(KEY_DIVISION); BIND_GLOBAL_ENUM_CONSTANT(KEY_YDIAERESIS); BIND_GLOBAL_ENUM_CONSTANT(KEY_CODE_MASK); BIND_GLOBAL_ENUM_CONSTANT(KEY_MODIFIER_MASK); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_SHIFT); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_ALT); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_META); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_CTRL); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_CMD); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_KPAD); BIND_GLOBAL_ENUM_CONSTANT(KEY_MASK_GROUP_SWITCH); // mouse BIND_GLOBAL_ENUM_CONSTANT(BUTTON_LEFT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MIDDLE); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_UP); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_DOWN); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_LEFT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_WHEEL_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_LEFT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(BUTTON_MASK_MIDDLE); //joypads BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_0); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_1); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_2); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_3); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_4); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_5); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_6); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_7); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_8); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_9); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_10); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_11); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_12); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_13); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_14); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_15); BIND_GLOBAL_ENUM_CONSTANT(JOY_BUTTON_MAX); BIND_GLOBAL_ENUM_CONSTANT(JOY_SONY_CIRCLE); BIND_GLOBAL_ENUM_CONSTANT(JOY_SONY_X); BIND_GLOBAL_ENUM_CONSTANT(JOY_SONY_SQUARE); BIND_GLOBAL_ENUM_CONSTANT(JOY_SONY_TRIANGLE); BIND_GLOBAL_ENUM_CONSTANT(JOY_XBOX_B); BIND_GLOBAL_ENUM_CONSTANT(JOY_XBOX_A); BIND_GLOBAL_ENUM_CONSTANT(JOY_XBOX_X); BIND_GLOBAL_ENUM_CONSTANT(JOY_XBOX_Y); BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_A); BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_B); BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_X); BIND_GLOBAL_ENUM_CONSTANT(JOY_DS_Y); BIND_GLOBAL_ENUM_CONSTANT(JOY_SELECT); BIND_GLOBAL_ENUM_CONSTANT(JOY_START); BIND_GLOBAL_ENUM_CONSTANT(JOY_DPAD_UP); BIND_GLOBAL_ENUM_CONSTANT(JOY_DPAD_DOWN); BIND_GLOBAL_ENUM_CONSTANT(JOY_DPAD_LEFT); BIND_GLOBAL_ENUM_CONSTANT(JOY_DPAD_RIGHT); BIND_GLOBAL_ENUM_CONSTANT(JOY_L); BIND_GLOBAL_ENUM_CONSTANT(JOY_L2); BIND_GLOBAL_ENUM_CONSTANT(JOY_L3); BIND_GLOBAL_ENUM_CONSTANT(JOY_R); BIND_GLOBAL_ENUM_CONSTANT(JOY_R2); BIND_GLOBAL_ENUM_CONSTANT(JOY_R3); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_0); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_1); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_2); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_3); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_4); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_5); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_6); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_7); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_8); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_9); BIND_GLOBAL_ENUM_CONSTANT(JOY_AXIS_MAX); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_LX); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_LY); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_RX); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_RY); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_L2); BIND_GLOBAL_ENUM_CONSTANT(JOY_ANALOG_R2); // error list BIND_GLOBAL_ENUM_CONSTANT(OK); BIND_GLOBAL_ENUM_CONSTANT(FAILED); ///< Generic fail error BIND_GLOBAL_ENUM_CONSTANT(ERR_UNAVAILABLE); ///< What is requested is unsupported/unavailable BIND_GLOBAL_ENUM_CONSTANT(ERR_UNCONFIGURED); ///< The object being used hasn't been properly set up yet BIND_GLOBAL_ENUM_CONSTANT(ERR_UNAUTHORIZED); ///< Missing credentials for requested resource BIND_GLOBAL_ENUM_CONSTANT(ERR_PARAMETER_RANGE_ERROR); ///< Parameter given out of range BIND_GLOBAL_ENUM_CONSTANT(ERR_OUT_OF_MEMORY); ///< Out of memory BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_NOT_FOUND); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_BAD_DRIVE); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_BAD_PATH); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_NO_PERMISSION); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_ALREADY_IN_USE); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_CANT_OPEN); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_CANT_WRITE); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_CANT_READ); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_UNRECOGNIZED); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_CORRUPT); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_MISSING_DEPENDENCIES); BIND_GLOBAL_ENUM_CONSTANT(ERR_FILE_EOF); BIND_GLOBAL_ENUM_CONSTANT(ERR_CANT_OPEN); ///< Can't open a resource/socket/file BIND_GLOBAL_ENUM_CONSTANT(ERR_CANT_CREATE); BIND_GLOBAL_ENUM_CONSTANT(ERR_PARSE_ERROR); BIND_GLOBAL_ENUM_CONSTANT(ERR_QUERY_FAILED); BIND_GLOBAL_ENUM_CONSTANT(ERR_ALREADY_IN_USE); BIND_GLOBAL_ENUM_CONSTANT(ERR_LOCKED); ///< resource is locked BIND_GLOBAL_ENUM_CONSTANT(ERR_TIMEOUT); BIND_GLOBAL_ENUM_CONSTANT(ERR_CANT_ACQUIRE_RESOURCE); BIND_GLOBAL_ENUM_CONSTANT(ERR_INVALID_DATA); ///< Data passed is invalid BIND_GLOBAL_ENUM_CONSTANT(ERR_INVALID_PARAMETER); ///< Parameter passed is invalid BIND_GLOBAL_ENUM_CONSTANT(ERR_ALREADY_EXISTS); ///< When adding ), item already exists BIND_GLOBAL_ENUM_CONSTANT(ERR_DOES_NOT_EXIST); ///< When retrieving/erasing ), it item does not exist BIND_GLOBAL_ENUM_CONSTANT(ERR_DATABASE_CANT_READ); ///< database is full BIND_GLOBAL_ENUM_CONSTANT(ERR_DATABASE_CANT_WRITE); ///< database is full BIND_GLOBAL_ENUM_CONSTANT(ERR_COMPILATION_FAILED); BIND_GLOBAL_ENUM_CONSTANT(ERR_METHOD_NOT_FOUND); BIND_GLOBAL_ENUM_CONSTANT(ERR_LINK_FAILED); BIND_GLOBAL_ENUM_CONSTANT(ERR_SCRIPT_FAILED); BIND_GLOBAL_ENUM_CONSTANT(ERR_CYCLIC_LINK); BIND_GLOBAL_ENUM_CONSTANT(ERR_BUSY); BIND_GLOBAL_ENUM_CONSTANT(ERR_HELP); ///< user requested help!! BIND_GLOBAL_ENUM_CONSTANT(ERR_BUG); ///< a bug in the software certainly happened ), due to a double check failing or unexpected behavior. BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_NONE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_RANGE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_EXP_RANGE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_ENUM); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_EXP_EASING); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_LENGTH); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_KEY_ACCEL); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_FLAGS); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_LAYERS_2D_RENDER); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_LAYERS_2D_PHYSICS); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_LAYERS_3D_RENDER); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_LAYERS_3D_PHYSICS); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_FILE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_DIR); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_GLOBAL_FILE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_GLOBAL_DIR); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_RESOURCE_TYPE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_MULTILINE_TEXT); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_COLOR_NO_ALPHA); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSY); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_STORAGE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_EDITOR); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_NETWORK); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_EDITOR_HELPER); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_CHECKABLE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_CHECKED); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_INTERNATIONALIZED); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_GROUP); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_CATEGORY); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_STORE_IF_NONZERO); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_STORE_IF_NONONE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_NO_INSTANCE_STATE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_RESTART_IF_CHANGED); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_SCRIPT_VARIABLE); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_DEFAULT); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_DEFAULT_INTL); BIND_GLOBAL_ENUM_CONSTANT(PROPERTY_USAGE_NOEDITOR); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_NORMAL); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_EDITOR); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_NOSCRIPT); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_CONST); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_REVERSE); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_VIRTUAL); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAG_FROM_SCRIPT); BIND_GLOBAL_ENUM_CONSTANT(METHOD_FLAGS_DEFAULT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_NIL", Variant::NIL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_BOOL", Variant::BOOL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_INT", Variant::INT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_REAL", Variant::REAL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_STRING", Variant::STRING); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_VECTOR2", Variant::VECTOR2); // 5 BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_RECT2", Variant::RECT2); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_VECTOR3", Variant::VECTOR3); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_TRANSFORM2D", Variant::TRANSFORM2D); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_PLANE", Variant::PLANE); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_QUAT", Variant::QUAT); // 10 BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_AABB", Variant::AABB); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_BASIS", Variant::BASIS); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_TRANSFORM", Variant::TRANSFORM); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_COLOR", Variant::COLOR); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_NODE_PATH", Variant::NODE_PATH); // 15 BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_RID", Variant::_RID); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_OBJECT", Variant::OBJECT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_DICTIONARY", Variant::DICTIONARY); // 20 BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_ARRAY", Variant::ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_RAW_ARRAY", Variant::POOL_BYTE_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_INT_ARRAY", Variant::POOL_INT_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_REAL_ARRAY", Variant::POOL_REAL_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_STRING_ARRAY", Variant::POOL_STRING_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_VECTOR2_ARRAY", Variant::POOL_VECTOR2_ARRAY); // 25 BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_VECTOR3_ARRAY", Variant::POOL_VECTOR3_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_COLOR_ARRAY", Variant::POOL_COLOR_ARRAY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("TYPE_MAX", Variant::VARIANT_MAX); //comparation BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_EQUAL", Variant::OP_EQUAL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_NOT_EQUAL", Variant::OP_NOT_EQUAL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_LESS", Variant::OP_LESS); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_LESS_EQUAL", Variant::OP_LESS_EQUAL); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_GREATER", Variant::OP_GREATER); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_GREATER_EQUAL", Variant::OP_GREATER_EQUAL); //mathematic BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_ADD", Variant::OP_ADD); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_SUBTRACT", Variant::OP_SUBTRACT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_MULTIPLY", Variant::OP_MULTIPLY); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_DIVIDE", Variant::OP_DIVIDE); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_NEGATE", Variant::OP_NEGATE); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_POSITIVE", Variant::OP_POSITIVE); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_MODULE", Variant::OP_MODULE); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_STRING_CONCAT", Variant::OP_STRING_CONCAT); //bitwise BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_SHIFT_LEFT", Variant::OP_SHIFT_LEFT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_SHIFT_RIGHT", Variant::OP_SHIFT_RIGHT); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_BIT_AND", Variant::OP_BIT_AND); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_BIT_OR", Variant::OP_BIT_OR); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_BIT_XOR", Variant::OP_BIT_XOR); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_BIT_NEGATE", Variant::OP_BIT_NEGATE); //logic BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_AND", Variant::OP_AND); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_OR", Variant::OP_OR); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_XOR", Variant::OP_XOR); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_NOT", Variant::OP_NOT); //containment BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_IN", Variant::OP_IN); BIND_GLOBAL_ENUM_CONSTANT_CUSTOM("OP_MAX", Variant::OP_MAX); } void unregister_global_constants() { _global_constants.clear(); } int GlobalConstants::get_global_constant_count() { return _global_constants.size(); } #ifdef DEBUG_METHODS_ENABLED StringName GlobalConstants::get_global_constant_enum(int p_idx) { return _global_constants[p_idx].enum_name; } #else StringName GlobalConstants::get_global_constant_enum(int p_idx) { return StringName(); } #endif const char *GlobalConstants::get_global_constant_name(int p_idx) { return _global_constants[p_idx].name; } int GlobalConstants::get_global_constant_value(int p_idx) { return _global_constants[p_idx].value; }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com