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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
1c9732f74854c66d7ca971b83d58739dfb17bdb8
aa0247d6d25406d9613acbe62d012f118312ac4e
/showanddelete.h
1c31d636a8d1a73c0a4b12cfac88fcc94ca025e3
[]
no_license
AIClubUBB/Lab5OOP
37c22138f08128fff2245d38bb2f2a80801160ce
40a4edfc60be3836d2689a9f7cf7c761e17422e6
refs/heads/master
2020-05-15T16:55:36.070324
2019-05-29T14:39:40
2019-05-29T14:39:40
182,397,569
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#ifndef SHOWANDDELETE_H #define SHOWANDDELETE_H #include <QDialog> #include "datamodel.h" namespace Ui { class ShowandDelete; } class ShowandDelete : public QDialog { Q_OBJECT public: explicit ShowandDelete(QWidget *parent = nullptr); ~ShowandDelete(); private slots: void on_BackButton_clicked(); void on_DeleteButton_clicked(); private: Ui::ShowandDelete *ui; DataModel *data_model; }; #endif // SHOWANDDELETE_H
[ "noreply@github.com" ]
AIClubUBB.noreply@github.com
fcc6f3973edcdc787cc1fbcd51cae5785a8915c8
a43d044987a2c18e634a7dadccd3fc97fcbf1ce6
/src/qt/walletview.cpp
70a032ebb83bfb04f052d6ef930217eb5cdc5e30
[ "MIT" ]
permissive
mhannigan/luckycoin
6de1b3287aad72eb7cdac0cb0af2f5363ee3b78f
f67258db5078c47adc6a768216b97ef685da5875
refs/heads/master
2020-03-27T06:54:52.029067
2018-08-26T02:46:21
2018-08-26T02:46:21
146,146,249
0
0
null
null
null
null
UTF-8
C++
false
false
15,967
cpp
// Copyright (c) 2011-2015 The Bitcoin developers // Copyright (c) 2016-2018 The LUK developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "bip38tooldialog.h" #include "bitcoingui.h" #include "blockexplorer.h" #include "clientmodel.h" #include "guiutil.h" #include "masternodeconfig.h" #include "multisenddialog.h" #include "multisigdialog.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "privacydialog.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "walletmodel.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QLabel> #include <QProgressDialog> #include <QPushButton> #include <QSettings> #include <QVBoxLayout> WalletView::WalletView(QWidget* parent) : QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); explorerWindow = new BlockExplorer(this); transactionsPage = new QWidget(this); // Create Header with the same names as the other forms to be CSS-Id compatible QFrame *frame_Header = new QFrame(transactionsPage); frame_Header->setObjectName(QStringLiteral("frame_Header")); QVBoxLayout* verticalLayout_8 = new QVBoxLayout(frame_Header); verticalLayout_8->setObjectName(QStringLiteral("verticalLayout_8")); verticalLayout_8->setContentsMargins(0, 0, 0, 0); QHBoxLayout* horizontalLayout_Header = new QHBoxLayout(); horizontalLayout_Header->setObjectName(QStringLiteral("horizontalLayout_Header")); QLabel* labelOverviewHeaderLeft = new QLabel(frame_Header); labelOverviewHeaderLeft->setObjectName(QStringLiteral("labelOverviewHeaderLeft")); labelOverviewHeaderLeft->setMinimumSize(QSize(464, 60)); labelOverviewHeaderLeft->setMaximumSize(QSize(16777215, 60)); labelOverviewHeaderLeft->setText(tr("HISTORY")); QFont fontHeaderLeft; fontHeaderLeft.setPointSize(20); fontHeaderLeft.setBold(true); fontHeaderLeft.setWeight(75); labelOverviewHeaderLeft->setFont(fontHeaderLeft); horizontalLayout_Header->addWidget(labelOverviewHeaderLeft); QSpacerItem* horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_Header->addItem(horizontalSpacer_3); QLabel* labelOverviewHeaderRight = new QLabel(frame_Header); labelOverviewHeaderRight->setObjectName(QStringLiteral("labelOverviewHeaderRight")); labelOverviewHeaderRight->setMinimumSize(QSize(464, 60)); labelOverviewHeaderRight->setMaximumSize(QSize(16777215, 60)); labelOverviewHeaderRight->setText(QString()); QFont fontHeaderRight; fontHeaderRight.setPointSize(14); labelOverviewHeaderRight->setFont(fontHeaderRight); labelOverviewHeaderRight->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); horizontalLayout_Header->addWidget(labelOverviewHeaderRight); horizontalLayout_Header->setStretch(0, 1); horizontalLayout_Header->setStretch(2, 1); verticalLayout_8->addLayout(horizontalLayout_Header); QVBoxLayout* vbox = new QVBoxLayout(); QHBoxLayout* hbox_buttons = new QHBoxLayout(); vbox->addWidget(frame_Header); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton* exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); // Sum of selected transactions QLabel* transactionSumLabel = new QLabel(); // Label transactionSumLabel->setObjectName("transactionSumLabel"); // Label ID as CSS-reference transactionSumLabel->setText(tr("Selected amount:")); hbox_buttons->addWidget(transactionSumLabel); transactionSum = new QLabel(); // Amount transactionSum->setObjectName("transactionSum"); // Label ID as CSS-reference transactionSum->setMinimumSize(200, 8); transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse); hbox_buttons->addWidget(transactionSum); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); privacyPage = new PrivacyDialog(); receiveCoinsPage = new ReceiveCoinsDialog(); sendCoinsPage = new SendCoinsDialog(); addWidget(overviewPage); addWidget(transactionsPage); addWidget(privacyPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); addWidget(explorerWindow); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeListPage = new MasternodeList(); addWidget(masternodeListPage); } // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Update wallet with sum of selected transactions connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString))); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI* gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString, QString, unsigned int)), gui, SLOT(message(QString, QString, unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString, int, CAmount, QString, QString)), gui, SLOT(incomingTransaction(QString, int, CAmount, QString, QString))); } } void WalletView::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); sendCoinsPage->setClientModel(clientModel); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeListPage->setClientModel(clientModel); } } void WalletView::setWalletModel(WalletModel* walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeListPage->setWalletModel(walletModel); } privacyPage->setModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsPage->setModel(walletModel); if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString, QString, unsigned int)), this, SIGNAL(message(QString, QString, unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(processNewTransaction(QModelIndex, int, int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock(AskPassphraseDialog::Context)), this, SLOT(unlockWallet(AskPassphraseDialog::Context))); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel* ttm = walletModel->getTransactionTableModel(); if (!ttm || ttm->processingQueuedTransactions()) return; QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); // Refresh UI-elements in case coins were locked/unlocked in CoinControl walletModel->emitBalanceChanged(); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoBlockExplorerPage() { setCurrentWidget(explorerWindow); } void WalletView::gotoMasternodePage() { QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { setCurrentWidget(masternodeListPage); } } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoPrivacyPage() { setCurrentWidget(privacyPage); // Refresh UI-elements in case coins were locked/unlocked in CoinControl walletModel->emitBalanceChanged(); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog* signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog* signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } void WalletView::gotoBip38Tool() { Bip38ToolDialog* bip38ToolDialog = new Bip38ToolDialog(this); //bip38ToolDialog->setAttribute(Qt::WA_DeleteOnClose); bip38ToolDialog->setModel(walletModel); bip38ToolDialog->showTab_ENC(true); } void WalletView::gotoMultiSendDialog() { MultiSendDialog* multiSendDialog = new MultiSendDialog(this); multiSendDialog->setModel(walletModel); multiSendDialog->show(); } void WalletView::gotoMultisigDialog(int index) { MultisigDialog* multisig = new MultisigDialog(this); multisig->setModel(walletModel); multisig->showTab(index); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); privacyPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if (!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Mode::Encrypt : AskPassphraseDialog::Mode::Decrypt, this, walletModel, AskPassphraseDialog::Context::Encrypt); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; walletModel->backupWallet(filename); } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::Mode::ChangePass, this, walletModel, AskPassphraseDialog::Context::ChangePass); dlg.exec(); } void WalletView::unlockWallet(AskPassphraseDialog::Context context) { if (!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) { AskPassphraseDialog dlg(AskPassphraseDialog::Mode::UnlockAnonymize, this, walletModel, context); dlg.exec(); } } void WalletView::lockWallet() { if (!walletModel) return; walletModel->setWalletLocked(true); } void WalletView::toggleLockWallet() { if (!walletModel) return; WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); // Unlock the wallet when requested if (encStatus == walletModel->Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Mode::UnlockAnonymize, this, walletModel, AskPassphraseDialog::Context::ToggleLock); dlg.exec(); } else if (encStatus == walletModel->Unlocked || encStatus == walletModel->UnlockedForAnonymizationOnly) { walletModel->setWalletLocked(true); } } void WalletView::usedSendingAddresses() { if (!walletModel) return; AddressBookPage* dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if (!walletModel) return; AddressBookPage* dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString& title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } /** Update wallet with the sum of the selected transactions */ void WalletView::trxAmount(QString amount) { transactionSum->setText(amount); }
[ "root@ip-172-31-94-31.ec2.internal" ]
root@ip-172-31-94-31.ec2.internal
5928c561fbcc036d05f70103088e180521bd7745
be21053e9bc0e3e26833ad416793cdf9df97f21e
/src/OpenRTMPlugin/deprecated/VirtualRobotRTC.cpp
a078438b142d439a99c736a72ced30db6dfabd85
[ "MIT", "IJG", "Zlib" ]
permissive
MiladShafiee/Surena4HumanoidSimulation-Choreonoid
2353f715ac126aa4404b57cd0c8c0612539f7c1b
a3d8af2a6ae2e7720bab4a329809507632173177
refs/heads/master
2020-04-10T00:46:13.984347
2018-12-23T07:08:16
2018-12-23T07:08:16
160,695,810
2
1
null
null
null
null
UTF-8
C++
false
false
14,803
cpp
/** \file \author shizuko hattori */ #include"VirtualRobotRTC.h" #include "BodyRTCItem.h" #include <cnoid/Config> #include <rtm/NVUtil.h> #include <cnoid/MessageView> #include <iostream> #include "../gettext.h" using namespace std; using namespace cnoid; namespace { const bool CONTROLLER_BRIDGE_DEBUG = false; } void VirtualRobotRTC::registerFactory(RTC::Manager* manager, const char* componentTypeName) { static const char* spec[] = { "implementation_id", "VirtualRobot", "type_name", "VirtualRobot", "description", "This component enables controller components to" "access the I/O of a virtual robot in a Choreonoid simulation", "version", CNOID_VERSION_STRING, "vendor", "AIST", "category", "Choreonoid", "activity_type", "DataFlowComponent", "max_instance", "100", "language", "C++", "lang_type", "compile", "" }; if(CONTROLLER_BRIDGE_DEBUG){ cout << "initVirtualRobotRTC()" << endl; } RTC::Properties profile(spec); profile.setDefault("type_name", componentTypeName); manager->registerFactory(profile, RTC::Create<VirtualRobotRTC>, RTC::Delete<VirtualRobotRTC>); } VirtualRobotRTC::VirtualRobotRTC(RTC::Manager* manager) : RTC::DataFlowComponentBase(manager) { if(CONTROLLER_BRIDGE_DEBUG){ cout << "VirtualRobotRTC::VirtualRobotRTC" << endl; } } RTC::ReturnCode_t VirtualRobotRTC::onInitialize() { return RTC::RTC_OK; } VirtualRobotRTC::~VirtualRobotRTC() { if(CONTROLLER_BRIDGE_DEBUG){ cout << "VirtualRobotRTC::~VirtualRobotRTC" << endl; } } void VirtualRobotRTC::createPorts( BridgeConf* bridgeConf) { if(bridgeConf){ PortInfoMap::iterator it; for(it = bridgeConf->outPortInfos.begin(); it != bridgeConf->outPortInfos.end(); ++it){ if (!createOutPortHandler(it->second)){ cerr << "createOutPortHandler(" << it->second.portName << ") failed" << std::endl; } } for(it = bridgeConf->inPortInfos.begin(); it != bridgeConf->inPortInfos.end(); ++it){ if (!createInPortHandler(it->second)){ cerr << "createInPortHandler(" << it->second.portName << ") failed" << std::endl; } } updatePortObjectRefs(); } } bool VirtualRobotRTC::createOutPortHandler(PortInfo& portInfo) { DataTypeId dataTypeId = portInfo.dataTypeId; bool ret = false; if(portInfo.dataOwnerNames.empty()){ switch(dataTypeId) { case JOINT_VALUE: case JOINT_VELOCITY: case JOINT_ACCELERATION: case JOINT_TORQUE: case FORCE_SENSOR: case RATE_GYRO_SENSOR: case ACCELERATION_SENSOR: ret = registerOutPortHandler(new SensorStateOutPortHandler(portInfo)); break; case CAMERA_RANGE: ret = registerOutPortHandler(new CameraRangeOutPortHandler(portInfo, false)); break; case CAMERA_IMAGE: ret = registerOutPortHandler(new CameraImageOutPortHandler(portInfo, false)); break; case RANGE_SENSOR: ret = registerOutPortHandler(new RangeSensorOutPortHandler(portInfo, false)); break; default: break; } } else { switch(dataTypeId) { case JOINT_VALUE: case JOINT_VELOCITY: case JOINT_ACCELERATION: case JOINT_TORQUE: case ABS_TRANSFORM: case ABS_VELOCITY: case ABS_ACCELERATION: case CONSTRAINT_FORCE: case EXTERNAL_FORCE: ret = registerOutPortHandler(new LinkDataOutPortHandler(portInfo)); break; case ABS_TRANSFORM2: ret = registerOutPortHandler(new AbsTransformOutPortHandler(portInfo)); break; case FORCE_SENSOR: case RATE_GYRO_SENSOR: case ACCELERATION_SENSOR: ret = registerOutPortHandler(new SensorDataOutPortHandler(portInfo)); break; case RATE_GYRO_SENSOR2: ret = registerOutPortHandler(new GyroSensorOutPortHandler(portInfo)); break; case ACCELERATION_SENSOR2: ret = registerOutPortHandler(new AccelerationSensorOutPortHandler(portInfo)); break; case LIGHT: ret = registerOutPortHandler(new LightOnOutPortHandler(portInfo)); break; case CAMERA_RANGE: ret = registerOutPortHandler(new CameraRangeOutPortHandler(portInfo, false)); break; case CAMERA_IMAGE: ret = registerOutPortHandler(new CameraImageOutPortHandler(portInfo, false)); break; case RANGE_SENSOR: ret = registerOutPortHandler(new RangeSensorOutPortHandler(portInfo, false)); break; default: break; } } return ret; } bool VirtualRobotRTC::createInPortHandler(PortInfo& portInfo) { DataTypeId dataTypeId = portInfo.dataTypeId; bool ret = false; if(portInfo.dataOwnerNames.empty()){ switch(dataTypeId) { case JOINT_VALUE: case JOINT_VELOCITY: case JOINT_ACCELERATION: case JOINT_TORQUE: ret = registerInPortHandler(new JointDataSeqInPortHandler(portInfo)); break; default: break; } }else{ switch(dataTypeId){ case JOINT_VALUE: case JOINT_VELOCITY: case JOINT_ACCELERATION: case JOINT_TORQUE: ret = registerInPortHandler(new LinkDataInPortHandler(portInfo)); break; case ABS_TRANSFORM2: ret = registerInPortHandler(new AbsTransformInPortHandler(portInfo)); break; case ABS_TRANSFORM: case ABS_VELOCITY: case ABS_ACCELERATION: case EXTERNAL_FORCE: ret = registerInPortHandler(new LinkDataInPortHandler(portInfo)); break; case LIGHT: ret = registerInPortHandler(new LightOnInPortHandler(portInfo)); break; default: break; } } return ret; } PortHandlerPtr VirtualRobotRTC::getOutPortHandler(const std::string& name_) { string name(name_); string::size_type index = name.rfind("."); if (index != string::npos) name = name.substr(index+1); PortHandlerPtr portHandler; OutPortHandlerMap::iterator p = outPortHandlers.find(name); if(p != outPortHandlers.end()){ portHandler = p->second; } return portHandler; } PortHandlerPtr VirtualRobotRTC::getInPortHandler(const std::string& name_) { string name(name_); string::size_type index = name.rfind("."); if (index != string::npos) name = name.substr(index+1); PortHandlerPtr portHandler; InPortHandlerMap::iterator q = inPortHandlers.find(name); if(q != inPortHandlers.end()){ portHandler = q->second; } return portHandler; } void VirtualRobotRTC::updatePortObjectRefs() { for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ OutPortHandlerPtr& handler = it->second; handler->portRef = RTC::PortService::_nil(); } for(InPortHandlerMap::iterator it = inPortHandlers.begin(); it != inPortHandlers.end(); ++it){ InPortHandlerPtr& handler = it->second; handler->portRef = RTC::PortService::_nil(); } RTC::PortServiceList_var ports = get_ports(); for(CORBA::ULong i=0; i < ports->length(); ++i){ RTC::PortProfile_var profile = ports[i]->get_port_profile(); const char* type; if (!(NVUtil::find(profile->properties, "port.port_type") >>= type)) break; PortHandlerPtr portHandler; if(!std::strcmp(type,"DataInPort")) portHandler = getInPortHandler(string(profile->name)); else portHandler = getOutPortHandler(string(profile->name)); if(portHandler){ portHandler->portRef = ports[i]; } } } RTC::RTCList* VirtualRobotRTC::getConnectedRtcs() { RTC::RTCList* rtcList = new RTC::RTCList; set<string> foundRtcNames; for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ OutPortHandlerPtr& handler = it->second; addConnectedRtcs(handler->portRef, *rtcList, foundRtcNames); } for(InPortHandlerMap::iterator it = inPortHandlers.begin(); it != inPortHandlers.end(); ++it){ InPortHandlerPtr& handler = it->second; addConnectedRtcs(handler->portRef, *rtcList, foundRtcNames); } return rtcList; } void VirtualRobotRTC::addConnectedRtcs(RTC::PortService_ptr portRef, RTC::RTCList& rtcList, std::set<std::string>& foundRtcNames) { RTC::PortProfile_var portProfile = portRef->get_port_profile(); string portName(portProfile->name); RTC::ConnectorProfileList_var connectorProfiles = portRef->get_connector_profiles(); for(CORBA::ULong i=0; i < connectorProfiles->length(); ++i){ RTC::ConnectorProfile& connectorProfile = connectorProfiles[i]; RTC::PortServiceList& connectedPorts = connectorProfile.ports; for(CORBA::ULong j=0; j < connectedPorts.length(); ++j){ RTC::PortService_ptr connectedPortRef = connectedPorts[j]; RTC::PortProfile_var connectedPortProfile = connectedPortRef->get_port_profile(); RTC::RTObject_var connectedRtcRef = RTC::RTObject::_duplicate(connectedPortProfile->owner); RTC::RTObject_var thisRef = RTC::RTObject::_duplicate(getObjRef()); if(!CORBA::is_nil(connectedRtcRef) && !connectedRtcRef->_is_equivalent(thisRef)){ CORBA::ULong ii=0; for(; ii<rtcList.length(); ii++){ if(rtcList[ii]->_is_equivalent(connectedRtcRef)) break; } if(ii == rtcList.length()){ RTC::ComponentProfile_var componentProfile = connectedRtcRef->get_component_profile(); string connectedRtcName(componentProfile->instance_name); MessageView* mv = MessageView::instance(); mv->putln(fmt(_("detected RTC: %1% Port connection: %2% <--> %3%")) % connectedRtcName % portName % connectedPortProfile->name); RTC::ExecutionContextList_var execServices = connectedRtcRef->get_owned_contexts(); for(CORBA::ULong k=0; k < execServices->length(); k++) { RTC::ExecutionContext_var execContext = execServices[k]; OpenRTM::ExtTrigExecutionContextService_var extTrigExecContext = OpenRTM::ExtTrigExecutionContextService::_narrow(execContext); if(!CORBA::is_nil(extTrigExecContext)){ CORBA::ULong n = rtcList.length(); rtcList.length(n + 1); rtcList[n] = connectedRtcRef; foundRtcNames.insert(connectedRtcName); RTC::PortServiceList_var portList = connectedRtcRef->get_ports(); for(CORBA::ULong jj=0; jj < portList->length(); ++jj){ addConnectedRtcs(portList[jj], rtcList, foundRtcNames); } } } } } } } } void VirtualRobotRTC::inputDataFromSimulator(BodyRTCItem* bodyRTC) { const double controlTime = bodyRTC->controlTime(); const double controlTimeStep = bodyRTC->timeStep(); for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ double stepTime = it->second->stepTime; if(stepTime){ double w = controlTime - (int)(controlTime / stepTime) * stepTime + controlTimeStep / 2; if(w >= stepTime){ w = 0.0; } if(w < controlTimeStep ){ it->second->inputDataFromSimulator(bodyRTC); } }else{ it->second->inputDataFromSimulator(bodyRTC); } } } void VirtualRobotRTC::outputDataToSimulator(const BodyPtr& body) { for(InPortHandlerMap::iterator it = inPortHandlers.begin(); it != inPortHandlers.end(); ++it){ it->second->outputDataToSimulator(body); } } void VirtualRobotRTC::writeDataToOutPorts(double controlTime, double controlTimeStep) { for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ if(!it->second->synchController) continue; double stepTime = it->second->stepTime; if(stepTime){ double w = controlTime-(int)(controlTime/stepTime)*stepTime + controlTimeStep/2; if(w >= stepTime) w=0; if(w < controlTimeStep ) it->second->writeDataToPort(); }else{ it->second->writeDataToPort(); } } } void VirtualRobotRTC::readDataFromInPorts() { for(InPortHandlerMap::iterator it = inPortHandlers.begin(); it != inPortHandlers.end(); ++it){ it->second->readDataFromPort(); } } void VirtualRobotRTC::stop() { } bool VirtualRobotRTC::checkOutPortStepTime(double controlTimeStep) { bool ret = true; for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ double stepTime = it->second->stepTime; if(stepTime && stepTime < controlTimeStep){ cerr << "OutPort(" << it->second->portName << ") : Output interval(" << stepTime << ") must be longer than the control interval(" << controlTimeStep << ")." << std::endl; ret &= false; } } return ret; } void VirtualRobotRTC::initialize(Body* simulationBody) { for(OutPortHandlerMap::iterator it = outPortHandlers.begin(); it != outPortHandlers.end(); ++it){ CameraImageOutPortHandler* cameaImageOutPortHandler = dynamic_cast<CameraImageOutPortHandler*>(it->second.get()); if(cameaImageOutPortHandler) cameaImageOutPortHandler->initialize(simulationBody); CameraRangeOutPortHandler* cameaRangeOutPortHandler = dynamic_cast<CameraRangeOutPortHandler*>(it->second.get()); if(cameaRangeOutPortHandler) cameaRangeOutPortHandler->initialize(simulationBody); RangeSensorOutPortHandler* rangeSensorOutPortHandler = dynamic_cast<RangeSensorOutPortHandler*>(it->second.get()); if(rangeSensorOutPortHandler) rangeSensorOutPortHandler->initialize(simulationBody); } }
[ "shafiee.a@ut.ac.ir" ]
shafiee.a@ut.ac.ir
04b66df97c74a74c3b2a2aa445e2263a02238b28
c6c015ae4a2b31e5228769cd1fe53aa78466976c
/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp
c2aec36ee86e74cab40dd1dd6f9e1e49e5c9eb30
[]
no_license
invisibleboy/my-customized-llvm
ad5717111ca9c6f111d07d964c64fb0ac51ced05
8cbd2eb76680846f189697d3cc8d5e06067212be
refs/heads/master
2021-01-10T09:46:09.266230
2012-01-04T11:22:51
2012-01-04T11:22:51
36,672,282
0
0
null
null
null
null
UTF-8
C++
false
false
105,455
cpp
//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code to emit Expr nodes with scalar LLVM types as LLVM code. // //===----------------------------------------------------------------------===// #include "clang/Frontend/CodeGenOptions.h" #include "CodeGenFunction.h" #include "CGCXXABI.h" #include "CGObjCRuntime.h" #include "CodeGenModule.h" #include "CGDebugInfo.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/Intrinsics.h" #include "llvm/Module.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetData.h" #include <cstdarg> using namespace clang; using namespace CodeGen; using llvm::Value; //===----------------------------------------------------------------------===// // Scalar Expression Emitter //===----------------------------------------------------------------------===// namespace { struct BinOpInfo { Value *LHS; Value *RHS; QualType Ty; // Computation Type. BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform const Expr *E; // Entire expr, for error unsupported. May not be binop. }; static bool MustVisitNullValue(const Expr *E) { // If a null pointer expression's type is the C++0x nullptr_t, then // it's not necessarily a simple constant and it must be evaluated // for its potential side effects. return E->getType()->isNullPtrType(); } class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, Value*> { CodeGenFunction &CGF; CGBuilderTy &Builder; bool IgnoreResultAssign; llvm::LLVMContext &VMContext; public: ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), VMContext(cgf.getLLVMContext()) { } //===--------------------------------------------------------------------===// // Utilities //===--------------------------------------------------------------------===// bool TestAndClearIgnoreResultAssign() { bool I = IgnoreResultAssign; IgnoreResultAssign = false; return I; } llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } Value *EmitLoadOfLValue(LValue LV) { return CGF.EmitLoadOfLValue(LV).getScalarVal(); } /// EmitLoadOfLValue - Given an expression with complex type that represents a /// value l-value, this method emits the address of the l-value, then loads /// and returns the result. Value *EmitLoadOfLValue(const Expr *E) { return EmitLoadOfLValue(EmitCheckedLValue(E)); } /// EmitConversionToBool - Convert the specified expression value to a /// boolean (i1) truth value. This is equivalent to "Val != 0". Value *EmitConversionToBool(Value *Src, QualType DstTy); /// EmitScalarConversion - Emit a conversion from the specified type to the /// specified destination type, both of which are LLVM scalar types. Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); /// EmitComplexToScalarConversion - Emit a conversion from the specified /// complex type to the specified destination type, where the destination type /// is an LLVM scalar type. Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy); /// EmitNullValue - Emit a value that corresponds to null for the given type. Value *EmitNullValue(QualType Ty); /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. Value *EmitFloatToBoolConversion(Value *V) { // Compare against 0.0 for fp scalars. llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); return Builder.CreateFCmpUNE(V, Zero, "tobool"); } /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. Value *EmitPointerToBoolConversion(Value *V) { Value *Zero = llvm::ConstantPointerNull::get( cast<llvm::PointerType>(V->getType())); return Builder.CreateICmpNE(V, Zero, "tobool"); } Value *EmitIntToBoolConversion(Value *V) { // Because of the type rules of C, we often end up computing a // logical value, then zero extending it to int, then wanting it // as a logical value again. Optimize this common case. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { Value *Result = ZI->getOperand(0); // If there aren't any more uses, zap the instruction to save space. // Note that there can be more uses, for example if this // is the result of an assignment. if (ZI->use_empty()) ZI->eraseFromParent(); return Result; } } return Builder.CreateIsNotNull(V, "tobool"); } //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// Value *Visit(Expr *E) { return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); } Value *VisitStmt(Stmt *S) { S->dump(CGF.getContext().getSourceManager()); llvm_unreachable("Stmt can't have complex result type!"); } Value *VisitExpr(Expr *S); Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { return Visit(E->getReplacement()); } Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { return Visit(GE->getResultExpr()); } // Leaves. Value *VisitIntegerLiteral(const IntegerLiteral *E) { return Builder.getInt(E->getValue()); } Value *VisitFloatingLiteral(const FloatingLiteral *E) { return llvm::ConstantFP::get(VMContext, E->getValue()); } Value *VisitCharacterLiteral(const CharacterLiteral *E) { return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); } Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); } Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { return EmitNullValue(E->getType()); } Value *VisitGNUNullExpr(const GNUNullExpr *E) { return EmitNullValue(E->getType()); } Value *VisitOffsetOfExpr(OffsetOfExpr *E); Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); return Builder.CreateBitCast(V, ConvertType(E->getType())); } Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); } Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { return CGF.EmitPseudoObjectRValue(E).getScalarVal(); } Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { if (E->isGLValue()) return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E)); // Otherwise, assume the mapping is the scalar directly. return CGF.getOpaqueRValueMapping(E).getScalarVal(); } // l-values. Value *VisitDeclRefExpr(DeclRefExpr *E) { Expr::EvalResult Result; if (!E->EvaluateAsRValue(Result, CGF.getContext())) return EmitLoadOfLValue(E); assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); llvm::Constant *C; if (Result.Val.isInt()) C = Builder.getInt(Result.Val.getInt()); else if (Result.Val.isFloat()) C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat()); else return EmitLoadOfLValue(E); // Make sure we emit a debug reference to the global variable. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { if (!CGF.getContext().DeclMustBeEmitted(VD)) CGF.EmitDeclRefExprDbgValue(E, C); } else if (isa<EnumConstantDecl>(E->getDecl())) { CGF.EmitDeclRefExprDbgValue(E, C); } return C; } Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { return CGF.EmitObjCSelectorExpr(E); } Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { return CGF.EmitObjCProtocolExpr(E); } Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E); } Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { if (E->getMethodDecl() && E->getMethodDecl()->getResultType()->isReferenceType()) return EmitLoadOfLValue(E); return CGF.EmitObjCMessageExpr(E).getScalarVal(); } Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { LValue LV = CGF.EmitObjCIsaExpr(E); Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal(); return V; } Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); Value *VisitMemberExpr(MemberExpr *E); Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); } Value *VisitInitListExpr(InitListExpr *E); Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { return CGF.CGM.EmitNullConstant(E->getType()); } Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { if (E->getType()->isVariablyModifiedType()) CGF.EmitVariablyModifiedType(E->getType()); return VisitCastExpr(E); } Value *VisitCastExpr(CastExpr *E); Value *VisitCallExpr(const CallExpr *E) { if (E->getCallReturnType()->isReferenceType()) return EmitLoadOfLValue(E); return CGF.EmitCallExpr(E).getScalarVal(); } Value *VisitStmtExpr(const StmtExpr *E); Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); // Unary Operators. Value *VisitUnaryPostDec(const UnaryOperator *E) { LValue LV = EmitLValue(E->getSubExpr()); return EmitScalarPrePostIncDec(E, LV, false, false); } Value *VisitUnaryPostInc(const UnaryOperator *E) { LValue LV = EmitLValue(E->getSubExpr()); return EmitScalarPrePostIncDec(E, LV, true, false); } Value *VisitUnaryPreDec(const UnaryOperator *E) { LValue LV = EmitLValue(E->getSubExpr()); return EmitScalarPrePostIncDec(E, LV, false, true); } Value *VisitUnaryPreInc(const UnaryOperator *E) { LValue LV = EmitLValue(E->getSubExpr()); return EmitScalarPrePostIncDec(E, LV, true, true); } llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E, llvm::Value *InVal, llvm::Value *NextVal, bool IsInc); llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre); Value *VisitUnaryAddrOf(const UnaryOperator *E) { if (isa<MemberPointerType>(E->getType())) // never sugared return CGF.CGM.getMemberPointerConstant(E); return EmitLValue(E->getSubExpr()).getAddress(); } Value *VisitUnaryDeref(const UnaryOperator *E) { if (E->getType()->isVoidType()) return Visit(E->getSubExpr()); // the actual value should be unused return EmitLoadOfLValue(E); } Value *VisitUnaryPlus(const UnaryOperator *E) { // This differs from gcc, though, most likely due to a bug in gcc. TestAndClearIgnoreResultAssign(); return Visit(E->getSubExpr()); } Value *VisitUnaryMinus (const UnaryOperator *E); Value *VisitUnaryNot (const UnaryOperator *E); Value *VisitUnaryLNot (const UnaryOperator *E); Value *VisitUnaryReal (const UnaryOperator *E); Value *VisitUnaryImag (const UnaryOperator *E); Value *VisitUnaryExtension(const UnaryOperator *E) { return Visit(E->getSubExpr()); } // C++ Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { return EmitLoadOfLValue(E); } Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { return Visit(DAE->getExpr()); } Value *VisitCXXThisExpr(CXXThisExpr *TE) { return CGF.LoadCXXThis(); } Value *VisitExprWithCleanups(ExprWithCleanups *E) { CGF.enterFullExpression(E); CodeGenFunction::RunCleanupsScope Scope(CGF); return Visit(E->getSubExpr()); } Value *VisitCXXNewExpr(const CXXNewExpr *E) { return CGF.EmitCXXNewExpr(E); } Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { CGF.EmitCXXDeleteExpr(E); return 0; } Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { return Builder.getInt1(E->getValue()); } Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); } Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); } Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); } Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { // C++ [expr.pseudo]p1: // The result shall only be used as the operand for the function call // operator (), and the result of such a call has type void. The only // effect is the evaluation of the postfix-expression before the dot or // arrow. CGF.EmitScalarExpr(E->getBase()); return 0; } Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { return EmitNullValue(E->getType()); } Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); return 0; } Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { return Builder.getInt1(E->getValue()); } // Binary Operators. Value *EmitMul(const BinOpInfo &Ops) { if (Ops.Ty->isSignedIntegerOrEnumerationType()) { switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { case LangOptions::SOB_Undefined: return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); case LangOptions::SOB_Defined: return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); case LangOptions::SOB_Trapping: return EmitOverflowCheckedBinOp(Ops); } } if (Ops.LHS->getType()->isFPOrFPVectorTy()) return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); } bool isTrapvOverflowBehavior() { return CGF.getContext().getLangOptions().getSignedOverflowBehavior() == LangOptions::SOB_Trapping; } /// Create a binary op that checks for overflow. /// Currently only supports +, - and *. Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); // Emit the overflow BB when -ftrapv option is activated. void EmitOverflowBB(llvm::BasicBlock *overflowBB) { Builder.SetInsertPoint(overflowBB); llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap); Builder.CreateCall(Trap); Builder.CreateUnreachable(); } // Check for undefined division and modulus behaviors. void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, llvm::Value *Zero,bool isDiv); Value *EmitDiv(const BinOpInfo &Ops); Value *EmitRem(const BinOpInfo &Ops); Value *EmitAdd(const BinOpInfo &Ops); Value *EmitSub(const BinOpInfo &Ops); Value *EmitShl(const BinOpInfo &Ops); Value *EmitShr(const BinOpInfo &Ops); Value *EmitAnd(const BinOpInfo &Ops) { return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); } Value *EmitXor(const BinOpInfo &Ops) { return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); } Value *EmitOr (const BinOpInfo &Ops) { return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); } BinOpInfo EmitBinOps(const BinaryOperator *E); LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, Value *(ScalarExprEmitter::*F)(const BinOpInfo &), Value *&Result); Value *EmitCompoundAssign(const CompoundAssignOperator *E, Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); // Binary operators and binary compound assignment operators. #define HANDLEBINOP(OP) \ Value *VisitBin ## OP(const BinaryOperator *E) { \ return Emit ## OP(EmitBinOps(E)); \ } \ Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ } HANDLEBINOP(Mul) HANDLEBINOP(Div) HANDLEBINOP(Rem) HANDLEBINOP(Add) HANDLEBINOP(Sub) HANDLEBINOP(Shl) HANDLEBINOP(Shr) HANDLEBINOP(And) HANDLEBINOP(Xor) HANDLEBINOP(Or) #undef HANDLEBINOP // Comparisons. Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, unsigned SICmpOpc, unsigned FCmpOpc); #define VISITCOMP(CODE, UI, SI, FP) \ Value *VisitBin##CODE(const BinaryOperator *E) { \ return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ llvm::FCmpInst::FP); } VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) #undef VISITCOMP Value *VisitBinAssign (const BinaryOperator *E); Value *VisitBinLAnd (const BinaryOperator *E); Value *VisitBinLOr (const BinaryOperator *E); Value *VisitBinComma (const BinaryOperator *E); Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } // Other Operators. Value *VisitBlockExpr(const BlockExpr *BE); Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); Value *VisitChooseExpr(ChooseExpr *CE); Value *VisitVAArgExpr(VAArgExpr *VE); Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { return CGF.EmitObjCStringLiteral(E); } Value *VisitAsTypeExpr(AsTypeExpr *CE); Value *VisitAtomicExpr(AtomicExpr *AE); }; } // end anonymous namespace. //===----------------------------------------------------------------------===// // Utilities //===----------------------------------------------------------------------===// /// EmitConversionToBool - Convert the specified expression value to a /// boolean (i1) truth value. This is equivalent to "Val != 0". Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); if (SrcType->isRealFloatingType()) return EmitFloatToBoolConversion(Src); if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && "Unknown scalar type to convert"); if (isa<llvm::IntegerType>(Src->getType())) return EmitIntToBoolConversion(Src); assert(isa<llvm::PointerType>(Src->getType())); return EmitPointerToBoolConversion(Src); } /// EmitScalarConversion - Emit a conversion from the specified type to the /// specified destination type, both of which are LLVM scalar types. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, QualType DstType) { SrcType = CGF.getContext().getCanonicalType(SrcType); DstType = CGF.getContext().getCanonicalType(DstType); if (SrcType == DstType) return Src; if (DstType->isVoidType()) return 0; llvm::Type *SrcTy = Src->getType(); // Floating casts might be a bit special: if we're doing casts to / from half // FP, we should go via special intrinsics. if (SrcType->isHalfType()) { Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src); SrcType = CGF.getContext().FloatTy; SrcTy = llvm::Type::getFloatTy(VMContext); } // Handle conversions to bool first, they are special: comparisons against 0. if (DstType->isBooleanType()) return EmitConversionToBool(Src, SrcType); llvm::Type *DstTy = ConvertType(DstType); // Ignore conversions like int -> uint. if (SrcTy == DstTy) return Src; // Handle pointer conversions next: pointers can only be converted to/from // other pointers and integers. Check for pointer types in terms of LLVM, as // some native types (like Obj-C id) may map to a pointer type. if (isa<llvm::PointerType>(DstTy)) { // The source value may be an integer, or a pointer. if (isa<llvm::PointerType>(SrcTy)) return Builder.CreateBitCast(Src, DstTy, "conv"); assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); // First, convert to the correct width so that we control the kind of // extension. llvm::Type *MiddleTy = CGF.IntPtrTy; bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); llvm::Value* IntResult = Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); // Then, cast to pointer. return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); } if (isa<llvm::PointerType>(SrcTy)) { // Must be an ptr to int cast. assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); return Builder.CreatePtrToInt(Src, DstTy, "conv"); } // A scalar can be splatted to an extended vector of the same element type if (DstType->isExtVectorType() && !SrcType->isVectorType()) { // Cast the scalar to element type QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); // Insert the element in element zero of an undef vector llvm::Value *UnV = llvm::UndefValue::get(DstTy); llvm::Value *Idx = Builder.getInt32(0); UnV = Builder.CreateInsertElement(UnV, Elt, Idx); // Splat the element across to all elements SmallVector<llvm::Constant*, 16> Args; unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); for (unsigned i = 0; i != NumElements; ++i) Args.push_back(Builder.getInt32(0)); llvm::Constant *Mask = llvm::ConstantVector::get(Args); llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); return Yay; } // Allow bitcast from vector to integer/fp of the same size. if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) return Builder.CreateBitCast(Src, DstTy, "conv"); // Finally, we have the arithmetic types: real int/float. Value *Res = NULL; llvm::Type *ResTy = DstTy; // Cast to half via float if (DstType->isHalfType()) DstTy = llvm::Type::getFloatTy(VMContext); if (isa<llvm::IntegerType>(SrcTy)) { bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); if (isa<llvm::IntegerType>(DstTy)) Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); else if (InputSigned) Res = Builder.CreateSIToFP(Src, DstTy, "conv"); else Res = Builder.CreateUIToFP(Src, DstTy, "conv"); } else if (isa<llvm::IntegerType>(DstTy)) { assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); if (DstType->isSignedIntegerOrEnumerationType()) Res = Builder.CreateFPToSI(Src, DstTy, "conv"); else Res = Builder.CreateFPToUI(Src, DstTy, "conv"); } else { assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && "Unknown real conversion"); if (DstTy->getTypeID() < SrcTy->getTypeID()) Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); else Res = Builder.CreateFPExt(Src, DstTy, "conv"); } if (DstTy != ResTy) { assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res); } return Res; } /// EmitComplexToScalarConversion - Emit a conversion from the specified complex /// type to the specified destination type, where the destination type is an /// LLVM scalar type. Value *ScalarExprEmitter:: EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy) { // Get the source element type. SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); // Handle conversions to bool first, they are special: comparisons against 0. if (DstTy->isBooleanType()) { // Complex != 0 -> (Real != 0) | (Imag != 0) Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); return Builder.CreateOr(Src.first, Src.second, "tobool"); } // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, // the imaginary part of the complex value is discarded and the value of the // real part is converted according to the conversion rules for the // corresponding real type. return EmitScalarConversion(Src.first, SrcTy, DstTy); } Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); return llvm::Constant::getNullValue(ConvertType(Ty)); } //===----------------------------------------------------------------------===// // Visitor Methods //===----------------------------------------------------------------------===// Value *ScalarExprEmitter::VisitExpr(Expr *E) { CGF.ErrorUnsupported(E, "scalar expression"); if (E->getType()->isVoidType()) return 0; return llvm::UndefValue::get(CGF.ConvertType(E->getType())); } Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { // Vector Mask Case if (E->getNumSubExprs() == 2 || (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); Value *Mask; llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); unsigned LHSElts = LTy->getNumElements(); if (E->getNumSubExprs() == 3) { Mask = CGF.EmitScalarExpr(E->getExpr(2)); // Shuffle LHS & RHS into one input vector. SmallVector<llvm::Constant*, 32> concat; for (unsigned i = 0; i != LHSElts; ++i) { concat.push_back(Builder.getInt32(2*i)); concat.push_back(Builder.getInt32(2*i+1)); } Value* CV = llvm::ConstantVector::get(concat); LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); LHSElts *= 2; } else { Mask = RHS; } llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); llvm::Constant* EltMask; // Treat vec3 like vec4. if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) EltMask = llvm::ConstantInt::get(MTy->getElementType(), (1 << llvm::Log2_32(LHSElts+2))-1); else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) EltMask = llvm::ConstantInt::get(MTy->getElementType(), (1 << llvm::Log2_32(LHSElts+1))-1); else EltMask = llvm::ConstantInt::get(MTy->getElementType(), (1 << llvm::Log2_32(LHSElts))-1); // Mask off the high bits of each shuffle index. SmallVector<llvm::Constant *, 32> MaskV; for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) MaskV.push_back(EltMask); Value* MaskBits = llvm::ConstantVector::get(MaskV); Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); // newv = undef // mask = mask & maskbits // for each elt // n = extract mask i // x = extract val n // newv = insert newv, x, i llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), MTy->getNumElements()); Value* NewV = llvm::UndefValue::get(RTy); for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { Value *Indx = Builder.getInt32(i); Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); // Handle vec3 special since the index will be off by one for the RHS. if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { Value *cmpIndx, *newIndx; cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3), "cmp_shuf_idx"); newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj"); Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); } Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); } return NewV; } Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); // Handle vec3 special since the index will be off by one for the RHS. llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); SmallVector<llvm::Constant*, 32> indices; for (unsigned i = 2; i < E->getNumSubExprs(); i++) { unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); if (VTy->getNumElements() == 3 && Idx > 3) Idx -= 1; indices.push_back(Builder.getInt32(Idx)); } Value *SV = llvm::ConstantVector::get(indices); return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); } Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { llvm::APSInt Value; if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { if (E->isArrow()) CGF.EmitScalarExpr(E->getBase()); else EmitLValue(E->getBase()); return Builder.getInt(Value); } // Emit debug info for aggregate now, if it was delayed to reduce // debug info size. CGDebugInfo *DI = CGF.getDebugInfo(); if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) { QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType(); if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl())) DI->getOrCreateRecordType(PTy->getPointeeType(), M->getParent()->getLocation()); } return EmitLoadOfLValue(E); } Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { TestAndClearIgnoreResultAssign(); // Emit subscript expressions in rvalue context's. For most cases, this just // loads the lvalue formed by the subscript expr. However, we have to be // careful, because the base of a vector subscript is occasionally an rvalue, // so we can't get it as an lvalue. if (!E->getBase()->getType()->isVectorType()) return EmitLoadOfLValue(E); // Handle the vector case. The base must be a vector, the index must be an // integer value. Value *Base = Visit(E->getBase()); Value *Idx = Visit(E->getIdx()); bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType(); Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); return Builder.CreateExtractElement(Base, Idx, "vecext"); } static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, unsigned Off, llvm::Type *I32Ty) { int MV = SVI->getMaskValue(Idx); if (MV == -1) return llvm::UndefValue::get(I32Ty); return llvm::ConstantInt::get(I32Ty, Off+MV); } Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { bool Ignore = TestAndClearIgnoreResultAssign(); (void)Ignore; assert (Ignore == false && "init list ignored"); unsigned NumInitElements = E->getNumInits(); if (E->hadArrayRangeDesignator()) CGF.ErrorUnsupported(E, "GNU array range designator extension"); llvm::VectorType *VType = dyn_cast<llvm::VectorType>(ConvertType(E->getType())); if (!VType) { if (NumInitElements == 0) { // C++11 value-initialization for the scalar. return EmitNullValue(E->getType()); } // We have a scalar in braces. Just use the first element. return Visit(E->getInit(0)); } unsigned ResElts = VType->getNumElements(); // Loop over initializers collecting the Value for each, and remembering // whether the source was swizzle (ExtVectorElementExpr). This will allow // us to fold the shuffle for the swizzle into the shuffle for the vector // initializer, since LLVM optimizers generally do not want to touch // shuffles. unsigned CurIdx = 0; bool VIsUndefShuffle = false; llvm::Value *V = llvm::UndefValue::get(VType); for (unsigned i = 0; i != NumInitElements; ++i) { Expr *IE = E->getInit(i); Value *Init = Visit(IE); SmallVector<llvm::Constant*, 16> Args; llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); // Handle scalar elements. If the scalar initializer is actually one // element of a different vector of the same width, use shuffle instead of // extract+insert. if (!VVT) { if (isa<ExtVectorElementExpr>(IE)) { llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); if (EI->getVectorOperandType()->getNumElements() == ResElts) { llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); Value *LHS = 0, *RHS = 0; if (CurIdx == 0) { // insert into undef -> shuffle (src, undef) Args.push_back(C); for (unsigned j = 1; j != ResElts; ++j) Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); LHS = EI->getVectorOperand(); RHS = V; VIsUndefShuffle = true; } else if (VIsUndefShuffle) { // insert into undefshuffle && size match -> shuffle (v, src) llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); for (unsigned j = 0; j != CurIdx; ++j) Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); for (unsigned j = CurIdx + 1; j != ResElts; ++j) Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); RHS = EI->getVectorOperand(); VIsUndefShuffle = false; } if (!Args.empty()) { llvm::Constant *Mask = llvm::ConstantVector::get(Args); V = Builder.CreateShuffleVector(LHS, RHS, Mask); ++CurIdx; continue; } } } V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), "vecinit"); VIsUndefShuffle = false; ++CurIdx; continue; } unsigned InitElts = VVT->getNumElements(); // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's // input is the same width as the vector being constructed, generate an // optimized shuffle of the swizzle input into the result. unsigned Offset = (CurIdx == 0) ? 0 : ResElts; if (isa<ExtVectorElementExpr>(IE)) { llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); Value *SVOp = SVI->getOperand(0); llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); if (OpTy->getNumElements() == ResElts) { for (unsigned j = 0; j != CurIdx; ++j) { // If the current vector initializer is a shuffle with undef, merge // this shuffle directly into it. if (VIsUndefShuffle) { Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, CGF.Int32Ty)); } else { Args.push_back(Builder.getInt32(j)); } } for (unsigned j = 0, je = InitElts; j != je; ++j) Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); if (VIsUndefShuffle) V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); Init = SVOp; } } // Extend init to result vector length, and then shuffle its contribution // to the vector initializer into V. if (Args.empty()) { for (unsigned j = 0; j != InitElts; ++j) Args.push_back(Builder.getInt32(j)); for (unsigned j = InitElts; j != ResElts; ++j) Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); llvm::Constant *Mask = llvm::ConstantVector::get(Args); Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), Mask, "vext"); Args.clear(); for (unsigned j = 0; j != CurIdx; ++j) Args.push_back(Builder.getInt32(j)); for (unsigned j = 0; j != InitElts; ++j) Args.push_back(Builder.getInt32(j+Offset)); for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); } // If V is undef, make sure it ends up on the RHS of the shuffle to aid // merging subsequent shuffles into this one. if (CurIdx == 0) std::swap(V, Init); llvm::Constant *Mask = llvm::ConstantVector::get(Args); V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); VIsUndefShuffle = isa<llvm::UndefValue>(Init); CurIdx += InitElts; } // FIXME: evaluate codegen vs. shuffling against constant null vector. // Emit remaining default initializers. llvm::Type *EltTy = VType->getElementType(); // Emit remaining default initializers for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { Value *Idx = Builder.getInt32(CurIdx); llvm::Value *Init = llvm::Constant::getNullValue(EltTy); V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); } return V; } static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { const Expr *E = CE->getSubExpr(); if (CE->getCastKind() == CK_UncheckedDerivedToBase) return false; if (isa<CXXThisExpr>(E)) { // We always assume that 'this' is never null. return false; } if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { // And that glvalue casts are never null. if (ICE->getValueKind() != VK_RValue) return false; } return true; } // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts // have to handle a more broad range of conversions than explicit casts, as they // handle things like function to ptr-to-function decay etc. Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { Expr *E = CE->getSubExpr(); QualType DestTy = CE->getType(); CastKind Kind = CE->getCastKind(); if (!DestTy->isVoidType()) TestAndClearIgnoreResultAssign(); // Since almost all cast kinds apply to scalars, this switch doesn't have // a default case, so the compiler will warn on a missing case. The cases // are in the same order as in the CastKind enum. switch (Kind) { case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); case CK_LValueBitCast: case CK_ObjCObjectLValueCast: { Value *V = EmitLValue(E).getAddress(); V = Builder.CreateBitCast(V, ConvertType(CGF.getContext().getPointerType(DestTy))); return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy)); } case CK_CPointerToObjCPointerCast: case CK_BlockPointerToObjCPointerCast: case CK_AnyPointerToBlockPointerCast: case CK_BitCast: { Value *Src = Visit(const_cast<Expr*>(E)); return Builder.CreateBitCast(Src, ConvertType(DestTy)); } case CK_NoOp: case CK_UserDefinedConversion: return Visit(const_cast<Expr*>(E)); case CK_BaseToDerived: { const CXXRecordDecl *DerivedClassDecl = DestTy->getCXXRecordDeclForPointerType(); return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(), ShouldNullCheckClassCastValue(CE)); } case CK_UncheckedDerivedToBase: case CK_DerivedToBase: { const RecordType *DerivedClassTy = E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); CXXRecordDecl *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(), ShouldNullCheckClassCastValue(CE)); } case CK_Dynamic: { Value *V = Visit(const_cast<Expr*>(E)); const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); return CGF.EmitDynamicCast(V, DCE); } case CK_ArrayToPointerDecay: { assert(E->getType()->isArrayType() && "Array to pointer decay must have array source type!"); Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. // Note that VLA pointers are always decayed, so we don't need to do // anything here. if (!E->getType()->isVariableArrayType()) { assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) ->getElementType()) && "Expected pointer to array"); V = Builder.CreateStructGEP(V, 0, "arraydecay"); } // Make sure the array decay ends up being the right type. This matters if // the array type was of an incomplete type. return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType())); } case CK_FunctionToPointerDecay: return EmitLValue(E).getAddress(); case CK_NullToPointer: if (MustVisitNullValue(E)) (void) Visit(E); return llvm::ConstantPointerNull::get( cast<llvm::PointerType>(ConvertType(DestTy))); case CK_NullToMemberPointer: { if (MustVisitNullValue(E)) (void) Visit(E); const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); } case CK_BaseToDerivedMemberPointer: case CK_DerivedToBaseMemberPointer: { Value *Src = Visit(E); // Note that the AST doesn't distinguish between checked and // unchecked member pointer conversions, so we always have to // implement checked conversions here. This is inefficient when // actual control flow may be required in order to perform the // check, which it is for data member pointers (but not member // function pointers on Itanium and ARM). return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); } case CK_ARCProduceObject: return CGF.EmitARCRetainScalarExpr(E); case CK_ARCConsumeObject: return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); case CK_ARCReclaimReturnedObject: { llvm::Value *value = Visit(E); value = CGF.EmitARCRetainAutoreleasedReturnValue(value); return CGF.EmitObjCConsumeObject(E->getType(), value); } case CK_ARCExtendBlockObject: return CGF.EmitARCExtendBlockObject(E); case CK_FloatingRealToComplex: case CK_FloatingComplexCast: case CK_IntegralRealToComplex: case CK_IntegralComplexCast: case CK_IntegralComplexToFloatingComplex: case CK_FloatingComplexToIntegralComplex: case CK_ConstructorConversion: case CK_ToUnion: llvm_unreachable("scalar cast to non-scalar value"); break; case CK_LValueToRValue: assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); return Visit(const_cast<Expr*>(E)); case CK_IntegralToPointer: { Value *Src = Visit(const_cast<Expr*>(E)); // First, convert to the correct width so that we control the kind of // extension. llvm::Type *MiddleTy = CGF.IntPtrTy; bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); llvm::Value* IntResult = Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); } case CK_PointerToIntegral: assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); case CK_ToVoid: { CGF.EmitIgnoredExpr(E); return 0; } case CK_VectorSplat: { llvm::Type *DstTy = ConvertType(DestTy); Value *Elt = Visit(const_cast<Expr*>(E)); // Insert the element in element zero of an undef vector llvm::Value *UnV = llvm::UndefValue::get(DstTy); llvm::Value *Idx = Builder.getInt32(0); UnV = Builder.CreateInsertElement(UnV, Elt, Idx); // Splat the element across to all elements SmallVector<llvm::Constant*, 16> Args; unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); llvm::Constant *Zero = Builder.getInt32(0); for (unsigned i = 0; i < NumElements; i++) Args.push_back(Zero); llvm::Constant *Mask = llvm::ConstantVector::get(Args); llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); return Yay; } case CK_IntegralCast: case CK_IntegralToFloating: case CK_FloatingToIntegral: case CK_FloatingCast: return EmitScalarConversion(Visit(E), E->getType(), DestTy); case CK_IntegralToBoolean: return EmitIntToBoolConversion(Visit(E)); case CK_PointerToBoolean: return EmitPointerToBoolConversion(Visit(E)); case CK_FloatingToBoolean: return EmitFloatToBoolConversion(Visit(E)); case CK_MemberPointerToBoolean: { llvm::Value *MemPtr = Visit(E); const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); } case CK_FloatingComplexToReal: case CK_IntegralComplexToReal: return CGF.EmitComplexExpr(E, false, true).first; case CK_FloatingComplexToBoolean: case CK_IntegralComplexToBoolean: { CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); // TODO: kill this function off, inline appropriate case here return EmitComplexToScalarConversion(V, E->getType(), DestTy); } } llvm_unreachable("unknown scalar cast"); return 0; } Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { CodeGenFunction::StmtExprEvaluation eval(CGF); return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType()) .getScalarVal(); } Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { LValue LV = CGF.EmitBlockDeclRefLValue(E); return CGF.EmitLoadOfLValue(LV).getScalarVal(); } //===----------------------------------------------------------------------===// // Unary Operators //===----------------------------------------------------------------------===// llvm::Value *ScalarExprEmitter:: EmitAddConsiderOverflowBehavior(const UnaryOperator *E, llvm::Value *InVal, llvm::Value *NextVal, bool IsInc) { switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { case LangOptions::SOB_Undefined: return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec"); break; case LangOptions::SOB_Defined: return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec"); break; case LangOptions::SOB_Trapping: BinOpInfo BinOp; BinOp.LHS = InVal; BinOp.RHS = NextVal; BinOp.Ty = E->getType(); BinOp.Opcode = BO_Add; BinOp.E = E; return EmitOverflowCheckedBinOp(BinOp); } llvm_unreachable("Unknown SignedOverflowBehaviorTy"); } llvm::Value * ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre) { QualType type = E->getSubExpr()->getType(); llvm::Value *value = EmitLoadOfLValue(LV); llvm::Value *input = value; int amount = (isInc ? 1 : -1); // Special case of integer increment that we have to check first: bool++. // Due to promotion rules, we get: // bool++ -> bool = bool + 1 // -> bool = (int)bool + 1 // -> bool = ((int)bool + 1 != 0) // An interesting aspect of this is that increment is always true. // Decrement does not have this property. if (isInc && type->isBooleanType()) { value = Builder.getTrue(); // Most common case by far: integer increment. } else if (type->isIntegerType()) { llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); // Note that signed integer inc/dec with width less than int can't // overflow because of promotion rules; we're just eliding a few steps here. if (type->isSignedIntegerOrEnumerationType() && value->getType()->getPrimitiveSizeInBits() >= CGF.IntTy->getBitWidth()) value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc); else value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); // Next most common: pointer increment. } else if (const PointerType *ptr = type->getAs<PointerType>()) { QualType type = ptr->getPointeeType(); // VLA types don't have constant size. if (const VariableArrayType *vla = CGF.getContext().getAsVariableArrayType(type)) { llvm::Value *numElts = CGF.getVLASize(vla).first; if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) value = Builder.CreateGEP(value, numElts, "vla.inc"); else value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); // Arithmetic on function pointers (!) is just +-1. } else if (type->isFunctionType()) { llvm::Value *amt = Builder.getInt32(amount); value = CGF.EmitCastToVoidPtr(value); if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) value = Builder.CreateGEP(value, amt, "incdec.funcptr"); else value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); value = Builder.CreateBitCast(value, input->getType()); // For everything else, we can just do a simple increment. } else { llvm::Value *amt = Builder.getInt32(amount); if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) value = Builder.CreateGEP(value, amt, "incdec.ptr"); else value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); } // Vector increment/decrement. } else if (type->isVectorType()) { if (type->hasIntegerRepresentation()) { llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); } else { value = Builder.CreateFAdd( value, llvm::ConstantFP::get(value->getType(), amount), isInc ? "inc" : "dec"); } // Floating point. } else if (type->isRealFloatingType()) { // Add the inc/dec to the real part. llvm::Value *amt; if (type->isHalfType()) { // Another special case: half FP increment should be done via float value = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), input); } if (value->getType()->isFloatTy()) amt = llvm::ConstantFP::get(VMContext, llvm::APFloat(static_cast<float>(amount))); else if (value->getType()->isDoubleTy()) amt = llvm::ConstantFP::get(VMContext, llvm::APFloat(static_cast<double>(amount))); else { llvm::APFloat F(static_cast<float>(amount)); bool ignored; F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, &ignored); amt = llvm::ConstantFP::get(VMContext, F); } value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); if (type->isHalfType()) value = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), value); // Objective-C pointer types. } else { const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); value = CGF.EmitCastToVoidPtr(value); CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); if (!isInc) size = -size; llvm::Value *sizeValue = llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); else value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); value = Builder.CreateBitCast(value, input->getType()); } // Store the updated result through the lvalue. if (LV.isBitField()) CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); else CGF.EmitStoreThroughLValue(RValue::get(value), LV); // If this is a postinc, return the value read from memory, otherwise use the // updated value. return isPre ? value : input; } Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { TestAndClearIgnoreResultAssign(); // Emit unary minus with EmitSub so we handle overflow cases etc. BinOpInfo BinOp; BinOp.RHS = Visit(E->getSubExpr()); if (BinOp.RHS->getType()->isFPOrFPVectorTy()) BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); else BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); BinOp.Ty = E->getType(); BinOp.Opcode = BO_Sub; BinOp.E = E; return EmitSub(BinOp); } Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { TestAndClearIgnoreResultAssign(); Value *Op = Visit(E->getSubExpr()); return Builder.CreateNot(Op, "neg"); } Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { // Compare operand to zero. Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); // Invert value. // TODO: Could dynamically modify easy computations here. For example, if // the operand is an icmp ne, turn into icmp eq. BoolVal = Builder.CreateNot(BoolVal, "lnot"); // ZExt result to the expr type. return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); } Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { // Try folding the offsetof to a constant. llvm::APSInt Value; if (E->EvaluateAsInt(Value, CGF.getContext())) return Builder.getInt(Value); // Loop over the components of the offsetof to compute the value. unsigned n = E->getNumComponents(); llvm::Type* ResultType = ConvertType(E->getType()); llvm::Value* Result = llvm::Constant::getNullValue(ResultType); QualType CurrentType = E->getTypeSourceInfo()->getType(); for (unsigned i = 0; i != n; ++i) { OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); llvm::Value *Offset = 0; switch (ON.getKind()) { case OffsetOfExpr::OffsetOfNode::Array: { // Compute the index Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); // Save the element type CurrentType = CGF.getContext().getAsArrayType(CurrentType)->getElementType(); // Compute the element size llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); // Multiply out to compute the result Offset = Builder.CreateMul(Idx, ElemSize); break; } case OffsetOfExpr::OffsetOfNode::Field: { FieldDecl *MemberDecl = ON.getField(); RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); // Compute the index of the field in its parent. unsigned i = 0; // FIXME: It would be nice if we didn't have to loop here! for (RecordDecl::field_iterator Field = RD->field_begin(), FieldEnd = RD->field_end(); Field != FieldEnd; (void)++Field, ++i) { if (*Field == MemberDecl) break; } assert(i < RL.getFieldCount() && "offsetof field in wrong type"); // Compute the offset to the field int64_t OffsetInt = RL.getFieldOffset(i) / CGF.getContext().getCharWidth(); Offset = llvm::ConstantInt::get(ResultType, OffsetInt); // Save the element type. CurrentType = MemberDecl->getType(); break; } case OffsetOfExpr::OffsetOfNode::Identifier: llvm_unreachable("dependent __builtin_offsetof"); case OffsetOfExpr::OffsetOfNode::Base: { if (ON.getBase()->isVirtual()) { CGF.ErrorUnsupported(E, "virtual base in offsetof"); continue; } RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); // Save the element type. CurrentType = ON.getBase()->getType(); // Compute the offset to the base. const RecordType *BaseRT = CurrentType->getAs<RecordType>(); CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) / CGF.getContext().getCharWidth(); Offset = llvm::ConstantInt::get(ResultType, OffsetInt); break; } } Result = Builder.CreateAdd(Result, Offset); } return Result; } /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of /// argument of the sizeof expression as an integer. Value * ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( const UnaryExprOrTypeTraitExpr *E) { QualType TypeToSize = E->getTypeOfArgument(); if (E->getKind() == UETT_SizeOf) { if (const VariableArrayType *VAT = CGF.getContext().getAsVariableArrayType(TypeToSize)) { if (E->isArgumentType()) { // sizeof(type) - make sure to emit the VLA size. CGF.EmitVariablyModifiedType(TypeToSize); } else { // C99 6.5.3.4p2: If the argument is an expression of type // VLA, it is evaluated. CGF.EmitIgnoredExpr(E->getArgumentExpr()); } QualType eltType; llvm::Value *numElts; llvm::tie(numElts, eltType) = CGF.getVLASize(VAT); llvm::Value *size = numElts; // Scale the number of non-VLA elements by the non-VLA element size. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); if (!eltSize.isOne()) size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); return size; } } // If this isn't sizeof(vla), the result must be constant; use the constant // folding logic so we don't have to duplicate it here. return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); } Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { Expr *Op = E->getSubExpr(); if (Op->getType()->isAnyComplexType()) { // If it's an l-value, load through the appropriate subobject l-value. // Note that we have to ask E because Op might be an l-value that // this won't work for, e.g. an Obj-C property. if (E->isGLValue()) return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); // Otherwise, calculate and project. return CGF.EmitComplexExpr(Op, false, true).first; } return Visit(Op); } Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { Expr *Op = E->getSubExpr(); if (Op->getType()->isAnyComplexType()) { // If it's an l-value, load through the appropriate subobject l-value. // Note that we have to ask E because Op might be an l-value that // this won't work for, e.g. an Obj-C property. if (Op->isGLValue()) return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); // Otherwise, calculate and project. return CGF.EmitComplexExpr(Op, true, false).second; } // __imag on a scalar returns zero. Emit the subexpr to ensure side // effects are evaluated, but not the actual value. CGF.EmitScalarExpr(Op, true); return llvm::Constant::getNullValue(ConvertType(E->getType())); } //===----------------------------------------------------------------------===// // Binary Operators //===----------------------------------------------------------------------===// BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { TestAndClearIgnoreResultAssign(); BinOpInfo Result; Result.LHS = Visit(E->getLHS()); Result.RHS = Visit(E->getRHS()); Result.Ty = E->getType(); Result.Opcode = E->getOpcode(); Result.E = E; return Result; } LValue ScalarExprEmitter::EmitCompoundAssignLValue( const CompoundAssignOperator *E, Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), Value *&Result) { QualType LHSTy = E->getLHS()->getType(); BinOpInfo OpInfo; if (E->getComputationResultType()->isAnyComplexType()) { // This needs to go through the complex expression emitter, but it's a tad // complicated to do that... I'm leaving it out for now. (Note that we do // actually need the imaginary part of the RHS for multiplication and // division.) CGF.ErrorUnsupported(E, "complex compound assignment"); Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); return LValue(); } // Emit the RHS first. __block variables need to have the rhs evaluated // first, plus this should improve codegen a little. OpInfo.RHS = Visit(E->getRHS()); OpInfo.Ty = E->getComputationResultType(); OpInfo.Opcode = E->getOpcode(); OpInfo.E = E; // Load/convert the LHS. LValue LHSLV = EmitCheckedLValue(E->getLHS()); OpInfo.LHS = EmitLoadOfLValue(LHSLV); OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType()); // Expand the binary operator. Result = (this->*Func)(OpInfo); // Convert the result back to the LHS type. Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); // Store the result value into the LHS lvalue. Bit-fields are handled // specially because the result is altered by the store, i.e., [C99 6.5.16p1] // 'An assignment expression has the value of the left operand after the // assignment...'. if (LHSLV.isBitField()) CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); else CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); return LHSLV; } Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { bool Ignore = TestAndClearIgnoreResultAssign(); Value *RHS; LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); // If the result is clearly ignored, return now. if (Ignore) return 0; // The result of an assignment in C is the assigned r-value. if (!CGF.getContext().getLangOptions().CPlusPlus) return RHS; // If the lvalue is non-volatile, return the computed value of the assignment. if (!LHS.isVolatileQualified()) return RHS; // Otherwise, reload the value. return EmitLoadOfLValue(LHS); } void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { llvm::Function::iterator insertPt = Builder.GetInsertBlock(); llvm::BasicBlock *contBB = CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn, llvm::next(insertPt)); llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); if (Ops.Ty->hasSignedIntegerRepresentation()) { llvm::Value *IntMin = Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero); llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin); llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne); llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and"); Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), overflowBB, contBB); } else { CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), overflowBB, contBB); } EmitOverflowBB(overflowBB); Builder.SetInsertPoint(contBB); } Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { if (isTrapvOverflowBehavior()) { llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); if (Ops.Ty->isIntegerType()) EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); else if (Ops.Ty->isRealFloatingType()) { llvm::Function::iterator insertPt = Builder.GetInsertBlock(); llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn, llvm::next(insertPt)); llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), overflowBB, DivCont); EmitOverflowBB(overflowBB); Builder.SetInsertPoint(DivCont); } } if (Ops.LHS->getType()->isFPOrFPVectorTy()) { llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); if (CGF.getContext().getLangOptions().OpenCL) { // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp llvm::Type *ValTy = Val->getType(); if (ValTy->isFloatTy() || (isa<llvm::VectorType>(ValTy) && cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) CGF.SetFPAccuracy(Val, 5, 2); } return Val; } else if (Ops.Ty->hasUnsignedIntegerRepresentation()) return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); else return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); } Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { // Rem in C can't be a floating point type: C99 6.5.5p2. if (isTrapvOverflowBehavior()) { llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); if (Ops.Ty->isIntegerType()) EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); } if (Ops.Ty->hasUnsignedIntegerRepresentation()) return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); else return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); } Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { unsigned IID; unsigned OpID = 0; switch (Ops.Opcode) { case BO_Add: case BO_AddAssign: OpID = 1; IID = llvm::Intrinsic::sadd_with_overflow; break; case BO_Sub: case BO_SubAssign: OpID = 2; IID = llvm::Intrinsic::ssub_with_overflow; break; case BO_Mul: case BO_MulAssign: OpID = 3; IID = llvm::Intrinsic::smul_with_overflow; break; default: llvm_unreachable("Unsupported operation for overflow detection"); IID = 0; } OpID <<= 1; OpID |= 1; llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); // Branch in case of overflow. llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); llvm::Function::iterator insertPt = initialBB; llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn, llvm::next(insertPt)); llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); Builder.CreateCondBr(overflow, overflowBB, continueBB); // Handle overflow with llvm.trap. const std::string *handlerName = &CGF.getContext().getLangOptions().OverflowHandler; if (handlerName->empty()) { EmitOverflowBB(overflowBB); Builder.SetInsertPoint(continueBB); return result; } // If an overflow handler is set, then we want to call it and then use its // result, if it returns. Builder.SetInsertPoint(overflowBB); // Get the overflow handler. llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext); llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; llvm::FunctionType *handlerTy = llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); // Sign extend the args to 64-bit, so that we can use the same handler for // all types of overflow. llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); // Call the handler with the two arguments, the operation, and the size of // the result. llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs, Builder.getInt8(OpID), Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())); // Truncate the result back to the desired size. handlerResult = Builder.CreateTrunc(handlerResult, opTy); Builder.CreateBr(continueBB); Builder.SetInsertPoint(continueBB); llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); phi->addIncoming(result, initialBB); phi->addIncoming(handlerResult, overflowBB); return phi; } /// Emit pointer + index arithmetic. static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op, bool isSubtraction) { // Must have binary (not unary) expr here. Unary pointer // increment/decrement doesn't use this path. const BinaryOperator *expr = cast<BinaryOperator>(op.E); Value *pointer = op.LHS; Expr *pointerOperand = expr->getLHS(); Value *index = op.RHS; Expr *indexOperand = expr->getRHS(); // In a subtraction, the LHS is always the pointer. if (!isSubtraction && !pointer->getType()->isPointerTy()) { std::swap(pointer, index); std::swap(pointerOperand, indexOperand); } unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); if (width != CGF.PointerWidthInBits) { // Zero-extend or sign-extend the pointer value according to // whether the index is signed or not. bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned, "idx.ext"); } // If this is subtraction, negate the index. if (isSubtraction) index = CGF.Builder.CreateNeg(index, "idx.neg"); const PointerType *pointerType = pointerOperand->getType()->getAs<PointerType>(); if (!pointerType) { QualType objectType = pointerOperand->getType() ->castAs<ObjCObjectPointerType>() ->getPointeeType(); llvm::Value *objectSize = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); index = CGF.Builder.CreateMul(index, objectSize); Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); result = CGF.Builder.CreateGEP(result, index, "add.ptr"); return CGF.Builder.CreateBitCast(result, pointer->getType()); } QualType elementType = pointerType->getPointeeType(); if (const VariableArrayType *vla = CGF.getContext().getAsVariableArrayType(elementType)) { // The element count here is the total number of non-VLA elements. llvm::Value *numElements = CGF.getVLASize(vla).first; // Effectively, the multiply by the VLA size is part of the GEP. // GEP indexes are signed, and scaling an index isn't permitted to // signed-overflow, so we use the same semantics for our explicit // multiply. We suppress this if overflow is not undefined behavior. if (CGF.getLangOptions().isSignedOverflowDefined()) { index = CGF.Builder.CreateMul(index, numElements, "vla.index"); pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); } else { index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); } return pointer; } // Explicitly handle GNU void* and function pointer arithmetic extensions. The // GNU void* casts amount to no-ops since our void* type is i8*, but this is // future proof. if (elementType->isVoidType() || elementType->isFunctionType()) { Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); result = CGF.Builder.CreateGEP(result, index, "add.ptr"); return CGF.Builder.CreateBitCast(result, pointer->getType()); } if (CGF.getLangOptions().isSignedOverflowDefined()) return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); } Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { if (op.LHS->getType()->isPointerTy() || op.RHS->getType()->isPointerTy()) return emitPointerArithmetic(CGF, op, /*subtraction*/ false); if (op.Ty->isSignedIntegerOrEnumerationType()) { switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { case LangOptions::SOB_Undefined: return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); case LangOptions::SOB_Defined: return Builder.CreateAdd(op.LHS, op.RHS, "add"); case LangOptions::SOB_Trapping: return EmitOverflowCheckedBinOp(op); } } if (op.LHS->getType()->isFPOrFPVectorTy()) return Builder.CreateFAdd(op.LHS, op.RHS, "add"); return Builder.CreateAdd(op.LHS, op.RHS, "add"); } Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { // The LHS is always a pointer if either side is. if (!op.LHS->getType()->isPointerTy()) { if (op.Ty->isSignedIntegerOrEnumerationType()) { switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { case LangOptions::SOB_Undefined: return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); case LangOptions::SOB_Defined: return Builder.CreateSub(op.LHS, op.RHS, "sub"); case LangOptions::SOB_Trapping: return EmitOverflowCheckedBinOp(op); } } if (op.LHS->getType()->isFPOrFPVectorTy()) return Builder.CreateFSub(op.LHS, op.RHS, "sub"); return Builder.CreateSub(op.LHS, op.RHS, "sub"); } // If the RHS is not a pointer, then we have normal pointer // arithmetic. if (!op.RHS->getType()->isPointerTy()) return emitPointerArithmetic(CGF, op, /*subtraction*/ true); // Otherwise, this is a pointer subtraction. // Do the raw subtraction part. llvm::Value *LHS = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); llvm::Value *RHS = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); // Okay, figure out the element size. const BinaryOperator *expr = cast<BinaryOperator>(op.E); QualType elementType = expr->getLHS()->getType()->getPointeeType(); llvm::Value *divisor = 0; // For a variable-length array, this is going to be non-constant. if (const VariableArrayType *vla = CGF.getContext().getAsVariableArrayType(elementType)) { llvm::Value *numElements; llvm::tie(numElements, elementType) = CGF.getVLASize(vla); divisor = numElements; // Scale the number of non-VLA elements by the non-VLA element size. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); if (!eltSize.isOne()) divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); // For everything elese, we can just compute it, safe in the // assumption that Sema won't let anything through that we can't // safely compute the size of. } else { CharUnits elementSize; // Handle GCC extension for pointer arithmetic on void* and // function pointer types. if (elementType->isVoidType() || elementType->isFunctionType()) elementSize = CharUnits::One(); else elementSize = CGF.getContext().getTypeSizeInChars(elementType); // Don't even emit the divide for element size of 1. if (elementSize.isOne()) return diffInChars; divisor = CGF.CGM.getSize(elementSize); } // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since // pointer difference in C is only defined in the case where both operands // are pointing to elements of an array. return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); } Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { // LLVM requires the LHS and RHS to be the same type: promote or truncate the // RHS to the same size as the LHS. Value *RHS = Ops.RHS; if (Ops.LHS->getType() != RHS->getType()) RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) { unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, llvm::ConstantInt::get(RHS->getType(), Width)), Cont, CGF.getTrapBB()); CGF.EmitBlock(Cont); } return Builder.CreateShl(Ops.LHS, RHS, "shl"); } Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { // LLVM requires the LHS and RHS to be the same type: promote or truncate the // RHS to the same size as the LHS. Value *RHS = Ops.RHS; if (Ops.LHS->getType() != RHS->getType()) RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) { unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, llvm::ConstantInt::get(RHS->getType(), Width)), Cont, CGF.getTrapBB()); CGF.EmitBlock(Cont); } if (Ops.Ty->hasUnsignedIntegerRepresentation()) return Builder.CreateLShr(Ops.LHS, RHS, "shr"); return Builder.CreateAShr(Ops.LHS, RHS, "shr"); } enum IntrinsicType { VCMPEQ, VCMPGT }; // return corresponding comparison intrinsic for given vector type static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, BuiltinType::Kind ElemKind) { switch (ElemKind) { default: llvm_unreachable("unexpected element type"); case BuiltinType::Char_U: case BuiltinType::UChar: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : llvm::Intrinsic::ppc_altivec_vcmpgtub_p; break; case BuiltinType::Char_S: case BuiltinType::SChar: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; break; case BuiltinType::UShort: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; break; case BuiltinType::Short: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; break; case BuiltinType::UInt: case BuiltinType::ULong: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; break; case BuiltinType::Int: case BuiltinType::Long: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; break; case BuiltinType::Float: return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; break; } return llvm::Intrinsic::not_intrinsic; } Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, unsigned SICmpOpc, unsigned FCmpOpc) { TestAndClearIgnoreResultAssign(); Value *Result; QualType LHSTy = E->getLHS()->getType(); if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { assert(E->getOpcode() == BO_EQ || E->getOpcode() == BO_NE); Value *LHS = CGF.EmitScalarExpr(E->getLHS()); Value *RHS = CGF.EmitScalarExpr(E->getRHS()); Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); } else if (!LHSTy->isAnyComplexType()) { Value *LHS = Visit(E->getLHS()); Value *RHS = Visit(E->getRHS()); // If AltiVec, the comparison results in a numeric type, so we use // intrinsics comparing vectors and giving 0 or 1 as a result if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { // constants for mapping CR6 register bits to predicate result enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; // in several cases vector arguments order will be reversed Value *FirstVecArg = LHS, *SecondVecArg = RHS; QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); BuiltinType::Kind ElementKind = BTy->getKind(); switch(E->getOpcode()) { default: llvm_unreachable("is not a comparison operation"); case BO_EQ: CR6 = CR6_LT; ID = GetIntrinsic(VCMPEQ, ElementKind); break; case BO_NE: CR6 = CR6_EQ; ID = GetIntrinsic(VCMPEQ, ElementKind); break; case BO_LT: CR6 = CR6_LT; ID = GetIntrinsic(VCMPGT, ElementKind); std::swap(FirstVecArg, SecondVecArg); break; case BO_GT: CR6 = CR6_LT; ID = GetIntrinsic(VCMPGT, ElementKind); break; case BO_LE: if (ElementKind == BuiltinType::Float) { CR6 = CR6_LT; ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; std::swap(FirstVecArg, SecondVecArg); } else { CR6 = CR6_EQ; ID = GetIntrinsic(VCMPGT, ElementKind); } break; case BO_GE: if (ElementKind == BuiltinType::Float) { CR6 = CR6_LT; ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; } else { CR6 = CR6_EQ; ID = GetIntrinsic(VCMPGT, ElementKind); std::swap(FirstVecArg, SecondVecArg); } break; } Value *CR6Param = Builder.getInt32(CR6); llvm::Function *F = CGF.CGM.getIntrinsic(ID); Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, ""); return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); } if (LHS->getType()->isFPOrFPVectorTy()) { Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, LHS, RHS, "cmp"); } else if (LHSTy->hasSignedIntegerRepresentation()) { Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, LHS, RHS, "cmp"); } else { // Unsigned integers and pointers. Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, LHS, RHS, "cmp"); } // If this is a vector comparison, sign extend the result to the appropriate // vector integer type and return it (don't convert to bool). if (LHSTy->isVectorType()) return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); } else { // Complex Comparison: can only be an equality comparison. CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); Value *ResultR, *ResultI; if (CETy->isRealFloatingType()) { ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, LHS.first, RHS.first, "cmp.r"); ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, LHS.second, RHS.second, "cmp.i"); } else { // Complex comparisons can only be equality comparisons. As such, signed // and unsigned opcodes are the same. ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, LHS.first, RHS.first, "cmp.r"); ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, LHS.second, RHS.second, "cmp.i"); } if (E->getOpcode() == BO_EQ) { Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); } else { assert(E->getOpcode() == BO_NE && "Complex comparison other than == or != ?"); Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); } } return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); } Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { bool Ignore = TestAndClearIgnoreResultAssign(); Value *RHS; LValue LHS; switch (E->getLHS()->getType().getObjCLifetime()) { case Qualifiers::OCL_Strong: llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); break; case Qualifiers::OCL_Autoreleasing: llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E); break; case Qualifiers::OCL_Weak: RHS = Visit(E->getRHS()); LHS = EmitCheckedLValue(E->getLHS()); RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); break; // No reason to do any of these differently. case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: // __block variables need to have the rhs evaluated first, plus // this should improve codegen just a little. RHS = Visit(E->getRHS()); LHS = EmitCheckedLValue(E->getLHS()); // Store the value into the LHS. Bit-fields are handled specially // because the result is altered by the store, i.e., [C99 6.5.16p1] // 'An assignment expression has the value of the left operand after // the assignment...'. if (LHS.isBitField()) CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); else CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); } // If the result is clearly ignored, return now. if (Ignore) return 0; // The result of an assignment in C is the assigned r-value. if (!CGF.getContext().getLangOptions().CPlusPlus) return RHS; // If the lvalue is non-volatile, return the computed value of the assignment. if (!LHS.isVolatileQualified()) return RHS; // Otherwise, reload the value. return EmitLoadOfLValue(LHS); } Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { llvm::Type *ResTy = ConvertType(E->getType()); // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. // If we have 1 && X, just emit X without inserting the control flow. bool LHSCondVal; if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { if (LHSCondVal) { // If we have 1 && X, just emit X. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); // ZExt result to int or bool. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); } // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. if (!CGF.ContainsLabel(E->getRHS())) return llvm::Constant::getNullValue(ResTy); } llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); CodeGenFunction::ConditionalEvaluation eval(CGF); // Branch on the LHS first. If it is false, go to the failure (cont) block. CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); // Any edges into the ContBlock are now from an (indeterminate number of) // edges from this first condition. All of these values will be false. Start // setting up the PHI node in the Cont Block for this. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, "", ContBlock); for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); PI != PE; ++PI) PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); eval.begin(CGF); CGF.EmitBlock(RHSBlock); Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); eval.end(CGF); // Reaquire the RHS block, as there may be subblocks inserted. RHSBlock = Builder.GetInsertBlock(); // Emit an unconditional branch from this block to ContBlock. Insert an entry // into the phi node for the edge with the value of RHSCond. if (CGF.getDebugInfo()) // There is no need to emit line number for unconditional branch. Builder.SetCurrentDebugLocation(llvm::DebugLoc()); CGF.EmitBlock(ContBlock); PN->addIncoming(RHSCond, RHSBlock); // ZExt result to int. return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); } Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { llvm::Type *ResTy = ConvertType(E->getType()); // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. // If we have 0 || X, just emit X without inserting the control flow. bool LHSCondVal; if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { if (!LHSCondVal) { // If we have 0 || X, just emit X. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); // ZExt result to int or bool. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); } // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. if (!CGF.ContainsLabel(E->getRHS())) return llvm::ConstantInt::get(ResTy, 1); } llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); CodeGenFunction::ConditionalEvaluation eval(CGF); // Branch on the LHS first. If it is true, go to the success (cont) block. CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); // Any edges into the ContBlock are now from an (indeterminate number of) // edges from this first condition. All of these values will be true. Start // setting up the PHI node in the Cont Block for this. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, "", ContBlock); for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); PI != PE; ++PI) PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); eval.begin(CGF); // Emit the RHS condition as a bool value. CGF.EmitBlock(RHSBlock); Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); eval.end(CGF); // Reaquire the RHS block, as there may be subblocks inserted. RHSBlock = Builder.GetInsertBlock(); // Emit an unconditional branch from this block to ContBlock. Insert an entry // into the phi node for the edge with the value of RHSCond. CGF.EmitBlock(ContBlock); PN->addIncoming(RHSCond, RHSBlock); // ZExt result to int. return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); } Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { CGF.EmitIgnoredExpr(E->getLHS()); CGF.EnsureInsertPoint(); return Visit(E->getRHS()); } //===----------------------------------------------------------------------===// // Other Operators //===----------------------------------------------------------------------===// /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified /// expression is cheap enough and side-effect-free enough to evaluate /// unconditionally instead of conditionally. This is used to convert control /// flow into selects in some cases. static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, CodeGenFunction &CGF) { E = E->IgnoreParens(); // Anything that is an integer or floating point constant is fine. if (E->isConstantInitializer(CGF.getContext(), false)) return true; // Non-volatile automatic variables too, to get "cond ? X : Y" where // X and Y are local variables. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) if (VD->hasLocalStorage() && !(CGF.getContext() .getCanonicalType(VD->getType()) .isVolatileQualified())) return true; return false; } Value *ScalarExprEmitter:: VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { TestAndClearIgnoreResultAssign(); // Bind the common expression if necessary. CodeGenFunction::OpaqueValueMapping binding(CGF, E); Expr *condExpr = E->getCond(); Expr *lhsExpr = E->getTrueExpr(); Expr *rhsExpr = E->getFalseExpr(); // If the condition constant folds and can be elided, try to avoid emitting // the condition and the dead arm. bool CondExprBool; if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { Expr *live = lhsExpr, *dead = rhsExpr; if (!CondExprBool) std::swap(live, dead); // If the dead side doesn't have labels we need, just emit the Live part. if (!CGF.ContainsLabel(dead)) { Value *Result = Visit(live); // If the live part is a throw expression, it acts like it has a void // type, so evaluating it returns a null Value*. However, a conditional // with non-void type must return a non-null Value*. if (!Result && !E->getType()->isVoidType()) Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); return Result; } } // OpenCL: If the condition is a vector, we can treat this condition like // the select function. if (CGF.getContext().getLangOptions().OpenCL && condExpr->getType()->isVectorType()) { llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); llvm::Value *LHS = Visit(lhsExpr); llvm::Value *RHS = Visit(rhsExpr); llvm::Type *condType = ConvertType(condExpr->getType()); llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); unsigned numElem = vecTy->getNumElements(); llvm::Type *elemType = vecTy->getElementType(); std::vector<llvm::Constant*> Zvals; for (unsigned i = 0; i < numElem; ++i) Zvals.push_back(llvm::ConstantInt::get(elemType, 0)); llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals); llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); llvm::Value *tmp = Builder.CreateSExt(TestMSB, llvm::VectorType::get(elemType, numElem), "sext"); llvm::Value *tmp2 = Builder.CreateNot(tmp); // Cast float to int to perform ANDs if necessary. llvm::Value *RHSTmp = RHS; llvm::Value *LHSTmp = LHS; bool wasCast = false; llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); if (rhsVTy->getElementType()->isFloatTy()) { RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); wasCast = true; } llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); if (wasCast) tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); return tmp5; } // If this is a really simple expression (like x ? 4 : 5), emit this as a // select instead of as control flow. We can only do this if it is cheap and // safe to evaluate the LHS and RHS unconditionally. if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); llvm::Value *LHS = Visit(lhsExpr); llvm::Value *RHS = Visit(rhsExpr); if (!LHS) { // If the conditional has void type, make sure we return a null Value*. assert(!RHS && "LHS and RHS types must match"); return 0; } return Builder.CreateSelect(CondV, LHS, RHS, "cond"); } llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); CodeGenFunction::ConditionalEvaluation eval(CGF); CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock); CGF.EmitBlock(LHSBlock); eval.begin(CGF); Value *LHS = Visit(lhsExpr); eval.end(CGF); LHSBlock = Builder.GetInsertBlock(); Builder.CreateBr(ContBlock); CGF.EmitBlock(RHSBlock); eval.begin(CGF); Value *RHS = Visit(rhsExpr); eval.end(CGF); RHSBlock = Builder.GetInsertBlock(); CGF.EmitBlock(ContBlock); // If the LHS or RHS is a throw expression, it will be legitimately null. if (!LHS) return RHS; if (!RHS) return LHS; // Create a PHI node for the real part. llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); PN->addIncoming(LHS, LHSBlock); PN->addIncoming(RHS, RHSBlock); return PN; } Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { return Visit(E->getChosenSubExpr(CGF.getContext())); } Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); // If EmitVAArg fails, we fall back to the LLVM instruction. if (!ArgPtr) return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); // FIXME Volatility. return Builder.CreateLoad(ArgPtr); } Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { return CGF.EmitBlockLiteral(block); } Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); llvm::Type *DstTy = ConvertType(E->getType()); // Going from vec4->vec3 or vec3->vec4 is a special case and requires // a shuffle vector instead of a bitcast. llvm::Type *SrcTy = Src->getType(); if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) { unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements(); unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements(); if ((numElementsDst == 3 && numElementsSrc == 4) || (numElementsDst == 4 && numElementsSrc == 3)) { // In the case of going from int4->float3, a bitcast is needed before // doing a shuffle. llvm::Type *srcElemTy = cast<llvm::VectorType>(SrcTy)->getElementType(); llvm::Type *dstElemTy = cast<llvm::VectorType>(DstTy)->getElementType(); if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy()) || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) { // Create a float type of the same size as the source or destination. llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy, numElementsSrc); Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast"); } llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); SmallVector<llvm::Constant*, 3> Args; Args.push_back(Builder.getInt32(0)); Args.push_back(Builder.getInt32(1)); Args.push_back(Builder.getInt32(2)); if (numElementsDst == 4) Args.push_back(llvm::UndefValue::get( llvm::Type::getInt32Ty(CGF.getLLVMContext()))); llvm::Constant *Mask = llvm::ConstantVector::get(Args); return Builder.CreateShuffleVector(Src, UnV, Mask, "astype"); } } return Builder.CreateBitCast(Src, DstTy, "astype"); } Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { return CGF.EmitAtomicExpr(E).getScalarVal(); } //===----------------------------------------------------------------------===// // Entry Point into this File //===----------------------------------------------------------------------===// /// EmitScalarExpr - Emit the computation of the specified expression of scalar /// type, ignoring the result. Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { assert(E && !hasAggregateLLVMType(E->getType()) && "Invalid scalar expression to emit"); if (isa<CXXDefaultArgExpr>(E)) disableDebugInfo(); Value *V = ScalarExprEmitter(*this, IgnoreResultAssign) .Visit(const_cast<Expr*>(E)); if (isa<CXXDefaultArgExpr>(E)) enableDebugInfo(); return V; } /// EmitScalarConversion - Emit a conversion from the specified type to the /// specified destination type, both of which are LLVM scalar types. Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy) { assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && "Invalid scalar expression to emit"); return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); } /// EmitComplexToScalarConversion - Emit a conversion from the specified complex /// type to the specified destination type, where the destination type is an /// LLVM scalar type. Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy) { assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && "Invalid complex -> scalar conversion"); return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, DstTy); } llvm::Value *CodeGenFunction:: EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre) { return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); } LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { llvm::Value *V; // object->isa or (*object).isa // Generate code as for: *(Class*)object // build Class* type llvm::Type *ClassPtrTy = ConvertType(E->getType()); Expr *BaseExpr = E->getBase(); if (BaseExpr->isRValue()) { V = CreateMemTemp(E->getType(), "resval"); llvm::Value *Src = EmitScalarExpr(BaseExpr); Builder.CreateStore(Src, V); V = ScalarExprEmitter(*this).EmitLoadOfLValue( MakeNaturalAlignAddrLValue(V, E->getType())); } else { if (E->isArrow()) V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); else V = EmitLValue(BaseExpr).getAddress(); } // build Class* type ClassPtrTy = ClassPtrTy->getPointerTo(); V = Builder.CreateBitCast(V, ClassPtrTy); return MakeNaturalAlignAddrLValue(V, E->getType()); } LValue CodeGenFunction::EmitCompoundAssignmentLValue( const CompoundAssignOperator *E) { ScalarExprEmitter Scalar(*this); Value *Result = 0; switch (E->getOpcode()) { #define COMPOUND_OP(Op) \ case BO_##Op##Assign: \ return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ Result) COMPOUND_OP(Mul); COMPOUND_OP(Div); COMPOUND_OP(Rem); COMPOUND_OP(Add); COMPOUND_OP(Sub); COMPOUND_OP(Shl); COMPOUND_OP(Shr); COMPOUND_OP(And); COMPOUND_OP(Xor); COMPOUND_OP(Or); #undef COMPOUND_OP case BO_PtrMemD: case BO_PtrMemI: case BO_Mul: case BO_Div: case BO_Rem: case BO_Add: case BO_Sub: case BO_Shl: case BO_Shr: case BO_LT: case BO_GT: case BO_LE: case BO_GE: case BO_EQ: case BO_NE: case BO_And: case BO_Xor: case BO_Or: case BO_LAnd: case BO_LOr: case BO_Assign: case BO_Comma: llvm_unreachable("Not valid compound assignment operators"); } llvm_unreachable("Unhandled compound assignment operator"); }
[ "ww345ww@gmail.com" ]
ww345ww@gmail.com
298e7eb3d4a17e0c348433a2747ceefe162ad867
10d5309b405167928db09bfce2381fd1b3a69b0c
/command/cmd_ws.cpp
d99f5dd81e801a6dae01ab09a413075278ff3885
[]
no_license
hoytech/overlay
5f25a50675cd29471d7689c3d2d81f92d26199af
578088194f92e2b1f5ebaec7e7db321a6248f79c
refs/heads/master
2023-05-14T09:04:24.760848
2019-11-10T07:17:55
2019-11-10T07:17:55
220,577,161
0
0
null
2023-05-07T05:53:25
2019-11-09T01:59:54
JavaScript
UTF-8
C++
false
false
7,295
cpp
#include <vector> #include <uWS/uWS.h> #include <tao/json.hpp> #include "overlay.h" #include "db.h" static const char *overlayDbPath = "./overlay.db/"; static const char *bindHost = "0.0.0.0"; static const int bindPort = 9777; namespace overlay { class WebsocketServer { public: void run() { ::mkdir(overlayDbPath, 0777); env.open(std::string(overlayDbPath)); hubGroup = hub.createGroup<uWS::SERVER>(uWS::PERMESSAGE_DEFLATE | uWS::SLIDING_DEFLATE_WINDOW); hubGroup->onConnection([this](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) { onConnection(ws, req); }); hubGroup->onDisconnection([this](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) { onDisconnection(ws, code, message, length); }); hubGroup->onMessage([this](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) { onMessage(ws, message, length, opCode); }); if (!hub.listen(bindHost, bindPort, nullptr, uS::REUSE_PORT, hubGroup)) throw overlay::error("unable to listen on port ", bindPort); std::cout << "Started websocket server" << std::endl; std::cout << " db = " << overlayDbPath << std::endl; std::cout << " listen = " << bindHost << ":" << bindPort << std::endl; hub.run(); } private: class Connection { public: Connection(uWS::WebSocket<uWS::SERVER> *p, uint64_t id) : websocket(p), connectionId(id) { } Connection(const Connection &) = delete; Connection(Connection &&) = delete; uWS::WebSocket<uWS::SERVER> *websocket; uint64_t connectionId; }; // Websocket thread void onConnection(uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) { uint64_t connId = nextConnId++; Connection *c = new Connection(ws, connId); ws->setUserData((void*)c); connIdToConnection.emplace(connId, c); } void onDisconnection(uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) { Connection *c = (Connection*)ws->getUserData(); uint64_t connectionId = c->connectionId; connIdToConnection.erase(connectionId); delete c; } void onMessage(uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) { auto &c = *(Connection*)ws->getUserData(); tao::json::value body; tao::json::value reply = tao::json::empty_object; try { std::string_view msg(message, length); body = tao::json::from_string(msg); if (body.optional<uint64_t>("id")) reply["id"] = body.as<uint64_t>("id"); processMsg(body, reply); } catch (std::exception &e) { reply["error"] = std::string("Error: ") + e.what(); } std::string replyStr = tao::json::to_string(reply); c.websocket->send(replyStr.data(), replyStr.size(), uWS::OpCode::TEXT); } std::string processMsg(tao::json::value &body, tao::json::value &reply) { std::string cmd = body.as<std::string>("cmd"); if (cmd == "add-zone") { auto txn = env.txn_rw(); uint64_t zoneId = overlay::db::get_next_integer_key(txn, env.dbi_zoneById); std::string zoneIdStr = std::string(lmdb::to_sv<uint64_t>(zoneId)); if (body.optional<std::string_view>("base")) { std::string base = from_hex(body.as<std::string_view>("base")); std::string_view baseZoneIdSv; if (!env.dbi_zoneByHash.get(txn, base, baseZoneIdSv)) throw overlay::error("unable to find base zone"); generic_foreach(env, txn, env.dbi_zone, [&](std::string_view k, std::string_view v){ if (k.substr(0, 8) != baseZoneIdSv) return false; std::string newKey = zoneIdStr + std::string(k.substr(8)); env.dbi_zone.put(txn, newKey, v); return true; }, false, baseZoneIdSv); } for (auto &item : body.at("items").get_array()) { std::string key = item.as<std::string>("key"); // FIXME: remove duplicate and trailing "/" chars key = zoneIdStr + key; std::string val = tao::json::to_string(item.at("val")); if (item.find("del")) { env.dbi_zone.del(txn, key, val); } else { env.dbi_zone.put(txn, key, val); } } std::string zoneHash = computeZoneHash(txn, zoneIdStr); std::string_view junkVal; if (env.dbi_zoneByHash.get(txn, zoneHash, junkVal)) { std::cout << "ZONE ALREADY EXISTS IN DB" << std::endl; txn.abort(); } else { env.dbi_zoneById.put(txn, zoneIdStr, zoneHash); env.dbi_zoneByHash.put(txn, zoneHash, zoneIdStr); txn.commit(); } reply["zoneHash"] = to_hex(zoneHash, true); } else if (cmd == "get-zone") { auto txn = env.txn_ro(); tao::json::value items = tao::json::empty_array; std::string zoneHash = from_hex(body.as<std::string_view>("zoneHash")); std::string_view zoneIdSv; if (!env.dbi_zoneByHash.get(txn, zoneHash, zoneIdSv)) throw overlay::error("unable to find zone"); std::string prefix = std::string(zoneIdSv); if (body.find("prefix")) prefix += body.as<std::string>("prefix"); generic_foreach(env, txn, env.dbi_zone, [&](std::string_view k, std::string_view v){ if (k.substr(0, prefix.size()) != prefix) return false; items.get_array().emplace_back(tao::json::value::array({ k.substr(8), tao::json::from_string(v), })); return true; }, false, prefix); reply["items"] = items; } else { throw overlay::error("unknown command: ", cmd); } return tao::json::to_string(reply); } std::string computeZoneHash(lmdb::txn &txn, const std::string &zoneIdStr) { // FIXME: compute merkle cache //std::vector<std::string> levels; //levels.push_back(""); std::string nodeHashes; generic_foreach(env, txn, env.dbi_zone, [&](std::string_view k, std::string_view v){ if (k.substr(0, 8) != zoneIdStr) return false; std::string keyHash = keccak256(k.substr(8)); std::string valHash = keccak256(v); std::string nodeHash = keccak256("\x01" + keyHash + valHash); nodeHashes += nodeHash; return true; }, false, zoneIdStr); return keccak256(nodeHashes); } overlay::db::environment env; // Websocket thread uWS::Hub hub; uWS::Group<uWS::SERVER> *hubGroup; std::unordered_map<uint64_t, Connection*> connIdToConnection; uint64_t nextConnId = 1; }; void cmd_ws() { WebsocketServer w; try { w.run(); } catch (std::exception &e) { std::cerr << "Fatal error: " << e.what() << std::endl; std::exit(1); } } }
[ "doug@hcsw.org" ]
doug@hcsw.org
777fc3cd668cf6a178cd9ca4bbfd0ddf395e59cc
782855ec588d462a3a3274671b6044b50e4beec7
/include/DSGeneratorRDMDecayGun.hh
73dbf9f9b824931c094361e8fbdb78029da19cc3
[]
no_license
liybu36/Montecarlo
28db7c19585f1ddecc4b11d5cf72c0424d9519fd
17c2b36a8b51eac34b5b0649c9fb39b5687019d8
refs/heads/master
2020-04-06T04:31:10.235172
2015-07-20T15:31:08
2015-07-20T15:31:08
24,011,192
0
1
null
null
null
null
UTF-8
C++
false
false
1,840
hh
// --------------------------------------------------------------------------// /** * AUTHOR: D. Franco * CONTACT: davide.franco@mi.infn.it */ // --------------------------------------------------------------------------// #ifndef _BXGENERATORRDMDecayGun_HH #define _BXGENERATORRDMDecayGun_HH //---------------------------------------------------------------------------// #include "G4GeneralParticleSource.hh" #include "G4ParticleDefinition.hh" #include "G4ThreeVector.hh" #include "Randomize.hh" #include "DSVGenerator.hh" #include "G4Event.hh" #include "DSGeneratorRDMNucleus.hh" #include "G4IonTable.hh" //---------------------------------------------------------------------------// class DSGeneratorRDMDecayGunMessenger ; class DSGeneratorRDMDecayGun : public DSVGenerator { public: //default constructor DSGeneratorRDMDecayGun(); //copy constructor //DSGeneratorRDMDecayGun(const DSGeneratorRDMDecayGun &); //destructor virtual ~DSGeneratorRDMDecayGun(); void SetNucleus(DSGeneratorRDMNucleus theIon1); // Sets the isotope. // DSGeneratorRDMNucleus GetNucleus() {return theIon;} // Returns the specified isotope. //public interface virtual void DSGeneratePrimaries(G4Event *event); //protected members //private members private: DSGeneratorRDMDecayGunMessenger* fTheMessenger; G4ParticleGun* fParticleGun; DSGeneratorRDMNucleus theIon; G4int fA ; G4int fZ; G4double fE ; G4bool IsFirst; G4ParticleDefinition* aIon; }; #endif /* * Revision 1.1 2013/03/22 13:50:09 dfranco * Added radioactive decay and radioactive decay chain generators. They require the correspondent stacking actions. Two mac files are included as examples * */
[ "hqian36@gmail.com" ]
hqian36@gmail.com
e22ca537bfadf41fab37e5aab8e209623049c0c5
231e075765a491fcd70a6074f939951b0199021b
/Src/Plugins/Dirt3Plugin/Dirt3Plugin/stdafx.cpp
6eae25aa1df95d5b787871c87b5c90fad10be47b
[ "MIT" ]
permissive
lattic/VRSimulator
3744fbe405613cb91833a16f7884ae6b1f7aa9b2
c3f8cee3f6b284343b63942ac2a92951b4c52078
refs/heads/master
2023-08-07T02:46:54.613248
2016-12-31T12:50:34
2016-12-31T12:50:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
// stdafx.cpp : source file that includes just the standard includes // Dirt3Plugin.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "jjuiddong@gmail.com" ]
jjuiddong@gmail.com
179b625bf84c80fe3298582580c67d4ed22408f3
c9299dd54ecf7b269fe52b5c28997c4775792e4e
/mainTest.cpp
7488e1e73ea425a6e4bd0901ed71bea0d5109744
[]
no_license
UKoksal/C-Compiler-and-Translator
9aa3eb48df034a260e054772cdbc5e21defa43b8
8dfe11aba81d414b108f7a14905a4d44062f6503
refs/heads/main
2022-12-25T04:39:45.891132
2020-10-12T19:44:03
2020-10-12T19:44:03
303,493,319
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
#include "parser.hpp" #include<iostream> int main(){ const Program* ast=parseAST(); std::cout << "done \n"; ast->print(std::cout); } /*int main(){ while(1){ tokenType type = (tokenType)yylex(); std::cout << "\n token type " << type << "\n"; if(type == None){ break; } } }*/
[ "utku.koksal@hotmail.com" ]
utku.koksal@hotmail.com
c201a097cc794a87e1b918cd08595fb94ec77891
44a32537c6025e85d1f8440e960b35189441a48b
/src/rpcwallet.cpp
166c03566920b10a7eb604a0328988093c45a85a
[ "MIT" ]
permissive
GladCoin/gladcoin-source
098c1197e4a24e3ab61091e45cd750cd4d5e1817
fb0a6157902e632a8320191872b768f25b6c607e
refs/heads/master
2021-08-26T09:13:41.412574
2017-11-22T20:35:56
2017-11-22T20:35:56
111,729,659
0
0
null
null
null
null
UTF-8
C++
false
false
61,881
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace json_spirit; using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); static void accountingDeprecationCheck() { if (!GetBoolArg("-enableaccounts", false)) throw runtime_error( "Accounting API is deprecated and will be removed in future.\n" "It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n" "If you still want to enable it, add to your config file enableaccounts=1\n"); if (GetBoolArg("-staking", true)) throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n"); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj, diff; obj.push_back(Pair("version", FormatFullVersion())); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset())); obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply))); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP())); diff.push_back(Pair("proof-of-work", GetDifficulty())); diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("difficulty", diff)); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); vector<unsigned char> vchPubKey = newKey.Raw(); return HexStr(vchPubKey.begin(), vchPubKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new GladCoin address for receiving payments. " "If [account] is specified, it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current GladCoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <gladcoinaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GladCoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <gladcoinaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GladCoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <gladcoinaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GladCoin address"); // Amount int64_t nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <gladcoinaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <gladcoinaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <gladcoinaddress> [minconf=1]\n" "Returns the total amount received by <gladcoinaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GladCoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); accountingDeprecationCheck(); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64_t nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!IsFinalTx(wtx) || wtx.GetDepthInMainChain() < 0) continue; int64_t nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64_t GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number. int64_t nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsTrusted()) continue; int64_t allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } accountingDeprecationCheck(); string strAccount = AccountFromValue(params[0]); int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); accountingDeprecationCheck(); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64_t nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <togladcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid GladCoin address"); int64_t nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64_t> > vecSend; int64_t totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid GladCoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64_t nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a GladCoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value addredeemscript(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) { string msg = "addredeemscript <redeemScript> [account]\n" "Add a P2SH address with a specified redeemScript to the wallet.\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Construct using pay-to-script-hash: vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript"); CScript inner(innerData.begin(), innerData.end()); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64_t nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64_t nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64_t nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); accountingDeprecationCheck(); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { bool stop = false; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase() || wtx.IsCoinStake()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } if (!wtx.IsCoinStake()) entry.push_back(Pair("amount", ValueFromAmount(r.second))); else { entry.push_back(Pair("amount", ValueFromAmount(-nFee))); stop = true; // only one coinstake output } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } if (stop) break; } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); accountingDeprecationCheck(); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64_t> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64_t nCredit = wtx.GetCredit(); int64_t nDebit = wtx.GetDebit(); int64_t nNet = nCredit - nDebit; int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill [new-size]\n" "Fills the keypool." + HelpRequiringPassphrase()); unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0); if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size"); nSize = (unsigned int) params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(nSize); if (pwalletMain->GetKeyPoolSize() < nSize) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("gladcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("gladcoin-lock-wa"); int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64_t nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64_t*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [stakingonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "if [stakingonly] is true sending functions are disabled."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64_t* pnSleepTime = new int64_t(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); // ppcoin: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockStakingOnly = params[2].get_bool(); else fWalletUnlockStakingOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; GladCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <gladcoinaddress>\n" "Return information about <gladcoinaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value validatepubkey(const Array& params, bool fHelp) { if (fHelp || !params.size() || params.size() > 2) throw runtime_error( "validatepubkey <gladcoinpubkey>\n" "Return information about <gladcoinpubkey>."); std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str()); CPubKey pubKey(vchPubKey); bool isValid = pubKey.IsValid(); bool isCompressed = pubKey.IsCompressed(); CKeyID keyID = pubKey.GetID(); CBitcoinAddress address; address.Set(keyID); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); ret.push_back(Pair("iscompressed", isCompressed)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } // ppcoin: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64_t nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); nReserveBalance = nAmount; } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); nReserveBalance = 0; } } Object result; result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // ppcoin: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // ppcoin: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // NovaCoin: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(true); return Value::null; } // ppcoin: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw()))); return result; }
[ "33889144+GladCoin@users.noreply.github.com" ]
33889144+GladCoin@users.noreply.github.com
51f4558f802d44af48c476c2ca39eac2faa4840f
1c6ff5eaba4232d0a61959c9117723fa9de42b2e
/HTMLEl.cc
a5974aa52fb64b260e690cab50c4918f34a256ca
[]
no_license
birdatdotty/untitled38
5059750f5c680b3ca4905670cde394b3ccf0050e
86a0a031481b1d84acbaf1afaec55ab00ffcb908
refs/heads/master
2020-06-25T11:48:50.365120
2019-07-28T21:01:01
2019-07-28T21:01:01
199,300,458
1
0
null
null
null
null
UTF-8
C++
false
false
2,148
cc
#include "HTMLEl.h" #include <QDebug> HTMLEl::HTMLEl(QObject */*parent*/) { tab = 2; } QString HTMLEl::out() { QString blocksStr; QString optStr;// = HTMLEl::getOpts(); for (QString key: optsMap.keys()) optStr += optsMap[key]; for (HTMLBlock* i: children) { blocksStr += i->out(); } int calculateCount = parent ? parent->tabCount() : 0; QString ret; if (children.size() > 0) ret = QString(" ").repeated(calculateCount) + "<" + typeName + optStr + ">\n" + blocksStr + QString(" ").repeated(calculateCount) + "</" + typeName + ">\n"; else ret = QString(" ").repeated(calculateCount) + "<" + typeName + optStr + ">" + text + "</" + typeName + ">\n"; return ret; } int HTMLEl::tabCount() { if (parent == nullptr) return tab; else return tab + parent->tabCount(); } QString HTMLEl::getOpts(QString optStr) { if (id.size() > 0) optStr += " id='" + id + "'"; if (className.size() > 0) optStr += " class='" + className + "'"; if (dataTarget.size() > 0) optStr += " data-target='" + dataTarget + "'"; if (dataToggle.size() > 0) optStr += " data-toggle='" + dataToggle + "'"; if (ariaControls.size() > 0) optStr += " aria-controls='" + ariaControls + "'"; if (ariaExpanded.size() > 0) optStr += " aria-expanded='" + ariaExpanded + "'"; if (ariaLabel.size() > 0) optStr += " aria-label='" + ariaLabel + "'"; if (ariaLabelledby.size() > 0) optStr += " aria-labelledby='" + ariaLabelledby + "'"; if (role.size() > 0) optStr += " role='" + role + "'"; if (type.size() > 0) optStr += " type='" + type + "'"; if (dataRide.size() > 0) optStr += " data-ride='" + dataRide + "'"; if (tabindex.size() > 0) optStr += " tabindex='" + tabindex + "'"; if (ariaHidden.size() > 0) optStr += " aria-hidden='" + ariaHidden + "'"; if (dataDismiss.size() > 0) optStr += " data-dismiss='" + dataDismiss + "'"; if (dataSpy.size() > 0) optStr += " data-spy='" + dataSpy + "'"; if (dataOffset.size() > 0) optStr += " data-offset='" + dataOffset + "'"; return optStr; }
[ "bird@dotty.su" ]
bird@dotty.su
085dde660d8835c91fa9028c0156ee77da6d5f5e
ab355575208d7880057cf1f10b969e7770079c49
/SimpleReflection/Utilities.hpp
8d40ab741f5f575484c56c0e62c0078b838ef035
[ "MIT" ]
permissive
playmer/SimpleReflection
56ae45c0e192605eb3990e08c7f697ae57a1dd1a
76779053353d7497f5bab8f5307ea63f2107a618
refs/heads/master
2020-06-20T02:10:30.452338
2019-07-21T00:45:53
2019-07-21T00:45:53
196,955,295
0
0
null
null
null
null
UTF-8
C++
false
false
2,235
hpp
#pragma once #ifndef YTE_StandardLibrary_Utilities_hpp #define YTE_StandardLibrary_Utilities_hpp #include <cstdint> #include <cstddef> #include <cstring> #include <memory> #include <string> #include <unordered_map> //#include "YTE/Platform/TargetDefinitions.hpp" namespace srefl { using byte = std::uint8_t; using s8 = signed char; using s16 = signed short; using s32 = signed int; using s64 = signed long long; using i8 = char; using i16 = std::int16_t; using i32 = std::int32_t; using i64 = std::int64_t; using u8 = std::uint8_t; using u16 = std::uint16_t; using u32 = std::uint32_t; using u64 = std::uint64_t; inline void runtime_assert(bool aValue, const char *aMessage = "") { if (false == aValue) { printf("ASSERT: %s\n", aMessage); // Intentionally crashing the program. int *base = nullptr; *base = 1; } } // We want to be able to use the string literals, this is the only way. using namespace std::string_literals; enum class StringComparison { String1Null, // (We check this first) LesserInString1, // The first character that does not match has a lower value in ptr1 than in ptr2 Equal, GreaterInString1,// The first character that does not match has a greater value in ptr1 than in ptr2 String2Null, // (We check this Second) }; inline StringComparison StringCompare(const char *aLeft, const char *aRight) { if (nullptr == aLeft) { return StringComparison::String1Null; } if (nullptr == aRight) { return StringComparison::String2Null; } auto comparison = std::strcmp(aLeft, aRight); if (0 == comparison) { return StringComparison::Equal; } if (comparison < 0) { return StringComparison::LesserInString1; } // else if (comparison < 0) This is by definition of the domain, no need to check { return StringComparison::GreaterInString1; } } template <typename ...tArguments> inline void UnusedArguments(tArguments const &...) { } template <typename tTo = std::size_t, typename tEnum = int> constexpr inline tTo EnumCast(tEnum aValue) { return static_cast<tTo>(aValue); } } #endif
[ "playmer@gmail.com" ]
playmer@gmail.com
e4294472f7e875f5b6713d546a56601217a18cbb
4be6611431e4ff6d53ad00df164646c7bce1c6b2
/codeforces/Helvetic Coding Contest 2017/B. Heidi and Library (medium)/main.cpp
36499f8fd6589dd74defc2bf8be1ca01a1879230
[]
no_license
cheerconi/online-judge
98d0a8353cf80ade292cf8edfba3d02474a80b67
46cc0f35f2f66aac520557c511484393cf16888b
refs/heads/master
2022-09-22T13:24:38.477277
2022-09-18T12:26:53
2022-09-18T12:26:53
97,737,698
3
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <vector> #include <set> #include <iostream> using namespace std; int main() { // freopen("test.txt", "r", stdin); int n, k; scanf("%d%d", &n, &k); vector<int> seq(n, 0); for (int i = 0; i < n; i++) scanf("%d", &seq[i]); vector<int> next(n, 0); vector<int> now(n+1, -1); for (int i = n-1; i >= 0; i--) { next[i] = now[seq[i]]; now[seq[i]] = i; } set<int> pos; int cnt = 0; for (int i = 0; i < n; i++) { if (pos.count(i) == 0) { if (pos.size() == k) { pos.erase(--pos.end()); } cnt++; } else { pos.erase(i); } if (next[i] != -1) pos.insert(next[i]); } cout << cnt << endl; }
[ "cheerconi@163.com" ]
cheerconi@163.com
ab35d18f2a20a6b1056bb9788ec77e9ba607f02e
792b2bbb3bcfc522e46441af029f50c5016a7c60
/languages-of-programming-cpp/1-laboratory-work/functions.cpp
7a6d5a672ccc0ea2c0921dbec73f4005c0e21223
[ "MIT" ]
permissive
bekzodbuyukov/university-tasks
b5c9e1e2d50e66c14651c50037ec7224c7eef34a
1efcc54e0c1b4f69c3c8f666cf144a4d5eed6da7
refs/heads/master
2023-01-13T01:37:46.341685
2020-11-19T12:04:49
2020-11-19T12:04:49
295,685,928
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
8,165
cpp
// // Created by bek on 12.09.2020. // #include "header.h" #define SEARCH_NOT_FOUND "Совпадений не найдено..." #define ID_SIZE 2 #define FULL_NAME_SIZE 30 #define YEAR_OF_BIRTH_SIZE 5 #define MEDICINE_CARD_NUMBER_SIZE 5 #define DIAGNOSIS_SIZE 50 // BEGIN: STABLE CODE // function for setting object data void TPatient::set() { cout << ".:: Введите данные пациента ::." << endl; setIndex(1); string newFullName; cout << "ФИО: "; cin.get(); getline(cin, newFullName); setFullName(newFullName); int newYearOfBirth; cout << "Год рождения: "; cin >> newYearOfBirth; setYearOfBirth(newYearOfBirth); int newMedicineCardNumber; cout << "Номер медицинской карты: "; cin >> newMedicineCardNumber; setMedicineCardNumber(newMedicineCardNumber); string newDiagnosis; cout << "Диагноз: "; cin.get(); getline(cin, newDiagnosis); setDiagnosis(newDiagnosis); } // function for printing object data void TPatient::printObjectData() const { cout << left << setw(ID_SIZE) << getIndex() << setw(FULL_NAME_SIZE) << getFullName() << setw(YEAR_OF_BIRTH_SIZE) << getYearOfBirth() << setw(MEDICINE_CARD_NUMBER_SIZE) << getMedicineCardNumber() << setw(DIAGNOSIS_SIZE) << getDiagnosis() << endl; } // function for copying data from structure directly to Class void TPatient::copy_data_from_struct(const TPatientStruct& Temp) { setFullName(Temp.fullName); setYearOfBirth(Temp.yearOfBirth); setMedicineCardNumber(Temp.medicineCardNumber); setDiagnosis(Temp.diagnosis); } // function for recording data as a table to file void TPatient::recordObjectDataToFile(ofstream& file) const { file << left << setw(ID_SIZE) << getIndex() << setw(FULL_NAME_SIZE) << getFullName() << setw(YEAR_OF_BIRTH_SIZE) << getYearOfBirth() << setw(MEDICINE_CARD_NUMBER_SIZE) << getMedicineCardNumber() << setw(DIAGNOSIS_SIZE) << getDiagnosis() << endl; //file.close(); } // overloading of operator '<' bool operator<(const TPatient& lhs, const TPatient& rhs) { return lhs.getYearOfBirth() < rhs.getYearOfBirth(); } // overloading of operator '>' bool operator>(const TPatient& lhs, const TPatient& rhs) { return rhs.getYearOfBirth() < lhs.getYearOfBirth(); } // function for returning file, which is opened for writing data in it ofstream openFileForWriting() { string fileName; cout << "Введите называние .txt файла: "; cin.get(); getline(cin, fileName); ofstream writingFile(fileName + ".txt", ios::ate); if (!writingFile) { cout << "Не удалось открыть файл для записи..." << endl; } return writingFile; } // function for returning file, which is opened for reading data from it ifstream openFileForReading() { string fileName; cout << "Введите называние .txt файла: "; cin.get(); getline(cin, fileName); cout << fileName + ".txt" << endl; ifstream readingFile(fileName + ".txt"); if (!readingFile) { cout << "Не удалось открыть файл для чтения..." << endl; } return readingFile; } // function return future array size, which was read from file int getArraySize(ifstream& file) { int size; bool status = true; while (status) { file >> size; status = false; } return size; } // function for writing data as a table to file, gets array void recordDataTableToFile(TPatient array[], int size, ofstream& openedFile) { for (int i = 0; i < size; ++i) { // array[i].setIndex(i); array[i].recordObjectDataToFile(openedFile); } openedFile.close(); } // function for filtering and printing data by given diagnosis and range of year of birth void filterByDiagnosisAndYearOfBirth(TPatient* array, int size) { string neededDiagnosis; cout << "Необходимый диагноз: "; cin.get(); getline(cin, neededDiagnosis); int fromYearOfBirth; cout << "Год рождения от: "; cin >> fromYearOfBirth; int toYearOfBirth; cout << "Год рождения от: "; cin >> toYearOfBirth; cout << "Результат:" << endl; int counter = 0; for (int i = 0; i < size; ++i) { if (array[i].getDiagnosis() == neededDiagnosis) { if (array[i].getYearOfBirth() >= fromYearOfBirth && array[i].getYearOfBirth() <= toYearOfBirth) { array[i].printObjectData(); counter += 1; } } } if (counter == 0) { cout << SEARCH_NOT_FOUND << endl; } } // function for filtering and printing data by medicine card number (prints data which has number in given range) void filterByMedicineCardNumber(TPatient* array, int size) { int fromMedicineCardNumber; cout << "Номер мед. карты от: "; cin >> fromMedicineCardNumber; int toMedicineCardNumber; cout << "Номер мед. карты до: "; cin >> toMedicineCardNumber; cout << "Результат:" << endl; int counter = 0; for (int i = 0; i < size; ++i) { if (array[i].getMedicineCardNumber() > fromMedicineCardNumber && array[i].getMedicineCardNumber() < toMedicineCardNumber) { array[i].printObjectData(); counter += 1; } } if (counter == 0) { cout << SEARCH_NOT_FOUND << endl; } } // function for filtering and printing data by year of birth (prints data which has number greater than given) void filterByYearOfBirth(TPatient* array, int size) { int afterYearOfBirth; cout << "Год рождения после: "; cin >> afterYearOfBirth; cout << "Результат:" << endl; int counter = 0; for (int i = 0; i < size; ++i) { if (array[i].getYearOfBirth() > afterYearOfBirth) { array[i].printObjectData(); counter += 1; } } if (counter == 0) { cout << SEARCH_NOT_FOUND << endl; } } // function for filling data to array of objects from file (uses structures and function which works which structure) TPatient* fillFromFile(ifstream& file, int size) { struct TPatientStruct Temp; auto* array = new TPatient[size]; string surname, other_name; for (int i = 0; i < size; i++) { file >> Temp.fullName >> surname >> other_name >> Temp.yearOfBirth >> Temp.medicineCardNumber >> Temp.diagnosis; Temp.fullName += " " + surname; Temp.fullName += " " + other_name; array[i].copy_data_from_struct(Temp); } file.close(); return array; } // function for printing data of array void printData(TPatient array[], int size) { for (int i = 0; i < size; ++i) { array[i].setIndex(i + 1); array[i].printObjectData(); } } // function for sorting array by given year of birth in '>' (increasing) mode [NOT OPTIMISED] void sortByYearOfBirthIncreasingMode(TPatient* array, int size) { int i, j; TPatient tempObject; // Bubble Sort Algorithm for (i = 0; i < size; ++i) { for (j = size - 1; j > i; --j) { if (array[j - 1] > array[j]) { tempObject = array[j - 1]; array[j - 1] = array[j]; array[j] = tempObject; } } } for (i = 0; i < size; ++i) { array[i].printObjectData(); } } // function for sorting array by given year of birth in '<' (decreasing) mode [NOT OPTIMISED] void sortByYearOfBirthDecreasingMode(TPatient* array, int size) { int i, j; TPatient tempObject; // Bubble Sort Algorithm for (i = 0; i < size; ++i) { for (j = size - 1; j > i; --j) { if (array[j - 1] < array[j]) { tempObject = array[j - 1]; array[j - 1] = array[j]; array[j] = tempObject; } } } for (i = 0; i < size; ++i) { array[i].printObjectData(); } } // END: STABLE CODE
[ "bek.buyukov@gmail.com" ]
bek.buyukov@gmail.com
eaacdadf70297988ddd2f4c9863db3eede5f1871
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/Blindmode/CPP/Targets/Wayfinder/symbian-r6/VectorMapContainer.h
0267c2cbd1d7923863770b13c6fabc07ea3c12d6
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,451
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef VECTORMAPCONTAINER_H #define VECTORMAPCONTAINER_H // INCLUDES #include <coecntrl.h> #include <vector> #include <map> #include "config.h" #include "PictureContainer.h" #include "WayFinderConstants.h" #include "Log.h" #include "TileMapToolkit.h" #include "CursorHolder.h" #include "MC2Coordinate.h" #include "TileMapInfoCallback.h" #include "VisibilityAdapter.h" #include "ScalableFonts.h" // FORWARD DECLARATIONS //Only for types in other namespaces than the global one. Other are //best declared in place. namespace isab { class DataGuiMess; } // CLASS DECLARATION /** * CVectorMapContainer container control class. * */ class CVectorMapContainer : public CCoeControl, public MCoeControlObserver, public PictureContainer, public TileMapTimerListener, public CursorHolder, public TileMapInfoCallback { public: // Constructors and destructor /** * Constructor. */ CVectorMapContainer( class CMapView* aMapView, isab::Log* aLog ); /** * EPOC default constructor. * @param aRect Frame rectangle for container. */ void ConstructL( const TRect& aRect, class CWayFinderAppUi* aWayFinderUI, class CTileMapControl* aMapControl, class CMapFeatureHolder* aFeatureHolder, class CMapInfoControl* aMapInfoControl, class CVectorMapConnection* aVectorMapConnection, const TDesC& aResourcePath); /** * Destructor. */ ~CVectorMapContainer(); public: TBool ShowingInfoText(); public: ///@name Functions from Symbian base classes ///@name From CCoeControl //@{ TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType); void HandlePointerEventL( const TPointerEvent& aPointerEvent ); private: void SizeChanged(); TInt CountComponentControls() const; class CCoeControl* ComponentControl(TInt aIndex) const; void Draw(const TRect& aRect) const; //@} ///@name From MCoeControlObserver //@{ // event handling section // e.g Listbox events void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType); TCoeInputCapabilities InputCapabilities() const; /** * From CCoeControl * Handles layout awarness */ void HandleResourceChange(TInt aType); //@} //@} public: ///@name From PictureContainer //@{ void PictureError( TInt aError ); void ScalingDone(); //@} public: // New functions enum ZoomScale{ EScaleMin = 1, EScale1 = 2, EScale2 = 4, EScale3 = 10, EScale4 = 20, EScale5 = 50, EScale6 = 100, EScale7 = 500, EScale8 = 1000, EScale9 = 2000, EScale10 = 5000, EScale11 = 10000, EScale12 = 14000, EScaleGlobe = 100000 }; /** * Returns true if we are done with ConstructL */ TBool ConstructDone(); void SetConStatusImage(CFbsBitmap* aConStatusBitmap, CFbsBitmap* aConStatusMask); void SetGpsStatusImage(CFbsBitmap* aGpsStatusBitmap, CFbsBitmap* aGpsStatusMask); /* void SetTurnImage(CFbsBitmap* aTurnBitmap, CFbsBitmap* aTurnMask); */ void SetTopBorder(); void HideTopBorder(); void SetTurnPictureL( TInt aMbmIndex ); /*void SetTurnPicture( TPictures aTurn, TDesC &aFullPath, TBool aRightTraffic );*/ //void HideTurnPicture(); void SetDetourPicture(TInt on); void SetSpeedCamPicture(TInt on); void SetDistanceL( TUint aDistance ); void Connect(); void UpdateRepaint(); void SetFullScreen( TBool aFullScreen ); TBool IsFullScreen(); void SetCenter( TInt32 aLat, TInt32 aLon ); void SetRotation( TInt aHeading ); void ResetRotation(); void RequestMarkedPositionMap( TPoint aPos ); void RequestPositionMap( TPoint aPos ); void SetRoute( TInt64 aRouteId ); void ClearRoute( ); void RequestRouteMap( TPoint aTl, TPoint aBr ); void SetZoom( TInt aScale ); void ZoomToOverview(); void CheckFavoriteRedraw(); void ZoomIn(); void ZoomOut(); void ShowUserPos( TBool aShow ); void ResetNorthArrowPos(); void ShowNorthArrow( TBool aShow ); void ShowScale( TBool aShow ); void ShowStart( TBool aShow, TInt32 aLat, TInt32 aLon ); void ShowEnd( TBool aShow, TInt32 aLat, TInt32 aLon ); void ShowPoint( TBool aShow, TInt32 aLat, TInt32 aLon ); void GetCoordinate( TPoint& aRealCoord ); void GetCoordinate( MC2Coordinate& aMC2Coord ); void ShowFeatureInfo(); HBufC* GetServerStringL(); /** * Sets info text. * * @param hideAfterMS If specified, the info text will be shown * this many milliseconds and then be hidden. */ void setInfoText(const char *txt, const char *left = NULL, const char *right = NULL, TBool persistant = EFalse, uint32 hideAfterMS = MAX_UINT32 ); TBool IsInfoTextOn(); void ShowDetailedFeatureInfo(TBool showWithList = EFalse); /* void ShowPopupListL(); */ const unsigned char* GetFeatureName(); /// @return If the cursor should be visible or not. bool getCursorVisibility() const; /// Implements the abstract method from TileMapInfoCallback. void notifyInfoNamesAvailable(); /// Check if the cursor should be shown or not. void updateCursorVisibility(); /// Get the active point on the map. class MC2Point getActivePoint() const; TInt GetScale(); /// Set the tracking mode and type. void setTrackingMode( TBool aOnOff, TrackingType aType ); // Show a wait symbol for the vector maps. void ShowVectorMapWaitSymbol( bool start ); /// Handle the timers. void timerExpired( uint32 id ); /** * Set a new gps position. * * @param coord The coordinate of the new gps position. * @param direction The angle (360 degrees). * @param scale The scalelevel (dependent on the * speed). * @return If the map was updated due to the new gps position. */ bool setGpsPos( const MC2Coordinate& coord, int direction, int scale ); /** * Set iMapControl and others to NULL since it is deleted by MapView. */ void SetMapControlsNull(); private: // New functions /** * Get the tracking point, * i.e. the point on the screen of the gps symbol. */ class MC2Point getTrackingPoint() const; /** * Get the active point on the screen when leaving tracking. */ class MC2Point getNonTrackingPoint( bool screenSizeChanged = false ) const; /* key timer callback */ static TInt KeyCallback(TAny* aThisPtr) { CVectorMapContainer* thisPtr = (CVectorMapContainer*) aThisPtr; thisPtr->TimerHandler(); return(1); } /* Timer handler */ void TimerHandler(); TInt GetLogicalFont(enum TScalableFonts fontId, class TFontSpec& fontSpec); /** * Sets the fonts used for text placement in the TileMapHandler. */ void setTileMapFonts(); /** * Init the keyhandler and cursor. */ void initKeyHandler(); /** * Called when focus changes. */ void FocusChanged( TDrawNow aDrawNow ); void BindMovementKeys(TBool aLandscapeMode); private: //data class CMapView* iView; class CWayFinderAppUi * iWayFinderUI; /// Map control class CTileMapControl* iMapControl; VisibilityAdapter<class CTileMapControl>* iMapControlVisAdapter; /// Interfaces to TileMapHandler. class MapMovingInterface* iMapMovingInterface; class MapDrawingInterface* iMapDrawingInterface; class MapComponentWrapper* iGlobeComponent; class CCoeControl* iGlobeControl; VisibilityAdapter<class CCoeControl>* iGlobeControlVisAdapter; class MapSwitcher* iMapSwitcher; VisibilityAdapter<class CMapBorderBar>* iTopBorderVisAdapter; VisibilityAdapter<class CBitmapControl>* iGpsStatusVisAdapter; VisibilityAdapter<class CBitmapControl>* iConStatusVisAdapter; class CursorVisibilityAdapter* iCursorVisAdapter; //True if the details window is showing TBool iShowingDetails; /// True, if start menu command has been issued TBool iIsConnected; /// True if we start vectormap container for the first time. TBool iSetStartupPos; /// Object that handles the key repetitions etc. class TileMapKeyHandler* m_keyHandler; /// Tracking on timer. Formerly key timer. CPeriodic* m_autoTrackingOnTimer; /// The view rect for normal mode TRect iNormalRect; /// Flag for full screen mode TBool iIsFullScreen; /// the movement, rotation and zoom delta values int32 iMovDelta; int32 iRotDelta; float32 iZoomInFactor; float32 iZoomOutFactor; class CMapFeatureHolder* iFeatureHolder; TInt m_timerPeriod; #ifdef NAV2_CLIENT_SERIES60_V3 VisibilityAdapter<class CImageHandler>* iDetourPictureVisAdapter; VisibilityAdapter<class CImageHandler>* iSpeedCamPictureVisAdapter; #else VisibilityAdapter<class CGuidePicture>* iDetourPictureVisAdapter; VisibilityAdapter<class CGuidePicture>* iSpeedCamPictureVisAdapter; #endif enum { /// Maximum length allowed for the text in the distance control. KVMCMaxDistLen = 32 }; isab::Log* iLog; /// Keep track of when ConstructL has completed intierly. TBool iConstructDone; /// If the info text is shown at all. TBool iInfoTextShown; /// If detailed info text is shown. bool m_detailedInfoTextShown; TBool iInfoTextPersistant; /// The type of the struct used for key bindings. typedef struct TKeyBinding { /// Symbian key int first; /// TileMapKeyHandler key. int second; } key_array_pair_t; /// Unsorted key bindings. static const key_array_pair_t c_keyBindings[]; static const key_array_pair_t c_landscapeKeyBindings[]; static const key_array_pair_t c_portraitKeyBindings[]; /// Sorted key bindings. std::map<int,int> m_keyMap; /// Callback to be able to fixup the favourites etc. class CVectorMapContainerKeyHandlerCallBack* m_khCallBack; /// The cursor sprite. class SpriteMover* m_cursorSprite; /// The higlighted cursor sprite. class SpriteMover* m_highlightCursorSprite; /// The cursor. class CursorSprite* m_cursor; /// Control for viewing feature map info (the blue note). class CMapInfoControl* m_mapInfoControl; /// Timer used to hide the blue note with feature info after a while. uint32 m_hideInfoTimerID; /// The map mover. class MapMover* m_mapMover; TPoint iCenter; int32 iScale; }; #endif // End of File
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
91f4dbc584536b00577f6a3b0de5118699bddb0c
dc38a39ddaa88b01353d28daecf133e77b04a6be
/codeforces/edu_98/p5.cpp
cccbe2552ba812ca96ebd76e7a0ea4a750a33c82
[]
no_license
alexriderspy/Competitive-Programming
de57a7a5af617f979063d528ca0ae12c22f29036
30c1809800411a361d557a4e98921c6fdc0eb7b2
refs/heads/main
2023-06-01T02:12:19.587635
2021-07-09T04:06:21
2021-07-09T04:06:21
384,316,770
0
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n,m,k; cin>>n>>m>>k; vector<pair<int,int> >v; for(int i=1;i<=n;i++){ int s,e;cin>>s>>e; v.push_back({s,1}),v.push_back({e,-1}); } sort(v.begin(),v.end()); int now=0,mx=0,mxp=0; int pos; for(int i=0;i<2*n;i++){ now+=v[i].second; if(now>mx) { mxp=v[i].first; mx=now; pos=i; } } int ans=0; for(int j=i;j<=k;j++){ ans+=(v[j].second) v.erase(j); } }
[ "sreemantidey1234@gmail.com" ]
sreemantidey1234@gmail.com
1593f39bef2509117fe3f1cb4358103afbdd821a
751dffa1e2acfd42de4a33ce415b7bdddaeb9b46
/game/Koopa.h
b55c57c775a4410e91b04bfa6743ad853f7f47c7
[]
no_license
kulcua/game
65e40ee97803c7e8939bb7393cb64c32065e0d4a
309c9d9cb86ef912dbecabda9a27b1662e52b54c
refs/heads/master
2023-06-24T06:33:55.250646
2021-07-29T08:46:03
2021-07-29T08:46:03
293,836,165
0
0
null
2021-07-28T16:12:04
2020-09-08T14:32:02
C++
UTF-8
C++
false
false
1,618
h
#pragma once #include "Enermy.h" #include "Utils.h" #define KOOPA_WALKING_SPEED 0.04f #define KOOPA_BALL_SPEED 0.35f #define KOOPA_GRAVITY 0.001f #define KOOPA_BBOX_WIDTH 50 #define KOOPA_BBOX_HEIGHT 82 #define KOOPA_BBOX_HEIGHT_DIE 45 #define KOOPA_STATE_WALKING 100 #define KOOPA_STATE_BALL 200 #define KOOPA_STATE_BALL_RELIVE 300 #define KOOPA_STATE_DIE 500 #define KOOPA_ANI_WALKING 0 #define KOOPA_ANI_BALL 1 #define KOOPA_ANI_BALL_ROLL 2 #define KOOPA_ANI_BALL_RELIVE 3 #define MARIO_BIG_RACCOON_HANDLED_SHELL_HEIGHT 16 #define MARIO_SMALL_HANDLED_SHELL_HEIGHT 4 #define MARIO_SMALL_BIG_RACCOON_HANDLE_SHELL_WIDTH_LEFT 24 #define MARIO_SMALL_BIG_HANDLE_SHELL_WIDTH_RIGHT 20 #define MARIO_RACCOON_HANDLE_SHELL_WIDTH_RIGHT 36 #define KOOPA_LEVEL_BALL 1 #define KOOPA_LEVEL_NO_WING 2 #define KOOPA_LEVEL_WING 3 #define KOOPA_BALL_RELIVE_TIME 4000 class CKoopa: public Enermy { protected: int level; ULONGLONG ballStartTime; ULONGLONG reliveStartTime; public: bool isKicked; bool isHandled; CKoopa(); void HandleByMario(); void SetPositionHandled(); void KickByMario(); virtual void SetState(int state); void WalkThrough(); void DowngradeLevel(); void SetLevel(int lv) { this->level = lv; } int GetLevel() { return level; } void TurnBack(float vx); virtual void GetBoundingBox(float& l, float& t, float& r, float& b); virtual void Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects); virtual void Render(); virtual void HandleCollision(vector<LPGAMEOBJECT>* coObjects); void StartBallTime() { ballStartTime = GetTickCount64(); } void StartReliveTime() { reliveStartTime = GetTickCount64(); } };
[ "17520834@gm.uit.edu.vn" ]
17520834@gm.uit.edu.vn
04d2f2f2931863660da87693fde612e4610ac616
a904f9c3b0e46bed017bf787ee3ea4d449adb9ab
/7 Wonders Duel/7 Wonders Duel/Button.h
17def74140876581ee97d4433a724913fdf7dfea
[]
no_license
rares221/7-wonders-duel
44e210eb53dd3d7cad5c62e88a1249b70b668fc0
21fb6d92defc1c2e6aff30b8e09c4d417789e07c
refs/heads/main
2023-02-15T03:55:41.897647
2021-01-07T18:44:51
2021-01-07T18:44:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
821
h
#ifndef BUTTON_H #define BUTTON_H #include<iostream> #include<ctime> #include<cstdlib> #include"SFML/System.hpp" #include"SFML/Window.hpp" #include"SFML/Graphics.hpp" #include"SFML/Audio.hpp" enum button_states{ BTN_IDLE = 0, BTN_HOVER, BTN_ACTIVE}; class Button { private: short unsigned buttonState; bool pressed; bool hover; sf::RectangleShape shape; sf::Font* font; sf::Text text; sf::Color idleColor; sf::Color hoverColor; sf::Color activeColor; public: Button()=default; Button(float x, float y, float width,float height,sf::Font* font, std::string text,sf::Color idleColor, sf::Color hoverColor,sf::Color activeColor); ~Button(); //Accessors const bool isPressed() const; //Functions void update(const sf::Vector2f mousePos); void render(sf::RenderTarget* target); }; #endif
[ "rtaraburca@yahoo.com" ]
rtaraburca@yahoo.com
d6eeb2141e979ac1b09d7d3a27c8e876eca1f790
59f62eb8da9529918883d2029ba7bba4e7df6484
/3DCG_RenderingFramework/src/shape/mesh/SmoothFace.h
f0a483ee67836dcf60a9557309efcb89a7e34c20
[]
no_license
jelteliekens/3DCG_RenderingFramework
0fad40f9be806a432a72fbddaac1ae3641269608
0eff7d96206d9e1df3f35951285d63375849d34e
refs/heads/master
2020-04-07T15:46:16.449092
2013-12-10T13:18:55
2013-12-10T13:18:55
14,365,665
1
0
null
null
null
null
UTF-8
C++
false
false
844
h
// // SmoothFace.h // 3DCG_RenderingFramework // // Created by Jelte Liekens on 5/11/13. // Copyright (c) 2013 Jelte Liekens. All rights reserved. // #ifndef ___DCG_RenderingFramework__SmoothFace__ #define ___DCG_RenderingFramework__SmoothFace__ #include "AFace.h" #include <vector> class SmoothFace: public AFace { private: std::vector<Point *> verts; std::vector<Vector *> norms; Vector facePlaneNormal; public: SmoothFace(Point* p0, Point* p1, Point* p2, Vector* v0, Vector* v1, Vector* v2); virtual const Point & getVertex(unsigned int i) const; virtual const Vector & getNormal(unsigned int i) const; virtual const Vector & getFacePlaneNormal() const; protected: virtual Vector getHitNormal(const Point & hitPoint); }; #endif /* defined(___DCG_RenderingFramework__SmoothFace__) */
[ "jelteliekens@pandora.be" ]
jelteliekens@pandora.be
9d99f0f758152e724b8b00280a0f52aac97742fd
c3bdc0d043569dc98e9724e06fd3147d7fac551b
/ea/ea06/typeoriented/bag.h
d11c5c7574af6637950915c6da03fc8b40585f97
[]
no_license
8emi95/elte-ik-prog
efc20783a60432a908fd3a56e0e94a37238f9de6
bf51ddd880d1d8e35b4020e6fdb3f8f95ba9127f
refs/heads/master
2020-07-25T09:10:54.122984
2019-03-16T22:47:27
2019-03-16T22:47:27
175,998,663
0
0
null
null
null
null
UTF-8
C++
false
false
498
h
#ifndef BAG_H #define BAG_H #include <vector> class Bag { public: enum Exceptions {EmptyBag}; Bag() { setEmpty(); } void setEmpty() { _vect.clear(); } void putIn(int e); int maxElem() const; private: struct Pair { int v; int c; Pair() {} Pair(int a, int b): v(a), c(b) {} }; std::vector<Pair> _vect; unsigned int _maxind; bool search(int e, unsigned int &ind) const; }; #endif // BAG_H
[ "8emi95@inf.elte.hu" ]
8emi95@inf.elte.hu
ed8540403b3948e675515ee46bc2a8213e67ddba
a5607231256848628859c21a4e79c2e157bcbba6
/03hw/vector2d.cc
56a3540a4a16bf02983f4c9164ec084a80d744a6
[]
no_license
jacmiller/CSCE-240
bb31be3100d59438c830fae8b0dcaddeb6a494c2
895daee83681d95bddc800129179164dfc5a24e2
refs/heads/master
2020-03-28T04:31:39.935386
2018-09-06T19:05:26
2018-09-06T19:05:26
147,720,275
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
cc
#include "vector2d.h" const Vector2d operator+(const Vector2d& lhs, const Vector2d& rhs) { return lhs.Add(rhs); } const Vector2d Vector2d::Add(const Vector2d& rhs) const { return Vector2d(x_ + rhs.x_, y_ + rhs.y_); } const Vector2d operator-(const Vector2d& lhs, const Vector2d& rhs) { return lhs.Subtract(rhs); } const Vector2d Vector2d::Subtract(const Vector2d& rhs) const { return Vector2d(x_ - rhs.x_, y_ - rhs.y_); } const Vector2d operator-(const Vector2d& rhs) { return rhs.Reverse(); } const Vector2d Vector2d::Reverse() const { return Vector2d(-x_, -y_); } const Vector2d operator*(const Vector2d& lhs, double rhs) { return Vector2d(lhs.x_*rhs, lhs.y_*rhs); } const Vector2d operator*(double lhs, const Vector2d& rhs) { return rhs*lhs; } const Vector2d Vector2d::Scale(double scalar) const { return Vector2d(x_ * scalar, y_ * scalar); } bool operator==(const Vector2d& lhs, const Vector2d& rhs) { return lhs.EqualTo(rhs); } bool Vector2d::EqualTo(const Vector2d& rhs) const { if (x_ == rhs.x_ && y_ == rhs.y_) return true; else return false; } bool operator!=(const Vector2d& lhs, const Vector2d& rhs) { return lhs.NotEqualTo(rhs); } bool Vector2d::NotEqualTo(const Vector2d& rhs) const { return !EqualTo(rhs); } double Vector2d::GetLength() const { double magnitude; magnitude = sqrt(pow(x_, 2) + (pow(y_, 2))); return magnitude; } const Vector2d Vector2d::GetUnit() const { return Vector2d(x_ / GetLength(), y_ / GetLength()); } const string Vector2d::ToString() const { return "(" + to_string(x_) + ", " + to_string(y_) + ")"; }
[ "cjmiller1337@gmail.com" ]
cjmiller1337@gmail.com
aa3cde036f8450b9caeb1479f917aebe2a0e488d
bf6ced748e5679ae3f402fe86c11bf87e59e54d3
/constexpr-templates.cpp
fd98d7aa6cb546bba5af69dd1e6754395e69356a
[]
no_license
khedoros/khedgba
1fdfdfe8575eb698ed07939a8e88992b90dacf5c
c09458e209887992446c5e80c140685c89c13610
refs/heads/master
2020-03-12T03:08:21.455992
2019-08-03T21:22:57
2019-08-03T21:22:57
130,418,483
0
0
null
null
null
null
UTF-8
C++
false
false
1,377
cpp
#include<iostream> #include<vector> #include<functional> #include<cstdint> class cpu; typedef cpu_func_ptr; class cpu { public: enum alu_op {add_op, or_op, xor_op, op_end}; enum set_status {set, no_set, set_end}; typedef uint32_t cpu_op; typedef uint32_t reg; cpu(): regs{0} {}; static const std::vector<std::function<cpu_func_ptr>> functs{ops<add_op,set>,ops<add_op,no_set>}; template <alu_op op, set_status s> void ops(cpu_op i) { //extract operands from cpu_op argument switch(op) { add_op: break; or_op: break; xor_op: break; default: break; } if(s==set) { } } private: reg regs[16]; }; typedef void(cpu::*cpu_func_ptr)(cpu::cpu_op); std::vector<std::function<cpu_func_ptr>> cpu::functs; /* constexpr void add() { cpu * a = nullptr; for(cpu::alu_op i=cpu::alu_op::add_op;i!=cpu::alu_op::op_end;i = cpu::alu_op(i+1)) { for(cpu::set_status j=cpu::set_status::set;j!=cpu::set_status::set_end;j = cpu::set_status(j+1)) { cpu::functs.push_back(a->ops<i,j>); } } } */ int main() { //add(); cpu a; cpu::cpu_op i=0; for(auto &f:a.functs) { f(i); i++; } return 0; }
[ "khedoros@gmail.com" ]
khedoros@gmail.com
764302a6aaa7b24627984f89c896f285712d4f82
5c2f166a574737aac6ddffc44610c58143ac5030
/weblayer/browser/browser_impl.cc
e2e39cb22c741d8a34fcbc28a62db1129760ca60
[ "BSD-3-Clause" ]
permissive
Iscialman/chromium
a3e9bacd955f855f585cfe9c0e276730a50c2c98
7284136fb67ce658ec8408c6e850820d7931b1ec
refs/heads/master
2023-01-12T15:12:53.166883
2020-04-07T18:29:59
2020-04-07T18:29:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,821
cc
// Copyright 2020 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 "weblayer/browser/browser_impl.h" #include <algorithm> #include "base/callback_forward.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "components/base32/base32.h" #include "content/public/browser/browser_context.h" #include "weblayer/browser/feature_list_creator.h" #include "weblayer/browser/persistence/browser_persister.h" #include "weblayer/browser/persistence/minimal_browser_persister.h" #include "weblayer/browser/profile_impl.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/common/weblayer_paths.h" #include "weblayer/public/browser_observer.h" #if defined(OS_ANDROID) #include "base/android/callback_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/json/json_writer.h" #include "weblayer/browser/java/jni/BrowserImpl_jni.h" #endif #if defined(OS_ANDROID) using base::android::AttachCurrentThread; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; #endif namespace weblayer { std::unique_ptr<Browser> Browser::Create( Profile* profile, const PersistenceInfo* persistence_info) { // BrowserImpl's constructor is private. auto browser = base::WrapUnique(new BrowserImpl(static_cast<ProfileImpl*>(profile))); if (persistence_info) browser->RestoreStateIfNecessary(*persistence_info); return browser; } BrowserImpl::~BrowserImpl() { #if defined(OS_ANDROID) // Android side should always remove tabs first (because the Java Tab class // owns the C++ Tab). See BrowserImpl.destroy() (in the Java BrowserImpl // class). DCHECK(tabs_.empty()); #else while (!tabs_.empty()) RemoveTab(tabs_.back().get()); #endif profile_->DecrementBrowserImplCount(); } TabImpl* BrowserImpl::CreateTabForSessionRestore( std::unique_ptr<content::WebContents> web_contents, const std::string& guid) { std::unique_ptr<TabImpl> tab = std::make_unique<TabImpl>(profile_, std::move(web_contents), guid); #if defined(OS_ANDROID) Java_BrowserImpl_createTabForSessionRestore( AttachCurrentThread(), java_impl_, reinterpret_cast<jlong>(tab.get())); #endif TabImpl* tab_ptr = tab.get(); AddTab(std::move(tab)); return tab_ptr; } #if defined(OS_ANDROID) void BrowserImpl::AddTab(JNIEnv* env, const JavaParamRef<jobject>& caller, long native_tab) { TabImpl* tab = reinterpret_cast<TabImpl*>(native_tab); std::unique_ptr<Tab> owned_tab; if (tab->browser()) owned_tab = tab->browser()->RemoveTab(tab); else owned_tab.reset(tab); AddTab(std::move(owned_tab)); } void BrowserImpl::RemoveTab(JNIEnv* env, const JavaParamRef<jobject>& caller, long native_tab) { // The Java side owns the Tab. RemoveTab(reinterpret_cast<TabImpl*>(native_tab)).release(); } ScopedJavaLocalRef<jobjectArray> BrowserImpl::GetTabs( JNIEnv* env, const JavaParamRef<jobject>& caller) { ScopedJavaLocalRef<jclass> clazz = base::android::GetClass(env, "org/chromium/weblayer_private/TabImpl"); jobjectArray tabs = env->NewObjectArray(tabs_.size(), clazz.obj(), nullptr /* initialElement */); base::android::CheckException(env); for (size_t i = 0; i < tabs_.size(); ++i) { TabImpl* tab = static_cast<TabImpl*>(tabs_[i].get()); env->SetObjectArrayElement(tabs, i, tab->GetJavaTab().obj()); } return ScopedJavaLocalRef<jobjectArray>(env, tabs); } void BrowserImpl::SetActiveTab(JNIEnv* env, const JavaParamRef<jobject>& caller, long native_tab) { SetActiveTab(reinterpret_cast<TabImpl*>(native_tab)); } ScopedJavaLocalRef<jobject> BrowserImpl::GetActiveTab( JNIEnv* env, const JavaParamRef<jobject>& caller) { if (!active_tab_) return nullptr; return ScopedJavaLocalRef<jobject>(active_tab_->GetJavaTab()); } void BrowserImpl::PrepareForShutdown(JNIEnv* env, const JavaParamRef<jobject>& caller) { PrepareForShutdown(); } ScopedJavaLocalRef<jstring> BrowserImpl::GetPersistenceId( JNIEnv* env, const JavaParamRef<jobject>& caller) { return ScopedJavaLocalRef<jstring>( base::android::ConvertUTF8ToJavaString(env, GetPersistenceId())); } void BrowserImpl::SaveBrowserPersisterIfNecessary( JNIEnv* env, const JavaParamRef<jobject>& caller) { browser_persister_->SaveIfNecessary(); } ScopedJavaLocalRef<jbyteArray> BrowserImpl::GetBrowserPersisterCryptoKey( JNIEnv* env, const JavaParamRef<jobject>& caller) { std::vector<uint8_t> key; if (browser_persister_) key = browser_persister_->GetCryptoKey(); return base::android::ToJavaByteArray(env, key); } ScopedJavaLocalRef<jbyteArray> BrowserImpl::GetMinimalPersistenceState( JNIEnv* env, const JavaParamRef<jobject>& caller) { auto state = GetMinimalPersistenceState(); return base::android::ToJavaByteArray(env, &(state.front()), state.size()); } void BrowserImpl::RestoreStateIfNecessary( JNIEnv* env, const JavaParamRef<jobject>& caller, const JavaParamRef<jstring>& j_persistence_id, const JavaParamRef<jbyteArray>& j_persistence_crypto_key, const JavaParamRef<jbyteArray>& j_minimal_persistence_state) { Browser::PersistenceInfo persistence_info; Browser::PersistenceInfo* persistence_info_ptr = nullptr; if (j_persistence_id.obj()) { const std::string persistence_id = base::android::ConvertJavaStringToUTF8(j_persistence_id); if (!persistence_id.empty()) { persistence_info.id = persistence_id; if (j_persistence_crypto_key.obj()) { base::android::JavaByteArrayToByteVector( env, j_persistence_crypto_key, &(persistence_info.last_crypto_key)); } persistence_info_ptr = &persistence_info; } } else if (j_minimal_persistence_state.obj()) { base::android::JavaByteArrayToByteVector(env, j_minimal_persistence_state, &(persistence_info.minimal_state)); persistence_info_ptr = &persistence_info; } if (persistence_info_ptr) RestoreStateIfNecessary(*persistence_info_ptr); } void BrowserImpl::WebPreferencesChanged(JNIEnv* env) { for (const auto& tab : tabs_) { TabImpl* tab_impl = static_cast<TabImpl*>(tab.get()); tab_impl->WebPreferencesChanged(); } } void BrowserImpl::OnFragmentStart( JNIEnv* env, const base::android::JavaParamRef<jobject>& caller) { // FeatureListCreator is created before any Browsers. DCHECK(FeatureListCreator::GetInstance()); FeatureListCreator::GetInstance()->OnBrowserFragmentStarted(); } #endif std::vector<uint8_t> BrowserImpl::GetMinimalPersistenceState( int max_size_in_bytes) { return PersistMinimalState(this, max_size_in_bytes); } bool BrowserImpl::GetPasswordEchoEnabled() { #if defined(OS_ANDROID) return Java_BrowserImpl_getPasswordEchoEnabled(AttachCurrentThread(), java_impl_); #else return false; #endif } Tab* BrowserImpl::AddTab(std::unique_ptr<Tab> tab) { DCHECK(tab); TabImpl* tab_impl = static_cast<TabImpl*>(tab.get()); DCHECK(!tab_impl->browser()); tabs_.push_back(std::move(tab)); tab_impl->set_browser(this); #if defined(OS_ANDROID) Java_BrowserImpl_onTabAdded(AttachCurrentThread(), java_impl_, tab_impl->GetJavaTab()); #endif for (BrowserObserver& obs : browser_observers_) obs.OnTabAdded(tab_impl); return tab_impl; } std::unique_ptr<Tab> BrowserImpl::RemoveTab(Tab* tab) { TabImpl* tab_impl = static_cast<TabImpl*>(tab); DCHECK_EQ(this, tab_impl->browser()); static_cast<TabImpl*>(tab)->set_browser(nullptr); auto iter = std::find_if(tabs_.begin(), tabs_.end(), base::MatchesUniquePtr(tab)); DCHECK(iter != tabs_.end()); std::unique_ptr<Tab> owned_tab = std::move(*iter); tabs_.erase(iter); const bool active_tab_changed = active_tab_ == tab; if (active_tab_changed) active_tab_ = nullptr; #if defined(OS_ANDROID) if (active_tab_changed) { Java_BrowserImpl_onActiveTabChanged( AttachCurrentThread(), java_impl_, active_tab_ ? static_cast<TabImpl*>(active_tab_)->GetJavaTab() : nullptr); } Java_BrowserImpl_onTabRemoved(AttachCurrentThread(), java_impl_, tab ? tab_impl->GetJavaTab() : nullptr); #endif if (active_tab_changed) { for (BrowserObserver& obs : browser_observers_) obs.OnActiveTabChanged(active_tab_); } for (BrowserObserver& obs : browser_observers_) obs.OnTabRemoved(tab, active_tab_changed); return owned_tab; } void BrowserImpl::SetActiveTab(Tab* tab) { if (GetActiveTab() == tab) return; // TODO: currently the java side sets visibility, this code likely should // too and it should be removed from the java side. active_tab_ = static_cast<TabImpl*>(tab); #if defined(OS_ANDROID) Java_BrowserImpl_onActiveTabChanged( AttachCurrentThread(), java_impl_, active_tab_ ? active_tab_->GetJavaTab() : nullptr); #endif for (BrowserObserver& obs : browser_observers_) obs.OnActiveTabChanged(active_tab_); if (active_tab_) active_tab_->web_contents()->GetController().LoadIfNecessary(); } Tab* BrowserImpl::GetActiveTab() { return active_tab_; } std::vector<Tab*> BrowserImpl::GetTabs() { std::vector<Tab*> tabs(tabs_.size()); for (size_t i = 0; i < tabs_.size(); ++i) tabs[i] = tabs_[i].get(); return tabs; } void BrowserImpl::PrepareForShutdown() { browser_persister_.reset(); } std::string BrowserImpl::GetPersistenceId() { return persistence_id_; } std::vector<uint8_t> BrowserImpl::GetMinimalPersistenceState() { // 0 means use the default max. return GetMinimalPersistenceState(0); } void BrowserImpl::AddObserver(BrowserObserver* observer) { browser_observers_.AddObserver(observer); } void BrowserImpl::RemoveObserver(BrowserObserver* observer) { browser_observers_.RemoveObserver(observer); } BrowserImpl::BrowserImpl(ProfileImpl* profile) : profile_(profile) { profile_->IncrementBrowserImplCount(); } void BrowserImpl::RestoreStateIfNecessary( const PersistenceInfo& persistence_info) { persistence_id_ = persistence_info.id; if (!persistence_id_.empty()) { browser_persister_ = std::make_unique<BrowserPersister>( GetBrowserPersisterDataPath(), this, persistence_info.last_crypto_key); } else if (!persistence_info.minimal_state.empty()) { RestoreMinimalState(this, persistence_info.minimal_state); } } void BrowserImpl::VisibleSecurityStateOfActiveTabChanged() { if (visible_security_state_changed_callback_for_tests_) std::move(visible_security_state_changed_callback_for_tests_).Run(); #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); Java_BrowserImpl_onVisibleSecurityStateOfActiveTabChanged(env, java_impl_); #endif } base::FilePath BrowserImpl::GetBrowserPersisterDataPath() { base::FilePath base_path = profile_->GetBrowserPersisterDataBaseDir(); DCHECK(!GetPersistenceId().empty()); const std::string encoded_name = base32::Base32Encode(GetPersistenceId()); return base_path.AppendASCII("State" + encoded_name); } #if defined(OS_ANDROID) // This function is friended. JNI_BrowserImpl_CreateBrowser can not be // friended, as it requires browser_impl.h to include BrowserImpl_jni.h, which // is problematic (meaning not really supported and generates compile errors). BrowserImpl* CreateBrowserForAndroid(ProfileImpl* profile, const JavaParamRef<jobject>& java_impl) { BrowserImpl* browser = new BrowserImpl(profile); browser->java_impl_ = java_impl; return browser; } static jlong JNI_BrowserImpl_CreateBrowser( JNIEnv* env, jlong profile, const JavaParamRef<jobject>& java_impl) { // The android side does not trigger restore from the constructor as at the // time this is called not enough of WebLayer has been wired up. Specifically, // when this is called BrowserImpl.java hasn't obtained the return value so // that it can't call any functions and further the client side hasn't been // fully created, leading to all sort of assertions if Tabs are created // and/or navigations start (which restore may trigger). return reinterpret_cast<intptr_t>(CreateBrowserForAndroid( reinterpret_cast<ProfileImpl*>(profile), java_impl)); } static void JNI_BrowserImpl_DeleteBrowser(JNIEnv* env, jlong browser) { delete reinterpret_cast<BrowserImpl*>(browser); } #endif } // namespace weblayer
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ef480deea8439d40e53e010b1d95f1265d1ad84d
56e768d5ad9c61a91fd6004d6408ae052e6039cb
/net/base/transport_security_state.cc
747dc7e6b957f330c033909026b2ef58aa5c49eb
[]
no_license
feefk/websocket
217faa069e5229a23b11ee91441d788c9616bd38
94a49ed057f08c3596756cde340dd991eb197bed
refs/heads/master
2020-03-26T20:16:51.781470
2014-07-24T10:04:19
2014-07-24T10:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,831
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/transport_security_state.h" #if defined(USE_OPENSSL) #include <openssl/ecdsa.h> #include <openssl/ssl.h> #else // !defined(USE_OPENSSL) #include <cryptohi.h> #include <hasht.h> #include <keyhi.h> #include <pk11pub.h> #include <nspr.h> #endif #include <algorithm> #include <utility> #include "base/base64.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/sha1.h" #include "base/string_number_conversions.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "crypto/sha2.h" #include "googleurl/src/gurl.h" #include "net/base/dns_util.h" #include "net/base/ssl_info.h" #include "net/base/x509_certificate.h" #include "net/http/http_util.h" #if defined(USE_OPENSSL) #include "crypto/openssl_util.h" #endif namespace net { const long int TransportSecurityState::kMaxHSTSAgeSecs = 86400 * 365; // 1 year static std::string HashHost(const std::string& canonicalized_host) { char hashed[crypto::kSHA256Length]; crypto::SHA256HashString(canonicalized_host, hashed, sizeof(hashed)); return std::string(hashed, sizeof(hashed)); } TransportSecurityState::TransportSecurityState() : delegate_(NULL) { } void TransportSecurityState::SetDelegate( TransportSecurityState::Delegate* delegate) { delegate_ = delegate; } void TransportSecurityState::EnableHost(const std::string& host, const DomainState& state) { DCHECK(CalledOnValidThread()); const std::string canonicalized_host = CanonicalizeHost(host); if (canonicalized_host.empty()) return; DomainState existing_state; // Use the original creation date if we already have this host. (But note // that statically-defined states have no |created| date. Therefore, we do // not bother to search the SNI-only static states.) DomainState state_copy(state); if (GetDomainState(host, false /* sni_enabled */, &existing_state) && !existing_state.created.is_null()) { state_copy.created = existing_state.created; } // No need to store this value since it is redundant. (|canonicalized_host| // is the map key.) state_copy.domain.clear(); enabled_hosts_[HashHost(canonicalized_host)] = state_copy; DirtyNotify(); } bool TransportSecurityState::DeleteHost(const std::string& host) { DCHECK(CalledOnValidThread()); const std::string canonicalized_host = CanonicalizeHost(host); if (canonicalized_host.empty()) return false; std::map<std::string, DomainState>::iterator i = enabled_hosts_.find( HashHost(canonicalized_host)); if (i != enabled_hosts_.end()) { enabled_hosts_.erase(i); DirtyNotify(); return true; } return false; } bool TransportSecurityState::GetDomainState(const std::string& host, bool sni_enabled, DomainState* result) { DCHECK(CalledOnValidThread()); DomainState state; const std::string canonicalized_host = CanonicalizeHost(host); if (canonicalized_host.empty()) return false; bool has_preload = GetStaticDomainState(canonicalized_host, sni_enabled, &state); std::string canonicalized_preload = CanonicalizeHost(state.domain); base::Time current_time(base::Time::Now()); for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) { std::string host_sub_chunk(&canonicalized_host[i], canonicalized_host.size() - i); // Exact match of a preload always wins. if (has_preload && host_sub_chunk == canonicalized_preload) { *result = state; return true; } std::map<std::string, DomainState>::iterator j = enabled_hosts_.find(HashHost(host_sub_chunk)); if (j == enabled_hosts_.end()) continue; if (current_time > j->second.upgrade_expiry && current_time > j->second.dynamic_spki_hashes_expiry) { enabled_hosts_.erase(j); DirtyNotify(); continue; } state = j->second; state.domain = DNSDomainToString(host_sub_chunk); // Succeed if we matched the domain exactly or if subdomain matches are // allowed. if (i == 0 || j->second.include_subdomains) { *result = state; return true; } return false; } return false; } void TransportSecurityState::DeleteSince(const base::Time& time) { DCHECK(CalledOnValidThread()); bool dirtied = false; std::map<std::string, DomainState>::iterator i = enabled_hosts_.begin(); while (i != enabled_hosts_.end()) { if (i->second.created >= time) { dirtied = true; enabled_hosts_.erase(i++); } else { i++; } } if (dirtied) DirtyNotify(); } // MaxAgeToInt converts a string representation of a number of seconds into a // int. We use strtol in order to handle overflow correctly. The string may // contain an arbitary number which we should truncate correctly rather than // throwing a parse failure. static bool MaxAgeToInt(std::string::const_iterator begin, std::string::const_iterator end, int* result) { const std::string s(begin, end); char* endptr; long int i = strtol(s.data(), &endptr, 10 /* base */); if (*endptr || i < 0) return false; if (i > TransportSecurityState::kMaxHSTSAgeSecs) i = TransportSecurityState::kMaxHSTSAgeSecs; *result = i; return true; } // Strip, Split, StringPair, and ParsePins are private implementation details // of ParsePinsHeader(std::string&, DomainState&). static std::string Strip(const std::string& source) { if (source.empty()) return source; std::string::const_iterator start = source.begin(); std::string::const_iterator end = source.end(); HttpUtil::TrimLWS(&start, &end); return std::string(start, end); } typedef std::pair<std::string, std::string> StringPair; static StringPair Split(const std::string& source, char delimiter) { StringPair pair; size_t point = source.find(delimiter); pair.first = source.substr(0, point); if (std::string::npos != point) pair.second = source.substr(point + 1); return pair; } // TODO(palmer): Support both sha256 and sha1. This will require additional // infrastructure code changes and can come in a later patch. // // static bool TransportSecurityState::ParsePin(const std::string& value, SHA1Fingerprint* out) { StringPair slash = Split(Strip(value), '/'); if (slash.first != "sha1") return false; std::string decoded; if (!base::Base64Decode(slash.second, &decoded) || decoded.size() != arraysize(out->data)) { return false; } memcpy(out->data, decoded.data(), arraysize(out->data)); return true; } static bool ParseAndAppendPin(const std::string& value, FingerprintVector* fingerprints) { // The base64'd fingerprint MUST be a quoted-string. 20 bytes base64'd is 28 // characters; 32 bytes base64'd is 44 characters. TODO(palmer): Support // SHA256. size_t size = value.size(); if (size != 30 || value[0] != '"' || value[size - 1] != '"') return false; std::string unquoted = HttpUtil::Unquote(value); std::string decoded; SHA1Fingerprint fp; if (!base::Base64Decode(unquoted, &decoded) || decoded.size() != arraysize(fp.data)) { return false; } memcpy(fp.data, decoded.data(), arraysize(fp.data)); fingerprints->push_back(fp); return true; } struct FingerprintsEqualPredicate { explicit FingerprintsEqualPredicate(const SHA1Fingerprint& fingerprint) : fingerprint_(fingerprint) {} bool operator()(const SHA1Fingerprint& other) const { return fingerprint_.Equals(other); } const SHA1Fingerprint& fingerprint_; }; // Returns true iff there is an item in |pins| which is not present in // |from_cert_chain|. Such an SPKI hash is called a "backup pin". static bool IsBackupPinPresent(const FingerprintVector& pins, const FingerprintVector& from_cert_chain) { for (FingerprintVector::const_iterator i = pins.begin(); i != pins.end(); ++i) { FingerprintVector::const_iterator j = std::find_if(from_cert_chain.begin(), from_cert_chain.end(), FingerprintsEqualPredicate(*i)); if (j == from_cert_chain.end()) return true; } return false; } static bool HashesIntersect(const FingerprintVector& a, const FingerprintVector& b) { for (FingerprintVector::const_iterator i = a.begin(); i != a.end(); ++i) { FingerprintVector::const_iterator j = std::find_if(b.begin(), b.end(), FingerprintsEqualPredicate(*i)); if (j != b.end()) return true; } return false; } // Returns true iff |pins| contains both a live and a backup pin. A live pin // is a pin whose SPKI is present in the certificate chain in |ssl_info|. A // backup pin is a pin intended for disaster recovery, not day-to-day use, and // thus must be absent from the certificate chain. The Public-Key-Pins header // specification requires both. static bool IsPinListValid(const FingerprintVector& pins, const SSLInfo& ssl_info) { if (pins.size() < 2) return false; const FingerprintVector& from_cert_chain = ssl_info.public_key_hashes; if (from_cert_chain.empty()) return false; return IsBackupPinPresent(pins, from_cert_chain) && HashesIntersect(pins, from_cert_chain); } // "Public-Key-Pins" ":" // "max-age" "=" delta-seconds ";" // "pin-" algo "=" base64 [ ";" ... ] bool TransportSecurityState::DomainState::ParsePinsHeader( const base::Time& now, const std::string& value, const SSLInfo& ssl_info) { bool parsed_max_age = false; int max_age_candidate = 0; FingerprintVector pins; std::string source = value; while (!source.empty()) { StringPair semicolon = Split(source, ';'); semicolon.first = Strip(semicolon.first); semicolon.second = Strip(semicolon.second); StringPair equals = Split(semicolon.first, '='); equals.first = Strip(equals.first); equals.second = Strip(equals.second); if (LowerCaseEqualsASCII(equals.first, "max-age")) { if (equals.second.empty() || !MaxAgeToInt(equals.second.begin(), equals.second.end(), &max_age_candidate)) { return false; } if (max_age_candidate > kMaxHSTSAgeSecs) max_age_candidate = kMaxHSTSAgeSecs; parsed_max_age = true; } else if (LowerCaseEqualsASCII(equals.first, "pin-sha1")) { if (!ParseAndAppendPin(equals.second, &pins)) return false; } else if (LowerCaseEqualsASCII(equals.first, "pin-sha256")) { // TODO(palmer) } else { // Silently ignore unknown directives for forward compatibility. } source = semicolon.second; } if (!parsed_max_age || !IsPinListValid(pins, ssl_info)) return false; dynamic_spki_hashes_expiry = now + base::TimeDelta::FromSeconds(max_age_candidate); dynamic_spki_hashes.clear(); if (max_age_candidate > 0) { for (FingerprintVector::const_iterator i = pins.begin(); i != pins.end(); ++i) { dynamic_spki_hashes.push_back(*i); } } return true; } // "Strict-Transport-Security" ":" // "max-age" "=" delta-seconds [ ";" "includeSubDomains" ] bool TransportSecurityState::DomainState::ParseSTSHeader( const base::Time& now, const std::string& value) { int max_age_candidate = 0; enum ParserState { START, AFTER_MAX_AGE_LABEL, AFTER_MAX_AGE_EQUALS, AFTER_MAX_AGE, AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER, AFTER_INCLUDE_SUBDOMAINS, } state = START; StringTokenizer tokenizer(value, " \t=;"); tokenizer.set_options(StringTokenizer::RETURN_DELIMS); while (tokenizer.GetNext()) { DCHECK(!tokenizer.token_is_delim() || tokenizer.token().length() == 1); switch (state) { case START: if (IsAsciiWhitespace(*tokenizer.token_begin())) continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "max-age")) return false; state = AFTER_MAX_AGE_LABEL; break; case AFTER_MAX_AGE_LABEL: if (IsAsciiWhitespace(*tokenizer.token_begin())) continue; if (*tokenizer.token_begin() != '=') return false; DCHECK_EQ(tokenizer.token().length(), 1U); state = AFTER_MAX_AGE_EQUALS; break; case AFTER_MAX_AGE_EQUALS: if (IsAsciiWhitespace(*tokenizer.token_begin())) continue; if (!MaxAgeToInt(tokenizer.token_begin(), tokenizer.token_end(), &max_age_candidate)) return false; state = AFTER_MAX_AGE; break; case AFTER_MAX_AGE: if (IsAsciiWhitespace(*tokenizer.token_begin())) continue; if (*tokenizer.token_begin() != ';') return false; state = AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER; break; case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: if (IsAsciiWhitespace(*tokenizer.token_begin())) continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "includesubdomains")) return false; state = AFTER_INCLUDE_SUBDOMAINS; break; case AFTER_INCLUDE_SUBDOMAINS: if (!IsAsciiWhitespace(*tokenizer.token_begin())) return false; break; } } // We've consumed all the input. Let's see what state we ended up in. switch (state) { case START: case AFTER_MAX_AGE_LABEL: case AFTER_MAX_AGE_EQUALS: return false; case AFTER_MAX_AGE: upgrade_expiry = now + base::TimeDelta::FromSeconds(max_age_candidate); include_subdomains = false; upgrade_mode = MODE_FORCE_HTTPS; return true; case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: return false; case AFTER_INCLUDE_SUBDOMAINS: upgrade_expiry = now + base::TimeDelta::FromSeconds(max_age_candidate); include_subdomains = true; upgrade_mode = MODE_FORCE_HTTPS; return true; default: NOTREACHED(); return false; } } static bool AddHash(const std::string& type_and_base64, FingerprintVector* out) { SHA1Fingerprint hash; if (!TransportSecurityState::ParsePin(type_and_base64, &hash)) return false; out->push_back(hash); return true; } TransportSecurityState::~TransportSecurityState() {} void TransportSecurityState::DirtyNotify() { DCHECK(CalledOnValidThread()); if (delegate_) delegate_->StateIsDirty(this); } // static std::string TransportSecurityState::CanonicalizeHost(const std::string& host) { // We cannot perform the operations as detailed in the spec here as |host| // has already undergone IDN processing before it reached us. Thus, we check // that there are no invalid characters in the host and lowercase the result. std::string new_host; if (!DNSDomainFromDot(host, &new_host)) { // DNSDomainFromDot can fail if any label is > 63 bytes or if the whole // name is >255 bytes. However, search terms can have those properties. return std::string(); } for (size_t i = 0; new_host[i]; i += new_host[i] + 1) { const unsigned label_length = static_cast<unsigned>(new_host[i]); if (!label_length) break; for (size_t j = 0; j < label_length; ++j) { // RFC 3490, 4.1, step 3 if (!IsSTD3ASCIIValidCharacter(new_host[i + 1 + j])) return std::string(); new_host[i + 1 + j] = tolower(new_host[i + 1 + j]); } // step 3(b) if (new_host[i + 1] == '-' || new_host[i + label_length] == '-') { return std::string(); } } return new_host; } // |ReportUMAOnPinFailure| uses these to report which domain was associated // with the public key pinning failure. // // DO NOT CHANGE THE ORDERING OF THESE NAMES OR REMOVE ANY OF THEM. Add new // domains at the END of the listing (but before DOMAIN_NUM_EVENTS). enum SecondLevelDomainName { DOMAIN_NOT_PINNED, DOMAIN_GOOGLE_COM, DOMAIN_ANDROID_COM, DOMAIN_GOOGLE_ANALYTICS_COM, DOMAIN_GOOGLEPLEX_COM, DOMAIN_YTIMG_COM, DOMAIN_GOOGLEUSERCONTENT_COM, DOMAIN_YOUTUBE_COM, DOMAIN_GOOGLEAPIS_COM, DOMAIN_GOOGLEADSERVICES_COM, DOMAIN_GOOGLECODE_COM, DOMAIN_APPSPOT_COM, DOMAIN_GOOGLESYNDICATION_COM, DOMAIN_DOUBLECLICK_NET, DOMAIN_GSTATIC_COM, DOMAIN_GMAIL_COM, DOMAIN_GOOGLEMAIL_COM, DOMAIN_GOOGLEGROUPS_COM, DOMAIN_TORPROJECT_ORG, DOMAIN_TWITTER_COM, DOMAIN_TWIMG_COM, DOMAIN_AKAMAIHD_NET, DOMAIN_TOR2WEB_ORG, // Boundary value for UMA_HISTOGRAM_ENUMERATION: DOMAIN_NUM_EVENTS }; // PublicKeyPins contains a number of SubjectPublicKeyInfo hashes for a site. // The validated certificate chain for the site must not include any of // |excluded_hashes| and must include one or more of |required_hashes|. struct PublicKeyPins { const char* const* required_hashes; const char* const* excluded_hashes; }; struct HSTSPreload { uint8 length; bool include_subdomains; char dns_name[34]; bool https_required; PublicKeyPins pins; SecondLevelDomainName second_level_domain_name; }; static bool HasPreload(const struct HSTSPreload* entries, size_t num_entries, const std::string& canonicalized_host, size_t i, TransportSecurityState::DomainState* out, bool* ret) { for (size_t j = 0; j < num_entries; j++) { if (entries[j].length == canonicalized_host.size() - i && memcmp(entries[j].dns_name, &canonicalized_host[i], entries[j].length) == 0) { if (!entries[j].include_subdomains && i != 0) { *ret = false; } else { out->include_subdomains = entries[j].include_subdomains; *ret = true; if (!entries[j].https_required) out->upgrade_mode = TransportSecurityState::DomainState::MODE_DEFAULT; if (entries[j].pins.required_hashes) { const char* const* hash = entries[j].pins.required_hashes; while (*hash) { bool ok = AddHash(*hash, &out->static_spki_hashes); DCHECK(ok) << " failed to parse " << *hash; hash++; } } if (entries[j].pins.excluded_hashes) { const char* const* hash = entries[j].pins.excluded_hashes; while (*hash) { bool ok = AddHash(*hash, &out->bad_static_spki_hashes); DCHECK(ok) << " failed to parse " << *hash; hash++; } } } return true; } } return false; } #include "net/base/transport_security_state_static.h" // Returns the HSTSPreload entry for the |canonicalized_host| in |entries|, // or NULL if there is none. Prefers exact hostname matches to those that // match only because HSTSPreload.include_subdomains is true. // // |canonicalized_host| should be the hostname as canonicalized by // CanonicalizeHost. static const struct HSTSPreload* GetHSTSPreload( const std::string& canonicalized_host, const struct HSTSPreload* entries, size_t num_entries) { for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) { for (size_t j = 0; j < num_entries; j++) { const struct HSTSPreload* entry = entries + j; if (i != 0 && !entry->include_subdomains) continue; if (entry->length == canonicalized_host.size() - i && memcmp(entry->dns_name, &canonicalized_host[i], entry->length) == 0) { return entry; } } } return NULL; } // static bool TransportSecurityState::IsGooglePinnedProperty(const std::string& host, bool sni_enabled) { std::string canonicalized_host = CanonicalizeHost(host); const struct HSTSPreload* entry = GetHSTSPreload(canonicalized_host, kPreloadedSTS, kNumPreloadedSTS); if (entry && entry->pins.required_hashes == kGoogleAcceptableCerts) return true; if (sni_enabled) { entry = GetHSTSPreload(canonicalized_host, kPreloadedSNISTS, kNumPreloadedSNISTS); if (entry && entry->pins.required_hashes == kGoogleAcceptableCerts) return true; } return false; } // static void TransportSecurityState::ReportUMAOnPinFailure(const std::string& host) { std::string canonicalized_host = CanonicalizeHost(host); const struct HSTSPreload* entry = GetHSTSPreload(canonicalized_host, kPreloadedSTS, kNumPreloadedSTS); if (!entry) { entry = GetHSTSPreload(canonicalized_host, kPreloadedSNISTS, kNumPreloadedSNISTS); } if (!entry) { // We don't care to report pin failures for dynamic pins. return; } DCHECK(entry); DCHECK(entry->pins.required_hashes); DCHECK(entry->second_level_domain_name != DOMAIN_NOT_PINNED); UMA_HISTOGRAM_ENUMERATION("Net.PublicKeyPinFailureDomain", entry->second_level_domain_name, DOMAIN_NUM_EVENTS); } bool TransportSecurityState::GetStaticDomainState( const std::string& canonicalized_host, bool sni_enabled, DomainState* out) { DCHECK(CalledOnValidThread()); out->upgrade_mode = DomainState::MODE_FORCE_HTTPS; out->include_subdomains = false; for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) { std::string host_sub_chunk(&canonicalized_host[i], canonicalized_host.size() - i); out->domain = DNSDomainToString(host_sub_chunk); std::string hashed_host(HashHost(host_sub_chunk)); if (forced_hosts_.find(hashed_host) != forced_hosts_.end()) { *out = forced_hosts_[hashed_host]; out->domain = DNSDomainToString(host_sub_chunk); return true; } bool ret; if (HasPreload(kPreloadedSTS, kNumPreloadedSTS, canonicalized_host, i, out, &ret)) { return ret; } if (sni_enabled && HasPreload(kPreloadedSNISTS, kNumPreloadedSNISTS, canonicalized_host, i, out, &ret)) { return ret; } } return false; } void TransportSecurityState::AddOrUpdateEnabledHosts( const std::string& hashed_host, const DomainState& state) { enabled_hosts_[hashed_host] = state; } void TransportSecurityState::AddOrUpdateForcedHosts( const std::string& hashed_host, const DomainState& state) { forced_hosts_[hashed_host] = state; } static std::string HashesToBase64String( const FingerprintVector& hashes) { std::vector<std::string> hashes_strs; for (FingerprintVector::const_iterator i = hashes.begin(); i != hashes.end(); i++) { std::string s; const std::string hash_str(reinterpret_cast<const char*>(i->data), sizeof(i->data)); base::Base64Encode(hash_str, &s); hashes_strs.push_back(s); } return JoinString(hashes_strs, ','); } TransportSecurityState::DomainState::DomainState() : upgrade_mode(MODE_FORCE_HTTPS), created(base::Time::Now()), include_subdomains(false) { } TransportSecurityState::DomainState::~DomainState() { } bool TransportSecurityState::DomainState::IsChainOfPublicKeysPermitted( const FingerprintVector& hashes) const { if (HashesIntersect(bad_static_spki_hashes, hashes)) { LOG(ERROR) << "Rejecting public key chain for domain " << domain << ". Validated chain: " << HashesToBase64String(hashes) << ", matches one or more bad hashes: " << HashesToBase64String(bad_static_spki_hashes); return false; } if (!(dynamic_spki_hashes.empty() && static_spki_hashes.empty()) && !HashesIntersect(dynamic_spki_hashes, hashes) && !HashesIntersect(static_spki_hashes, hashes)) { LOG(ERROR) << "Rejecting public key chain for domain " << domain << ". Validated chain: " << HashesToBase64String(hashes) << ", expected: " << HashesToBase64String(dynamic_spki_hashes) << " or: " << HashesToBase64String(static_spki_hashes); return false; } return true; } bool TransportSecurityState::DomainState::ShouldRedirectHTTPToHTTPS() const { return upgrade_mode == MODE_FORCE_HTTPS; } bool TransportSecurityState::DomainState::Equals( const DomainState& other) const { // TODO(palmer): Implement this (void) other; return true; } bool TransportSecurityState::DomainState::HasPins() const { return static_spki_hashes.size() > 0 || bad_static_spki_hashes.size() > 0 || dynamic_spki_hashes.size() > 0; } } // namespace
[ "liangyihao@pset.suntec.net" ]
liangyihao@pset.suntec.net
4274ba2020306133c232ebb67cf87d62617abf22
39e38c0be28ce52f8e42d8329efcfcbbe5b24e84
/TILE0/4.cpp
01917627c58b90aa0b1090cdefab99a95cfdfdf1
[]
no_license
shailesh1001/CODECHEF
bba2460f3a8ee2f61537fd67c1ed6add22a8e135
450a54d3513987691f96c2935b74362a119ab1f9
refs/heads/master
2021-01-17T20:51:28.200912
2014-11-18T16:04:04
2014-11-18T16:04:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,180
cpp
//Author : pakhandi // using namespace std; #include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<cmath> #include<cstring> #define wl while #define fl(i,a,b) for(i=a; i<b; i++) #define MOD 1000000007 using std::string; static struct IO { char tmp[1 << 10]; // fast input routines char cur; //#define nextChar() (cur = getc_unlocked(stdin)) //#define peekChar() (cur) inline char nextChar() { return cur = getc_unlocked(stdin); } inline char peekChar() { return cur; } inline operator bool() { return peekChar(); } inline static bool isBlank(char c) { return (c < '-' && c); } inline bool skipBlanks() { while (isBlank(nextChar())); return peekChar() != 0; } inline IO& operator >> (char & c) { c = nextChar(); return *this; } inline IO& operator >> (char * buf) { if (skipBlanks()) { if (peekChar()) { *(buf++) = peekChar(); while (!isBlank(nextChar())) *(buf++) = peekChar(); } *(buf++) = 0; } return *this; } inline IO& operator >> (string & s) { if (skipBlanks()) { s.clear(); s += peekChar(); while (!isBlank(nextChar())) s += peekChar(); } return *this; } inline IO& operator >> (double & d) { if ((*this) >> tmp) sscanf(tmp, "%lf", &d); return *this; } #define defineInFor(intType) \ inline IO& operator >>(intType & n) { \ if (skipBlanks()) { \ int sign = +1; \ if (peekChar() == '-') { \ sign = -1; \ n = nextChar() - '0'; \ } else \ n = peekChar() - '0'; \ while (!isBlank(nextChar())) { \ n += n + (n << 3) + peekChar() - 48; \ } \ n *= sign; \ } \ return *this; \ } defineInFor(int) defineInFor(unsigned int) defineInFor(long long) // fast output routines //#define putChar(c) putc_unlocked((c), stdout) inline void putChar(char c) { putc_unlocked(c, stdout); } inline IO& operator << (char c) { putChar(c); return *this; } inline IO& operator << (const char * s) { while (*s) putChar(*s++); return *this; } inline IO& operator << (const string & s) { for (int i = 0; i < (int)s.size(); ++i) putChar(s[i]); return *this; } char * toString(double d) { sprintf(tmp, "%lf%c", d, '\0'); return tmp; } inline IO& operator << (double d) { return (*this) << toString(d); } #define defineOutFor(intType) \ inline char * toString(intType n) { \ char * p = (tmp + 30); \ if (n) { \ bool isNeg = 0; \ if (n < 0) isNeg = 1, n = -n; \ while (n) \ *--p = (n % 10) + '0', n /= 10; \ if (isNeg) *--p = '-'; \ } else *--p = '0'; \ return p; \ } \ inline IO& operator << (intType n) { return (*this) << toString(n); } defineOutFor(int) defineOutFor(long long) #define endl ('\n') #define cout __io__ #define cin __io__ } __io__; long long int fbn[1000005]; void calc_fbn() { int i; fbn[0]=0; fbn[1]=1; long long int temp; fl(i,2,1000005) { temp=fbn[i-1]+fbn[i-2]; if(temp>MOD) temp%=MOD; fbn[i]=temp; } } int main() { calc_fbn(); long long int cases, r, ans; scanf("%lld", &cases); wl(cases--) { cin>>r; if(r==1) printf("%lld\n", 1); else if(r==2) printf("%lld\n", 2); else { ans=(2*fbn[r-1])+(1*fbn[r-2]); printf("%lld\n", ans%MOD); } } return 0; }
[ "asimkprasad@gmail.com" ]
asimkprasad@gmail.com
3ebaa1189d7a607145fdff5149d8ea3f1eb17606
5747242ac720c643a21d4c72646d719f0080be25
/Graph_Theory/Bellman_Ford.h
6f90a9d0075cfa750ea9c1ed5a6b66a3089e40f5
[ "MIT" ]
permissive
tj1432423/Graph_Theory
b5ef5cb5d63a77b0b879a25b1efa12bc7efab2ff
5a5333ee028cc86d7658ee7227a113ce90f798ae
refs/heads/main
2023-02-08T16:08:42.503849
2021-01-04T11:52:23
2021-01-04T11:52:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,360
h
#ifndef BELLMAN_FORD_H #define BELLMAN_FORD_H #include "Chain_Forward_Star.h" #include <vector> class Bellman_Ford //最短路径问题常用算法 { public: Bellman_Ford(const Chain_Forward_Star &grath, int _start_index) { //grath = _grath; start_index = _start_index; int n = grath.head.size(); dist.resize(n, Bis_Dist); dist[start_index] = 0; for (int k = 1; k <= (n - 1); k++) { //遍历n-1遍 for (int i = 0; i < grath.edges.size(); i++) { dist[grath.edges[i].to] = min(dist[grath.edges[i].to], dist[grath.edges[i].from] + grath.edges[i].w); } } negative_weight_loop = negative_weight_loop_detection(grath); } private: bool negative_weight_loop_detection(const Chain_Forward_Star &grath) { vector<float> tmp_dist(dist); for (int i = 0; i < grath.edges.size(); i++) { dist[grath.edges[i].to] = min(dist[grath.edges[i].to], dist[grath.edges[i].from] + grath.edges[i].w); } return !(dist == tmp_dist); } public: vector<float> dist; bool negative_weight_loop; int start_index; private: //Chain_Forward_Star grath; const float Bis_Dist = 99999.9; }; #endif // defined BELLMAN_FORD_H
[ "noreply@github.com" ]
tj1432423.noreply@github.com
dc185569b59eef5e6554e421d4853db1c5dcafbb
cb083845ee088f7ed57ce21216c917005389853b
/sql/src/struct_dynamic.cpp
e899f65fd1a1b7a807f8a1c550e15317932874ba
[]
no_license
jjzhang166/ServiceGalaxy
1258f2432e1e169edf1fcc422806eb5a12ac353b
6f7be491616a8bffa9d39d7925c5d6733e85d3b3
refs/heads/master
2023-03-16T13:39:30.787314
2016-06-25T01:18:34
2016-06-25T01:18:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,296
cpp
#include "struct_dynamic.h" #include "sql_control.h" #include "sql_extern.h" #include "sql_select.h" #include "sql_insert.h" #include "sql_update.h" #include "sql_delete.h" #include <boost/interprocess/sync/scoped_lock.hpp> extern void yyrestart(FILE *input_file); namespace ai { namespace scci { using namespace ai::sg; namespace bi = boost::interprocess; extern int inquote; extern int incomments; extern string tminline; extern int line_no; extern int column; boost::mutex struct_dynamic::mutex; struct_dynamic::struct_dynamic(dbtype_enum dbtype_, bool ind_required_, int _size_) : dbtype(dbtype_), ind_required(ind_required_), _size(_size_) { select_data = NULL; bind_data = NULL; select_inds = NULL; bind_inds = NULL; select_count = 0; bind_count = 0; } struct_dynamic::~struct_dynamic() { clear(); } dbtype_enum struct_dynamic::get_dbtype() { return dbtype; } void struct_dynamic::setSQL(const string& sql, const vector<column_desc_t>& binds) { int ret; if (sql.empty()) throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: empty SQL given.")).str(SGLOCALE)); bi::scoped_lock<boost::mutex> lock(mutex); char temp_name[4096]; const char *tmpdir = ::getenv("TMPDIR"); if (tmpdir == NULL) tmpdir = P_tmpdir; sprintf(temp_name, "%s/scciXXXXXX", tmpdir); int fd = ::mkstemp(temp_name); if (fd == -1) throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: mkstemp() failure, {1}") % ::strerror(errno)).str(SGLOCALE)); yyin = ::fdopen(fd, "w+"); if (yyin == NULL) { ::close(fd); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: open temp file [{1}] failure, {2}") % temp_name % ::strerror(errno)).str(SGLOCALE)); } if (::fwrite(sql.c_str(), sql.length(), 1, yyin) != 1) { ::fclose(yyin); ::unlink(temp_name); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: write sql to file [{1}] failure, {2}") % temp_name % ::strerror(errno)).str(SGLOCALE)); } ::fflush(yyin); ::fseek(yyin, 0, SEEK_SET); yyout = stdout; // default errcnt = 0; inquote = 0; incomments = 0; tminline = ""; line_no = 0; column = 0; sql_statement::clear(); // call yyparse() to parse temp file yyrestart(yyin); if ((ret = yyparse()) < 0) { ::fclose(yyin); ::unlink(temp_name); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Parse failed.")).str(SGLOCALE)); } if (ret == 1) { ::fclose(yyin); ::unlink(temp_name); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Severe error found. Stop syntax checking.")).str(SGLOCALE)); } if (errcnt > 0) { ::fclose(yyin); ::unlink(temp_name); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Above errors found during syntax checking.")).str(SGLOCALE)); } ::fclose(yyin); ::unlink(temp_name); print_prefix = ""; sql_statement::set_dbtype(dbtype); if (!sql_statement::gen_data_dynamic(this)) { sql_statement::clear(); throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Parse failed, see LOG for more information.")).str(SGLOCALE)); } select_count = select_fields.size() - 1; bind_count = bind_fields.size() - 1; alloc_select(); alloc_bind(binds); } int struct_dynamic::size() const { return _size; } void struct_dynamic::alloc_select() { // Will be delayed to alloc in prepare(). if (select_count <= 0 || select_fields[0].field_type == SQLTYPE_ANY) return; select_data = new char *[select_count]; ::memset(select_data, '\0', sizeof(char *) * select_count); if (ind_required) { select_inds = new char *[select_count]; ::memset(select_inds, '\0', sizeof(char *) * select_count); } for (int i = 0; i < select_count; i++) { select_data[i] = new char[select_fields[i].field_length * _size]; // Adjust offset. select_fields[i].field_offset = select_data[i] - reinterpret_cast<char *>(this); if (ind_required) { select_inds[i] = new char[select_fields[i].ind_length * _size]; // Adjust offset. select_fields[i].ind_offset = select_inds[i] - reinterpret_cast<char *>(this); } } } void struct_dynamic::alloc_bind(const vector<column_desc_t>& binds) { if (bind_count <= 0) return; if (!binds.empty() && bind_count != binds.size()) throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Bind array given doesn't match the size of bind fields.")).str(SGLOCALE)); bind_data = new char *[bind_count]; ::memset(bind_data, '\0', sizeof(char *) * bind_count); if (ind_required) { bind_inds = new char *[bind_count]; ::memset(bind_inds, '\0', sizeof(char *) * bind_count); } for (int i = 0; i < bind_count; i++) { if (bind_fields[i].field_type == SQLTYPE_ANY) { if (binds.empty()) throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Bind array should be provided for ANY type binding")).str(SGLOCALE)); bind_fields[i].field_type = binds[i].field_type; switch (binds[i].field_type) { case SQLTYPE_CHAR: bind_fields[i].field_length = sizeof(char); break; case SQLTYPE_UCHAR: bind_fields[i].field_length = sizeof(unsigned char); break; case SQLTYPE_SHORT: bind_fields[i].field_length = sizeof(short); break; case SQLTYPE_USHORT: bind_fields[i].field_length = sizeof(unsigned short); break; case SQLTYPE_INT: bind_fields[i].field_length = sizeof(int); break; case SQLTYPE_UINT: bind_fields[i].field_length = sizeof(unsigned int); break; case SQLTYPE_LONG: bind_fields[i].field_length = sizeof(long); break; case SQLTYPE_ULONG: bind_fields[i].field_length = sizeof(unsigned long); break; case SQLTYPE_FLOAT: bind_fields[i].field_length = sizeof(float); break; case SQLTYPE_DOUBLE: bind_fields[i].field_length = sizeof(double); break; case SQLTYPE_STRING: case SQLTYPE_VSTRING: bind_fields[i].field_length = binds[i].field_length + 1; break; case SQLTYPE_DATE: case SQLTYPE_TIME: case SQLTYPE_DATETIME: bind_fields[i].field_length = binds[i].field_length; break; default: throw bad_sql(__FILE__, __LINE__, 0, 0, (_("ERROR: Sql type unrecognized.")).str(SGLOCALE)); } } bind_data[i] = new char[bind_fields[i].field_length * _size]; // Adjust offset. bind_fields[i].field_offset = bind_data[i] - reinterpret_cast<char *>(this); if (ind_required) { bind_inds[i] = new char[bind_fields[i].ind_length * _size]; // Adjust offset. bind_fields[i].ind_offset = bind_inds[i] - reinterpret_cast<char *>(this); } } } void struct_dynamic::clear() { int i; if (bind_data) { for (i = 0; i < bind_count; i++) { delete []bind_data[i]; if (ind_required) delete []bind_inds[i]; } delete []bind_data; delete []bind_inds; bind_data = NULL; bind_inds = NULL; } if (select_data) { for (i = 0; i < select_count; i++) { delete []select_data[i]; if (ind_required) delete []select_inds[i]; } delete []select_data; delete []select_inds; select_data = NULL; select_inds = NULL; } select_fields.clear(); bind_fields.clear(); table_fields.clear(); select_count = 0; bind_count = 0; } bind_field_t * struct_dynamic::getSelectFields(int index) { return &select_fields[0]; } bind_field_t * struct_dynamic::getBindFields(int index) { return &bind_fields[0]; } string& struct_dynamic::getSQL(int index) { return _sql; } table_field_t * struct_dynamic::getTableFields(int index) { return &table_fields[index]; } } }
[ "xugq@asiainfo.com" ]
xugq@asiainfo.com
b30ed91716b17543f79453ca0c34bdea7c4fd117
39539987d11d1031f1c6ca56f85235a8355d8750
/usr/bin/qtopia/examples/painting/svgviewer/svgview.cpp
ba19d5710dab03c8e9bf52e3d948b27700d89833
[]
no_license
sensarliar/zfcs_filesystem
dfe36b46c91eaa027940ec22f556dea6dabb08cf
fea119e8a5027cbef664414b7e44138a3bde7ce5
refs/heads/master
2021-01-25T10:29:28.515351
2014-08-29T13:27:46
2014-08-29T13:27:46
22,943,366
1
2
null
2018-02-23T15:05:27
2014-08-14T06:19:08
C++
UTF-8
C++
false
false
5,720
cpp
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "svgview.h" #include <QFile> #include <QWheelEvent> #include <QMouseEvent> #include <QGraphicsRectItem> #include <QGraphicsSvgItem> #include <QPaintEvent> #include <qmath.h> #ifndef QT_NO_OPENGL #include <QGLWidget> #endif SvgView::SvgView(QWidget *parent) : QGraphicsView(parent) , m_renderer(Native) , m_svgItem(0) , m_backgroundItem(0) , m_outlineItem(0) { setScene(new QGraphicsScene(this)); setTransformationAnchor(AnchorUnderMouse); setDragMode(ScrollHandDrag); setViewportUpdateMode(FullViewportUpdate); // Prepare background check-board pattern QPixmap tilePixmap(64, 64); tilePixmap.fill(Qt::white); QPainter tilePainter(&tilePixmap); QColor color(220, 220, 220); tilePainter.fillRect(0, 0, 32, 32, color); tilePainter.fillRect(32, 32, 32, 32, color); tilePainter.end(); setBackgroundBrush(tilePixmap); } void SvgView::drawBackground(QPainter *p, const QRectF &) { p->save(); p->resetTransform(); p->drawTiledPixmap(viewport()->rect(), backgroundBrush().texture()); p->restore(); } void SvgView::openFile(const QFile &file) { if (!file.exists()) return; QGraphicsScene *s = scene(); bool drawBackground = (m_backgroundItem ? m_backgroundItem->isVisible() : false); bool drawOutline = (m_outlineItem ? m_outlineItem->isVisible() : true); s->clear(); resetTransform(); m_svgItem = new QGraphicsSvgItem(file.fileName()); m_svgItem->setFlags(QGraphicsItem::ItemClipsToShape); m_svgItem->setCacheMode(QGraphicsItem::NoCache); m_svgItem->setZValue(0); m_backgroundItem = new QGraphicsRectItem(m_svgItem->boundingRect()); m_backgroundItem->setBrush(Qt::white); m_backgroundItem->setPen(Qt::NoPen); m_backgroundItem->setVisible(drawBackground); m_backgroundItem->setZValue(-1); m_outlineItem = new QGraphicsRectItem(m_svgItem->boundingRect()); QPen outline(Qt::black, 2, Qt::DashLine); outline.setCosmetic(true); m_outlineItem->setPen(outline); m_outlineItem->setBrush(Qt::NoBrush); m_outlineItem->setVisible(drawOutline); m_outlineItem->setZValue(1); s->addItem(m_backgroundItem); s->addItem(m_svgItem); s->addItem(m_outlineItem); s->setSceneRect(m_outlineItem->boundingRect().adjusted(-10, -10, 10, 10)); } void SvgView::setRenderer(RendererType type) { m_renderer = type; if (m_renderer == OpenGL) { #ifndef QT_NO_OPENGL setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); #endif } else { setViewport(new QWidget); } } void SvgView::setHighQualityAntialiasing(bool highQualityAntialiasing) { #ifndef QT_NO_OPENGL setRenderHint(QPainter::HighQualityAntialiasing, highQualityAntialiasing); #else Q_UNUSED(highQualityAntialiasing); #endif } void SvgView::setViewBackground(bool enable) { if (!m_backgroundItem) return; m_backgroundItem->setVisible(enable); } void SvgView::setViewOutline(bool enable) { if (!m_outlineItem) return; m_outlineItem->setVisible(enable); } void SvgView::paintEvent(QPaintEvent *event) { if (m_renderer == Image) { if (m_image.size() != viewport()->size()) { m_image = QImage(viewport()->size(), QImage::Format_ARGB32_Premultiplied); } QPainter imagePainter(&m_image); QGraphicsView::render(&imagePainter); imagePainter.end(); QPainter p(viewport()); p.drawImage(0, 0, m_image); } else { QGraphicsView::paintEvent(event); } } void SvgView::wheelEvent(QWheelEvent *event) { qreal factor = qPow(1.2, event->delta() / 240.0); scale(factor, factor); event->accept(); }
[ "sensarliar@gmail.com" ]
sensarliar@gmail.com
58d93b7d07ab3062c0dc2f218c1a7e0d8508651e
e94caa5e0894eb25ff09ad75aa104e484d9f0582
/data/s66/rpa/hf/58/AB/cc-pVTZ/restart.cc
dbb5195d9d77e0223a619b04413eead93b7eddd2
[]
no_license
bdnguye2/divergence_mbpt_noncovalent
d74e5d755497509026e4ac0213ed66f3ca296908
f29b8c75ba2f1c281a9b81979d2a66d2fd48e09c
refs/heads/master
2022-04-14T14:09:08.951134
2020-04-04T10:49:03
2020-04-04T10:49:03
240,377,466
0
0
null
null
null
null
UTF-8
C++
false
false
444
cc
$chkbas= 35888.6453527893 $nucrep= 577.235386768728 $chkaux= 201147052.186550 $chkupro= 1.00000000000000 $chkipro= 2.00000000000000 $chklasrep= 1.00000000000000 $chkisy6= 4.00000000000000 $chkmos= 228.002125144891 $chkCCVPQ_ISQR= 3910.41708644236 $chkbqia= 40.8705321540233 $chkr0_MP2= 0.00000000000000 $energy_MP2= -495.527978904777 $sccss= 1.00000000000000 $sccos= 1.00000000000000 $end
[ "bdnguye2@uci.edu" ]
bdnguye2@uci.edu
1e530fc6d0526e2d7864a10212d849c0d8f5dd44
3259934ca94ea655c07b34e773c327c2c9ed95c6
/phase_contrast_preconditioning/meshgrid.cpp
e32c7da3e17e75dcf72b1454c158262e7783f62f
[]
no_license
agasa17/phase_contrast_preconditioning
d4d5a4d8a56c28b14ddc87b7556db04a746d5311
c5ace12abfb07c8b9288115683af7bd361d533d7
refs/heads/master
2016-08-05T09:11:03.639625
2014-11-18T21:28:53
2014-11-18T21:28:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
#include <opencv2/core/core.hpp> void meshgrid(const cv::Mat &xgv, const cv::Mat &ygv, cv::Mat &X, cv::Mat &Y) { cv::repeat(xgv.reshape(1, 1), ygv.total(), 1, X); cv::repeat(ygv.reshape(1, 1).t(), 1, xgv.total(), Y); } // helper function (maybe that goes somehow easier) void meshgridTest(const cv::Range &xgv, const cv::Range &ygv, cv::Mat &X, cv::Mat &Y) { std::vector<int> t_x, t_y; for (int i = xgv.start; i <= xgv.end; i++) t_x.push_back(i); for (int i = ygv.start; i <= ygv.end; i++) t_y.push_back(i); meshgrid(cv::Mat(t_x), cv::Mat(t_y), X, Y); }
[ "s2na.mn23@gmail.com" ]
s2na.mn23@gmail.com
ffc0c56b23695b965fc0a369afaee4fd5c089606
7d8627273662415b2cd64c3c32fb18c613dacd79
/src/saisieQT/main/saisieMasqQT_main.cpp
3b82369c58d37bd370828524f12ef89d05b01b76
[]
no_license
caomw/micmac
0a60d17341a353e645926e7bf7c03eee8f10a971
9233424efe81da6c710194eec4c58c20c35ee83e
refs/heads/master
2021-01-09T06:33:16.126905
2015-03-16T14:37:04
2015-03-16T14:37:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,110
cpp
#include "saisieQT_main.h" int saisieMasqQT_main(QApplication &app, int argc, char *argv[]) { MMD_InitArgcArgv(argc,argv); Pt2di SzWP = Pt2di(900,700); std::string aFullName =""; std::string aPost("_Masq"); std::string aNameMasq =""; std::string aAttr=""; double aGama=1.0; if (argv[1][0] == 'v') { argv++; argc--; argv[0] = (char*) "SaisieMasqQT"; MMVisualMode = true; saisieMasq_ElInitArgMain(argc, argv, aFullName, aPost, aNameMasq, aAttr, SzWP, aGama); MMVisualMode = false; return EXIT_SUCCESS; } else { //Set application name before SaisieQtWindow creation to read settings app.setApplicationName("SaisieMasqQT"); app.setOrganizationName("Culture3D"); QStringList cmdline_args = QCoreApplication::arguments(); loadTranslation(app); SaisieQtWindow w; #ifdef _DEBUG for (int aK=0; aK < cmdline_args.size();++aK) cout << "arguments : " << cmdline_args[aK].toStdString().c_str() << endl; #endif if ((cmdline_args.size() == 3) && (cmdline_args.back().contains("help"))) { QString help = app.applicationName() +" [filename] [option=]\n\n" "* [filename] string\t: open file (image or ply or camera xml)\n\n" "Options\n\n" "* [Name=SzW] Pt2di\t: set window size (default=[900,700])\n" "* [Name=Post] string\t: change postfix output file (default=_Masq)\n" "* [Name=Name] string\t: set output filename (default=input+_Masq)\n" "* [Name=Gama] REAL\t: apply gamma to image\n" "* [Name=Attr] string\t: string to add to postfix\n\n" "Example: mm3d " + app.applicationName() + " IMG.tif SzW=[1200,800] Name=PLAN Gama=1.5\n\n" "NB: \n" "1: "+ app.applicationName() + " can be run without any argument\n" "2: visual interface for argument edition available with command: mm3d v" + app.applicationName() + "\n\n"; return helpMessage(app, help); } else if (cmdline_args.size() != 2) { argc--; argv++; saisieMasq_ElInitArgMain(argc, argv, aFullName, aPost, aNameMasq, aAttr, SzWP, aGama); if (EAMIsInit(&aPost)) w.setPostFix(QString(aPost.c_str())); else w.setPostFix("_Masq"); if (EAMIsInit(&aAttr)) w.setPostFix(w.getPostFix() + QString(aAttr.c_str())); if (EAMIsInit(&aGama)) w.setGamma(aGama); if(EAMIsInit(&aNameMasq)) w.getEngine()->setFilenameOut(QString(aNameMasq.c_str())); w.resize(SzWP.x,SzWP.y); } w.show(); if (aFullName != "") { QStringList filenames; filenames.push_back(QString(aFullName.c_str())); w.addFiles(filenames,true); } return app.exec(); } }
[ "helio@kde.org" ]
helio@kde.org
0281a380a6a3e8f9280be3ea87dd5b6ce1c0c66e
5216bf9769cd1ca05248d2441c039e8ee287b616
/salsa20.h
aebefb69efb73046f3e2760355a276b35f28eea9
[]
no_license
zichengl/Gee-Mail
442c508e94b588e69eb66003fa0e7194a4231363
1761476676bda07c196718588697105a23b0432e
refs/heads/master
2021-01-12T09:37:24.981087
2016-12-12T21:25:19
2016-12-12T21:25:19
76,200,332
0
0
null
null
null
null
UTF-8
C++
false
false
495
h
#ifndef SALSA20_H_ #define SALSA20_H_ #include <iostream> #include <string> #include "crypto++/osrng.h" #include "crypto++/salsa.h" #include "crypto++/hex.h" #include "crypto++/filters.h" #include "sha.h" using namespace CryptoPP; using namespace std; string encrypt(string text,string passPhrase); string salsa_encrypt(byte* keyBytes,byte* textBytes,int numBytes); string decrypt(string ciphertextStr,string passPhrase); string salsa_decrypt(string ciphertextStr, byte* key, byte* iv); #endif
[ "zcliu@udel.edu" ]
zcliu@udel.edu
0b3c079efdf0fd4bf468845f58502e25eec97ac7
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/third_party/blink/renderer/modules/gamepad/gamepad_dispatcher.cc
2a06737b891e46904267ec01e79b55317412748b
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
3,272
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 "third_party/blink/renderer/modules/gamepad/gamepad_dispatcher.h" #include "device/gamepad/public/cpp/gamepads.h" #include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/modules/gamepad/gamepad_shared_memory_reader.h" #include "third_party/blink/renderer/modules/gamepad/navigator_gamepad.h" namespace blink { using device::mojom::blink::GamepadHapticsManager; void GamepadDispatcher::SampleGamepads(device::Gamepads& gamepads) { if (reader_) { reader_->SampleGamepads(gamepads); } } void GamepadDispatcher::PlayVibrationEffectOnce( uint32_t pad_index, device::mojom::blink::GamepadHapticEffectType type, device::mojom::blink::GamepadEffectParametersPtr params, GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) { InitializeHaptics(); gamepad_haptics_manager_remote_->PlayVibrationEffectOnce( pad_index, type, std::move(params), std::move(callback)); } void GamepadDispatcher::ResetVibrationActuator( uint32_t pad_index, GamepadHapticsManager::ResetVibrationActuatorCallback callback) { InitializeHaptics(); gamepad_haptics_manager_remote_->ResetVibrationActuator(pad_index, std::move(callback)); } GamepadDispatcher::GamepadDispatcher( scoped_refptr<base::SingleThreadTaskRunner> task_runner) : task_runner_(std::move(task_runner)) {} GamepadDispatcher::~GamepadDispatcher() = default; void GamepadDispatcher::InitializeHaptics() { if (!gamepad_haptics_manager_remote_) { Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( gamepad_haptics_manager_remote_.BindNewPipeAndPassReceiver( task_runner_)); } } void GamepadDispatcher::Trace(Visitor* visitor) { PlatformEventDispatcher::Trace(visitor); } void GamepadDispatcher::DidConnectGamepad(uint32_t index, const device::Gamepad& gamepad) { DispatchDidConnectOrDisconnectGamepad(index, gamepad, true); } void GamepadDispatcher::DidDisconnectGamepad(uint32_t index, const device::Gamepad& gamepad) { DispatchDidConnectOrDisconnectGamepad(index, gamepad, false); } void GamepadDispatcher::ButtonOrAxisDidChange(uint32_t index, const device::Gamepad& gamepad) { DCHECK_LT(index, device::Gamepads::kItemsLengthCap); NotifyControllers(); } void GamepadDispatcher::DispatchDidConnectOrDisconnectGamepad( uint32_t index, const device::Gamepad& gamepad, bool connected) { DCHECK_LT(index, device::Gamepads::kItemsLengthCap); DCHECK_EQ(connected, gamepad.connected); NotifyControllers(); } void GamepadDispatcher::StartListening(LocalFrame* frame) { if (!reader_) { DCHECK(frame); reader_ = std::make_unique<GamepadSharedMemoryReader>(*frame); } reader_->Start(this); } void GamepadDispatcher::StopListening() { if (reader_) reader_->Stop(); } } // namespace blink
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
0830a33d34f8d7f5b77c8afbaa7621a9906b23b5
a15950e54e6775e6f7f7004bb90a5585405eade7
/chromeos/services/device_sync/fake_device_sync_observer.cc
e0d0880d25496761800dd34facc8edf744299f68
[ "BSD-3-Clause" ]
permissive
whycoding126/chromium
19f6b44d0ec3e4f1b5ef61cc083cae587de3df73
9191e417b00328d59a7060fa6bbef061a3fe4ce4
refs/heads/master
2023-02-26T22:57:28.582142
2018-04-09T11:12:57
2018-04-09T11:12:57
128,760,157
1
0
null
2018-04-09T11:17:03
2018-04-09T11:17:03
null
UTF-8
C++
false
false
1,204
cc
// Copyright 2018 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 "chromeos/services/device_sync/fake_device_sync_observer.h" namespace chromeos { namespace device_sync { FakeDeviceSyncObserver::FakeDeviceSyncObserver() = default; FakeDeviceSyncObserver::~FakeDeviceSyncObserver() = default; void FakeDeviceSyncObserver::SetDelegate(Delegate* delegate) { delegate_ = delegate; } mojom::DeviceSyncObserverPtr FakeDeviceSyncObserver::GenerateInterfacePtr() { mojom::DeviceSyncObserverPtr interface_ptr; bindings_.AddBinding(this, mojo::MakeRequest(&interface_ptr)); return interface_ptr; } void FakeDeviceSyncObserver::OnEnrollmentFinished(bool success) { if (success) ++num_enrollment_success_events_; else ++num_enrollment_failure_events_; if (delegate_) delegate_->OnEnrollmentFinishedCalled(); } void FakeDeviceSyncObserver::OnDevicesSynced(bool success) { if (success) ++num_sync_success_events_; else ++num_sync_failure_events_; if (delegate_) delegate_->OnDevicesSyncedCalled(); } } // namespace device_sync } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f4a71b4562d130bbed659f393d3c911de14eaaf9
bcd122dc1ec9131f148178950a1a9b6e0b61c808
/src/libinterpolviz/include/interpolviz/utils/fileutils.h
792804f86523b7687748c9996b0c6b41ebf0e846
[ "MIT" ]
permissive
QubingHuo-source/interpolation-methods
88d73cef91ad4ad4b2a8455a79d0bffc9817b535
094cbabbd0c25743d088a623f5913149c6b8a2ab
refs/heads/master
2023-04-30T19:55:29.781785
2020-02-21T13:14:30
2020-02-21T13:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
h
/** * This file is part of https://github.com/adrelino/interpolation-methods * * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #ifndef INTERPOL_FILEUTILS_H #define INTERPOL_FILEUTILS_H #include <iostream> #include <vector> #include <string> #include <fstream> namespace interpol { namespace fileutils { template<typename Number> void saveVector(const std::string& filename, const std::vector<Number>& vec){ std::ofstream outputFile(filename, std::ofstream::out) ; for (const auto& it : vec){ outputFile << it <<std::endl; } outputFile.close( ); std::cout<<"Wrote "<<vec.size()<<" numbers to "<<filename<<std::endl; } template<typename Number> void loadVector(const std::string& filename, std::vector<Number>& vec){ std::ifstream file(filename,std::ifstream::in); vec.clear(); if( file.fail() == true ) { std::cerr << filename << " could not be opened" << std::endl; }else{ Number elem; while(file >> elem){ vec.push_back(elem); } } } template<typename Number> std::vector<Number> loadVector(std::string filename){ std::vector<Number> vec; loadVector(filename,vec); return vec; } } // ns fileutils } // ns interpol #endif // INTERPOL_FILEUTILS_H
[ "mail@adrian-haarbach.de" ]
mail@adrian-haarbach.de
195bf87b96acdde2671d1f26c8cd011548f131b7
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/multimedia/danim/src/appel/backend/callback.cpp
5fc8129810c93bf881317ada6ac9322ae37b303f
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,535
cpp
/******************************************************************************* Copyright (c) 1995-97 Microsoft Corporation Abstract: Callback behaviors *******************************************************************************/ #include <headers.h> #include "perf.h" #include "bvr.h" #include "values.h" #include "jaxaimpl.h" #include "privinc/debug.h" class TmpConstBvrImpl : public BvrImpl { public: TmpConstBvrImpl(AxAValue c) : _cnst(c) { Assert(c); } // Override the main Perform since it doesn't need the cache virtual Perf Perform(PerfParam& p) { return _Perform(p); } virtual Perf _Perform(PerfParam&) { RaiseException_UserError(E_FAIL, IDS_ERR_BE_TRANS_CONST_BVR); return NULL; } virtual AxAValue GetConst(ConstParam & cp) { return _cnst; } virtual void _DoKids(GCFuncObj proc) { (*proc)(_cnst); } #if _USE_PRINT virtual ostream& Print(ostream& os) { return os << _cnst; } #endif virtual DXMTypeInfo GetTypeInfo () { if (_cnst == NULL) RaiseException_UserError(E_FAIL, IDS_ERR_BE_TRANS_GONE); return _cnst->GetTypeInfo(); } void Invalidate() { _cnst = NULL; } void Set(AxAValue v) { _cnst = v; } protected: AxAValue _cnst; }; // // Implementation for bvr hook // class CallbackPerfImpl : public PerfImpl { public: CallbackPerfImpl(int id, Perf perf, Bvr cur, Time t0, TimeXform tt, BvrHook h) : _id(id), _perf(perf), _cur(cur), _notifier(h), _t0(t0), _tt(tt),_tmp(NULL) {} // TODO: Well, don't want constant folding here // Maybe we do... virtual AxAValue _GetRBConst(RBConstParam& id) { if (_perf) { // Go down to calculate as much rb const as we can, though // we say we're not constant _perf->GetRBConst(id); } return NULL; } //{ return _perf ? _perf->GetRBConst(id) : NULL; } // TODO: Well, don't want constant folding here // Maybe we do... virtual AxAValue GetConst(ConstParam & cp) { return NULL; } void _DoKids(GCFuncObj proc) { (*proc)(_perf); (*proc)(_cur); (*proc)(_notifier); (*proc)(_tt); if (_tmp) (*proc)(_tmp); } virtual AxAValue _Sample(Param& p) { AxAValue v = _perf->Sample(p); if (!p._noHook) { if (_tmp) _tmp->Set(v); else _tmp = NEW TmpConstBvrImpl(v); double localTime = EvalLocalTime(p, _tt); Bvr result = _notifier-> Notify(_id, FALSE, _t0, p._time, localTime, _tmp, _cur); if (result) { ConstParam cp; v = result->GetConst(cp); } _tmp->Invalidate(); if (!v) { RaiseException_UserError(E_FAIL, IDS_ERR_BE_BADHOOKRETURN); } } return v; } #if _USE_PRINT ostream& Print(ostream& os) { return os << _perf; } #endif private: TmpConstBvrImpl *_tmp; Perf _perf; BvrHook _notifier; Bvr _cur; TimeXform _tt; int _id; Time _t0; }; class CallbackBvrImpl : public BvrImpl { public: CallbackBvrImpl(Bvr b, BvrHook h) : _bvr(b), _notifier(h), _type(b->GetTypeInfo()), _id(0) {} virtual DWORD GetInfo(bool recalc) { return _bvr->GetInfo(recalc); } virtual Perf _Perform(PerfParam& pp) { Param p(pp._t0); Perf perf = ::Perform(_bvr, pp); AxAValue v = perf->Sample(p); TmpConstBvrImpl *tmp = NEW TmpConstBvrImpl(v); Bvr b0 = StartedBvr(perf, _type); _notifier->Notify(++_id, TRUE, pp._t0, pp._t0, 0.0, tmp, b0); tmp->Invalidate(); return NEW CallbackPerfImpl(_id, perf, b0, pp._t0, pp._tt, _notifier); } // TODO: Well, don't want constant folding here // Maybe we do... virtual AxAValue GetConst(ConstParam & cp) { return NULL; } Bvr EndEvent(Bvr overrideEvent) { return _bvr->EndEvent(overrideEvent); } void _DoKids(GCFuncObj proc) { (*proc)(_bvr); (*proc)(_notifier); (*proc)(_type); } #if _USE_PRINT ostream& Print(ostream& os) { return os << _bvr; } #endif virtual DXMTypeInfo GetTypeInfo () { return _type; } private: Bvr _bvr; BvrHook _notifier; DXMTypeInfo _type; int _id; }; Bvr BvrCallback(Bvr b, BvrHook notifier) { return NEW CallbackBvrImpl(b, notifier); }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
b908b78d0693a2e1db5f22108a811b1a773858b5
97101ce54b261b827ea3023c3e8cb50e47c296c1
/Flounder.Core/src/maths/Transform.cpp
21197a4c67f39a2ca5cbce66bac8952cfb1fb166
[ "MIT" ]
permissive
cappah/Flounder
f93a2db330aa79161a718d511075558b7b64cc30
36c7f69ca0c1fad4a2e300cc5d0b178912b88bbf
refs/heads/master
2021-07-22T18:49:21.956455
2017-11-02T11:45:31
2017-11-02T11:45:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
cpp
#include "Transform.hpp" namespace Flounder { Transform::Transform() : m_position(new Vector3()), m_rotation(new Vector3()), m_scaling(new Vector3()) { } Transform::Transform(const Transform &source) : m_position(new Vector3(*source.m_position)), m_rotation(new Vector3(*source.m_rotation)), m_scaling(new Vector3(*source.m_scaling)) { } Transform::Transform(const Vector3 &position, const Vector3 &rotation, const Vector3 &scaling) : m_position(new Vector3(position)), m_rotation(new Vector3(rotation)), m_scaling(new Vector3(scaling)) { } Transform::~Transform() { delete m_position; delete m_rotation; delete m_scaling; } Matrix4 *Transform::GetWorldMatrix(Matrix4 *destination) const { return Matrix4::TransformationMatrix(*m_position, *m_rotation, *m_scaling, destination); } Matrix4 *Transform::GetModelMatrix(Matrix4 *destination) const { return Matrix4::TransformationMatrix(Vector3(), *m_rotation, Vector3(), destination); } void Transform::Set(const Transform &source) const { m_position->Set(*source.m_position); m_rotation->Set(*source.m_rotation); m_scaling->Set(*source.m_scaling); } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
12bf43ff0e96119a4c0a720837e2034076f62030
7b1eb5a031a8a1db81abf72954316011374e7546
/safe_memcpy.hpp
3c9c925bb2abe96efec263bb33747810a1e96fb4
[ "MIT" ]
permissive
wangzhicheng2013/safe_memcpy
891943d793a426af559ed10d49fb5836a4cef06f
0e99287ce3792d49fb7918f7ab15962e4a77c00b
refs/heads/main
2023-04-28T10:55:32.190259
2021-05-28T08:12:17
2021-05-28T08:12:17
371,628,601
1
0
null
null
null
null
UTF-8
C++
false
false
934
hpp
#pragma once #include <stdint.h> #include <string.h> static inline bool between(const uint8_t *start, const uint8_t *end, const uint8_t *p) { return (p < end) && (p >= start); } static inline bool safe_check(void *dst, size_t len, const void *start, const void *end) { if (len < 1) { return false; } if (!dst || !start || !end) { return false; } void *last_pos = ((uint8_t *)dst) + len - 1; if (last_pos < dst) { return false; } return between((uint8_t *)start, (uint8_t *)end, (uint8_t *)dst) && between((uint8_t *)start, (uint8_t *)end, (uint8_t *)last_pos); } static inline bool safe_memcpy(void *dst, const void *src, size_t len, const void *start, const void *end) { if (!safe_check(dst, len, start, end)) { return false; } if (!src) { return false; } memcpy(dst, src, len); return true; }
[ "noreply@github.com" ]
wangzhicheng2013.noreply@github.com
8b57ad3314d288d8ac197a2f35f481e9884c1843
659a4753fadd4266acb522c75da0a8f0fadd1e55
/source/imebra/base/src/baseObject.cpp
190218a38db313c386f283fab1a974ebef3cc796
[]
no_license
hackerlank/ImageSegmentationEditor
a071153343eaf2e65d9265d8c2fb3b65031f5974
f169c93a4a9d3269c97e764beadaa00d5304d57d
refs/heads/master
2020-06-12T18:45:31.880872
2015-07-28T02:10:20
2015-07-28T02:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,133
cpp
/* Imebra 2011 build 2013-07-16_08-42-08 Imebra: a C++ Dicom library Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 by Paolo Brandoli/Binarno s.p. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ------------------- If you want to use Imebra commercially then you have to buy the commercial support available at http://imebra.com After you buy the commercial support then you can use Imebra according to the terms described in the Imebra Commercial License Version 1. A copy of the Imebra Commercial License Version 1 is available in the documentation pages. Imebra is available at http://imebra.com The author can be contacted by email at info@binarno.com or by mail at the following address: Paolo Brandoli Rakuseva 14 1000 Ljubljana Slovenia */ /*! \file baseObject.cpp \brief Implementation of the baseObject class. */ #include "../include/baseObject.h" #include "../include/exception.h" #include <iostream> namespace puntoexe { /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // basePtr // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Default constructor // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// basePtr::basePtr() : object(0) { } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Constructor with initialization // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// basePtr::basePtr(baseObject* pObject): object(pObject) { addRef(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Destructor // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// basePtr::~basePtr() { release(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Release // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void basePtr::release() { if(object != 0) { object->release(); object = 0; } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Increase reference counter // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void basePtr::addRef() { if(object != 0) { object->addRef(); } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // // baseObject // // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Default constructor // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// baseObject::baseObject(): m_lockCounter(0), m_bValid(true), m_pCriticalSection(new CObjectCriticalSection) { m_pCriticalSection->addRef(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Constructs the object and set an external lock // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// baseObject::baseObject(const ptr<baseObject>& externalLock): m_lockCounter(0), m_bValid(true) { if(externalLock == 0) { m_pCriticalSection = new CObjectCriticalSection; } else { m_pCriticalSection = externalLock->m_pCriticalSection; } m_pCriticalSection->addRef(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Return true if the object is referenced once. // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// bool baseObject::isReferencedOnce() { lockCriticalSection lockThis(&m_counterCriticalSection); return m_lockCounter == 1; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Destructor // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// baseObject::~baseObject() { m_pCriticalSection->release(); m_bValid = false; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Increase the references counter // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void baseObject::addRef() { if(this == 0) { return; } lockCriticalSection lockThis(&m_counterCriticalSection); ++m_lockCounter; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Decrease the references counter and delete the object // if the counter reaches 0 // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void baseObject::release() { // Calling release on a non-existing object. // Simply return /////////////////////////////////////////////////////////// if(this == 0) { return; } // Decrease the reference counter /////////////////////////////////////////////////////////// { lockCriticalSection lockThis(&m_counterCriticalSection); if(--m_lockCounter != 0) { return; } } if(!preDelete()) { return; } delete this; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // This function is called by release() just before // the object is deleted. // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// bool baseObject::preDelete() { return true; } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Lock the object // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void baseObject::lock() { if(this == 0) { return; } m_pCriticalSection->m_criticalSection.lock(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Unlock the object // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void baseObject::unlock() { if(this == 0) { return; } m_pCriticalSection->m_criticalSection.unlock(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // // lockObject // // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Lock the specified object // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// lockObject::lockObject(baseObject* pObject) { m_pObject = pObject; if(m_pObject != 0) { m_pObject->lock(); } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Unlock the specified object // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// lockObject::~lockObject() { unlock(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Unlock the specified object // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void lockObject::unlock() { if( m_pObject != 0) { m_pObject->unlock(); m_pObject = 0; } } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // // lockMultipleObject // // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Lock the specified objects // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// lockMultipleObjects::lockMultipleObjects(tObjectsList* pObjectsList) { tCriticalSectionsList csList; for(tObjectsList::iterator scanObjects = pObjectsList->begin(); scanObjects != pObjectsList->end(); ++scanObjects) { if((*scanObjects) == 0) { continue; } csList.push_back(&( (*scanObjects)->m_pCriticalSection->m_criticalSection) ); } m_pLockedCS.reset(puntoexe::lockMultipleCriticalSections(&csList)); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Unlock the locked objects // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// lockMultipleObjects::~lockMultipleObjects() { unlock(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Unlock the locked objects // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void lockMultipleObjects::unlock() { if(m_pLockedCS.get() == 0) { return; } puntoexe::unlockMultipleCriticalSections(m_pLockedCS.get()); m_pLockedCS.reset(); } } // namespace puntoexe
[ "haukebartsch@gmail.com" ]
haukebartsch@gmail.com
fc502c4b6c15e964914ad578f1b68749f773659d
6e2f3b5c27df0cbcc6174bf926be729aa63ef1ea
/Include/xsim/generated/AngleV1.hpp
8d82801ab2901484318be8204d993cef4000418b
[ "LicenseRef-scancode-object-form-exception-to-mit", "MIT", "BSL-1.0" ]
permissive
raving-bots/expansim-sdk
349b18875c9530bb4a5b32c5fd063036ce1ae269
22f5c794523abbe9c27688963b607b13671ff118
refs/heads/master
2021-10-22T10:21:00.872874
2021-10-18T19:58:47
2021-10-18T19:58:47
223,376,080
2
1
null
null
null
null
UTF-8
C++
false
false
1,656
hpp
// Copyright Raving Bots 2018-2021 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file SDK-LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) // <auto-generated> // WARNING: This file has been generated automatically. Do not edit manually, changes will be lost. // </auto-generated> #pragma once #include <xsim/types.hpp> namespace xsim { struct AngleV1 final { constexpr AngleV1() = default; constexpr AngleV1(const AngleV1&) = default; constexpr AngleV1(AngleV1&&) = default; ~AngleV1() = default; constexpr AngleV1& operator=(const AngleV1&) = default; constexpr AngleV1& operator=(AngleV1&&) = default; constexpr AngleV1(float value) : m_Value(value) { } constexpr float Value() const { return m_Value; } friend constexpr bool operator==(const AngleV1& left, const AngleV1& right) { return left.m_Value == right.m_Value; } friend constexpr bool operator!=(const AngleV1& left, const AngleV1& right) { return left.m_Value != right.m_Value; } private: float m_Value{}; }; } static_assert( std::is_standard_layout<::xsim::AngleV1>::value, "SDK bug: TypeStruct AngleV1 not standard layout" ); namespace fmt { template <typename Char> struct formatter<::xsim::AngleV1, Char> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const ::xsim::AngleV1& value, FormatContext& ctx) { return format_to(ctx.out(), XSIM_FMT_LITERAL("{}"), value.Value()); } }; }
[ "me@catpp.eu" ]
me@catpp.eu
caa68e1d78ac53d89684dbdc07b4d65999b1d227
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Segmentation/LevelSetsv4/include/itkBinaryImageToLevelSetImageAdaptor.hxx
30d00f33b7376d09236e339f68a4d9e18f9b51dd
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "Zlib", "MIT", "LicenseRef-scancode-proprietary-license", "Spencer-86", "Apache-2.0", "FSFUL", "LicenseRef-scancode-public-domain", "Libpng", "BSD-2-Clause" ]
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
25,543
hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkBinaryImageToLevelSetImageAdaptor_hxx #define itkBinaryImageToLevelSetImageAdaptor_hxx #include "itkBinaryImageToLevelSetImageAdaptor.h" #include "itkSignedMaurerDistanceMapImageFilter.h" namespace itk { template< typename TInputImage, typename TLevelSetImage > BinaryImageToLevelSetImageAdaptor< TInputImage, LevelSetDenseImage< TLevelSetImage > > ::BinaryImageToLevelSetImageAdaptor() { this->m_SignedDistanceTransformFilter = SignedMaurerDistanceMapImageFilter< InputImageType, LevelSetImageType >::New(); } template< typename TInputImage, typename TLevelSetImage > BinaryImageToLevelSetImageAdaptor< TInputImage, LevelSetDenseImage< TLevelSetImage > > ::~BinaryImageToLevelSetImageAdaptor() {} template< typename TInputImage, typename TLevelSetImage > void BinaryImageToLevelSetImageAdaptor< TInputImage, LevelSetDenseImage< TLevelSetImage > > ::Initialize() { if( this->m_InputImage.IsNull() ) { itkGenericExceptionMacro( "m_InputImage is ITK_NULLPTR" ); } if( m_SignedDistanceTransformFilter.IsNull() ) { itkGenericExceptionMacro( "m_SignedDistanceTransformFilter is ITK_NULLPTR" ); } m_SignedDistanceTransformFilter->SetInput( this->m_InputImage ); m_SignedDistanceTransformFilter->Update(); typename LevelSetImageType::Pointer tempImage = LevelSetImageType::New(); tempImage->Graft( m_SignedDistanceTransformFilter->GetOutput() ); this->m_LevelSet = LevelSetType::New(); this->m_LevelSet->SetImage( tempImage ); } template< typename TInput, typename TOutput > BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::BinaryImageToLevelSetImageAdaptor() {} template< typename TInput, typename TOutput > BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::~BinaryImageToLevelSetImageAdaptor() { } template< typename TInput, typename TOutput > void BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::Initialize() { if( this->m_InputImage.IsNull() ) { itkGenericExceptionMacro( << "m_InputImage is ITK_NULLPTR" ); } this->m_LabelMap = LevelSetLabelMapType::New(); this->m_LabelMap->SetBackgroundValue( LevelSetType::PlusThreeLayer() ); this->m_LabelMap->CopyInformation( this->m_InputImage ); this->m_InternalImage = InternalImageType::New(); this->m_InternalImage->CopyInformation( this->m_InputImage ); this->m_InternalImage->SetRegions( this->m_InputImage->GetBufferedRegion() ); this->m_InternalImage->Allocate(); this->m_InternalImage->FillBuffer( LevelSetType::PlusThreeLayer() ); LevelSetLabelObjectPointer innerPart = LevelSetLabelObjectType::New(); innerPart->SetLabel( LevelSetType::MinusThreeLayer() ); // Precondition labelmap and phi InputIteratorType inputIt( this->m_InputImage, this->m_InputImage->GetLargestPossibleRegion() ); inputIt.GoToBegin(); InternalIteratorType internalIt( this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); internalIt.GoToBegin(); while( !inputIt.IsAtEnd() ) { if ( inputIt.Get() != NumericTraits< InputImagePixelType >::ZeroValue() ) { innerPart->AddIndex( inputIt.GetIndex() ); internalIt.Set( LevelSetType::MinusThreeLayer() ); } ++internalIt; ++inputIt; } innerPart->Optimize(); this->m_LabelMap->AddLabelObject( innerPart ); FindActiveLayer(); FindPlusOneMinusOneLayer(); PropagateToOuterLayers( LevelSetType::MinusOneLayer(), LevelSetType::MinusTwoLayer(), LevelSetType::MinusThreeLayer() ); PropagateToOuterLayers( LevelSetType::PlusOneLayer(), LevelSetType::PlusTwoLayer(), LevelSetType::PlusThreeLayer() ); this->m_LabelMap->Optimize(); this->m_LevelSet->SetLabelMap( this->m_LabelMap ); // release the memory this->m_InternalImage = ITK_NULLPTR; } template< typename TInput, typename TOutput > void BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::PropagateToOuterLayers( LayerIdType layerToBeScanned, LayerIdType outputLayer, LayerIdType testValue ) { const LevelSetLayerType layerPlus1 = this->m_LevelSet->GetLayer( layerToBeScanned ); LevelSetLayerType & layerPlus2 = this->m_LevelSet->GetLayer( outputLayer ); const LevelSetOutputType plus2 = static_cast< LevelSetOutputType >( outputLayer ); typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); ZeroFluxNeumannBoundaryCondition< InternalImageType > im_nbc; NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &im_nbc ); typename NeighborhoodIteratorType::OffsetType neighOffset; neighOffset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { neighOffset[dim] = -1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 0; } // iterate on the layer to be scanned LevelSetLayerConstIterator nodeIt = layerPlus1.begin(); LevelSetLayerConstIterator nodeEnd = layerPlus1.end(); while( nodeIt != nodeEnd ) { LevelSetInputType idx = nodeIt->first; neighIt.SetLocation( idx ); for( typename NeighborhoodIteratorType::Iterator it = neighIt.Begin(); !it.IsAtEnd(); ++it ) { // check if in the neighborhood there are values equal to testValue if( it.Get() == testValue ) { LevelSetInputType tempIndex = neighIt.GetIndex( it.GetNeighborhoodOffset() ); layerPlus2.insert( LayerPairType( tempIndex, plus2 ) ); } } ++nodeIt; } LevelSetLabelObjectPointer ObjectPlus2 = LevelSetLabelObjectType::New(); ObjectPlus2->SetLabel( int(outputLayer) ); nodeIt = layerPlus2.begin(); nodeEnd = layerPlus2.end(); while( nodeIt != nodeEnd ) { if ( testValue != this->m_LabelMap->GetBackgroundValue() ) { this->m_LabelMap->GetLabelObject( testValue )->RemoveIndex( nodeIt->first ); } ObjectPlus2->AddIndex( nodeIt->first ); this->m_InternalImage->SetPixel( nodeIt->first, outputLayer ); ++nodeIt; } ObjectPlus2->Optimize(); this->m_LabelMap->AddLabelObject( ObjectPlus2 ); } template< typename TInput, typename TOutput > void BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::FindActiveLayer() { LevelSetLabelObjectPointer labelObject = this->m_LabelMap->GetLabelObject( LevelSetType::MinusThreeLayer() ); const LevelSetOutputType zero = NumericTraits< LevelSetOutputType >::ZeroValue(); LevelSetLayerType& layer0 = this->m_LevelSet->GetLayer( LevelSetType::ZeroLayer() ); typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); ZeroFluxNeumannBoundaryCondition< InternalImageType > im_nbc; NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &im_nbc ); typename NeighborhoodIteratorType::OffsetType neighOffset; neighOffset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { neighOffset[dim] = -1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 0; } typename LevelSetLabelObjectType::ConstIndexIterator lineIt( labelObject ); lineIt.GoToBegin(); while( !lineIt.IsAtEnd() ) { const LevelSetInputType & idx = lineIt.GetIndex(); neighIt.SetLocation( idx ); for( typename NeighborhoodIteratorType::Iterator it = neighIt.Begin(); !it.IsAtEnd(); ++it ) { if( it.Get() == LevelSetType::PlusThreeLayer() ) { layer0.insert( LayerPairType( idx, zero ) ); break; } } ++lineIt; } if( !layer0.empty() ) { LevelSetLabelObjectPointer ZeroSet = LevelSetLabelObjectType::New(); ZeroSet->SetLabel( LevelSetType::ZeroLayer() ); LevelSetLayerConstIterator nodeIt = layer0.begin(); LevelSetLayerConstIterator nodeEnd = layer0.end(); while( nodeIt != nodeEnd ) { this->m_LabelMap->GetLabelObject( LevelSetType::MinusThreeLayer() )->RemoveIndex( nodeIt->first ); ZeroSet->AddIndex( nodeIt->first ); this->m_InternalImage->SetPixel( nodeIt->first, LevelSetType::ZeroLayer() ); ++nodeIt; } ZeroSet->Optimize(); this->m_LabelMap->AddLabelObject( ZeroSet ); } } template< typename TInput, typename TOutput > void BinaryImageToLevelSetImageAdaptor< TInput, WhitakerSparseLevelSetImage< TOutput, TInput::ImageDimension > > ::FindPlusOneMinusOneLayer() { const LevelSetOutputType minus1 = - NumericTraits< LevelSetOutputType >::OneValue(); const LevelSetOutputType plus1 = NumericTraits< LevelSetOutputType >::OneValue(); const LevelSetLayerType layer0 = this->m_LevelSet->GetLayer( LevelSetType::ZeroLayer() ); LevelSetLayerType & layerMinus1 = this->m_LevelSet->GetLayer( LevelSetType::MinusOneLayer() ); LevelSetLayerType & layerPlus1 = this->m_LevelSet->GetLayer( LevelSetType::PlusOneLayer() ); typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); ZeroFluxNeumannBoundaryCondition< InternalImageType > im_nbc; NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &im_nbc ); typename NeighborhoodIteratorType::OffsetType neighOffset; neighOffset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { neighOffset[dim] = -1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 0; } LevelSetLayerConstIterator nodeIt = layer0.begin(); LevelSetLayerConstIterator nodeEnd = layer0.end(); while( nodeIt != nodeEnd ) { LevelSetInputType idx = nodeIt->first; neighIt.SetLocation( idx ); for( typename NeighborhoodIteratorType::Iterator it = neighIt.Begin(); !it.IsAtEnd(); ++it ) { if( it.Get() == LevelSetType::PlusThreeLayer() ) { LevelSetInputType tempIndex = neighIt.GetIndex( it.GetNeighborhoodOffset() ); layerPlus1.insert( LayerPairType( tempIndex, plus1 ) ); } if( it.Get() == LevelSetType::MinusThreeLayer() ) { LevelSetInputType tempIndex = neighIt.GetIndex( it.GetNeighborhoodOffset() ); layerMinus1.insert( LayerPairType( tempIndex, minus1 ) ); } } ++nodeIt; } LevelSetLabelObjectPointer ObjectMinus1 = LevelSetLabelObjectType::New(); ObjectMinus1->SetLabel( LevelSetType::MinusOneLayer() ); nodeIt = layerMinus1.begin(); nodeEnd = layerMinus1.end(); while( nodeIt != nodeEnd ) { this->m_LabelMap->GetLabelObject( LevelSetType::MinusThreeLayer() )->RemoveIndex( nodeIt->first ); ObjectMinus1->AddIndex( nodeIt->first ); this->m_InternalImage->SetPixel( nodeIt->first, LevelSetType::MinusOneLayer() ); ++nodeIt; } ObjectMinus1->Optimize(); this->m_LabelMap->AddLabelObject( ObjectMinus1 ); LevelSetLabelObjectPointer ObjectPlus1 = LevelSetLabelObjectType::New(); ObjectPlus1->SetLabel( LevelSetType::PlusOneLayer() ); nodeIt = layerPlus1.begin(); nodeEnd = layerPlus1.end(); while( nodeIt != nodeEnd ) { ObjectPlus1->AddIndex( nodeIt->first ); this->m_InternalImage->SetPixel( nodeIt->first, LevelSetType::PlusOneLayer() ); ++nodeIt; } ObjectPlus1->Optimize(); this->m_LabelMap->AddLabelObject( ObjectPlus1 ); } //////////////////////////////////////////////////////////////////////////////// template< typename TInput > BinaryImageToLevelSetImageAdaptor< TInput, ShiSparseLevelSetImage< TInput::ImageDimension > > ::BinaryImageToLevelSetImageAdaptor() {} template< typename TInput > BinaryImageToLevelSetImageAdaptor< TInput, ShiSparseLevelSetImage< TInput::ImageDimension > > ::~BinaryImageToLevelSetImageAdaptor() { } template< typename TInput > void BinaryImageToLevelSetImageAdaptor< TInput, ShiSparseLevelSetImage< TInput::ImageDimension > > ::Initialize() { if( this->m_InputImage.IsNull() ) { itkGenericExceptionMacro( << "m_InputImage is ITK_NULLPTR" ); } this->m_LabelMap = LevelSetLabelMapType::New(); this->m_LabelMap->SetBackgroundValue( LevelSetType::PlusThreeLayer() ); this->m_LabelMap->CopyInformation( this->m_InputImage ); this->m_InternalImage = InternalImageType::New(); this->m_InternalImage->CopyInformation( this->m_InputImage ); this->m_InternalImage->SetRegions( this->m_InputImage->GetBufferedRegion() ); this->m_InternalImage->Allocate(); this->m_InternalImage->FillBuffer( LevelSetType::PlusThreeLayer() ); LevelSetLabelObjectPointer innerPart = LevelSetLabelObjectType::New(); innerPart->SetLabel( LevelSetType::MinusThreeLayer() ); // Precondition labelmap and phi InputIteratorType iIt( this->m_InputImage, this->m_InputImage->GetLargestPossibleRegion() ); iIt.GoToBegin(); InternalIteratorType labelIt( this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); labelIt.GoToBegin(); while( !iIt.IsAtEnd() ) { if ( iIt.Get() != NumericTraits< InputImagePixelType >::ZeroValue() ) { innerPart->AddIndex( iIt.GetIndex() ); labelIt.Set( LevelSetType::MinusThreeLayer() ); } ++labelIt; ++iIt; } innerPart->Optimize(); this->m_LabelMap->AddLabelObject( innerPart ); FindActiveLayer(); this->m_LevelSet->SetLabelMap( this->m_LabelMap ); this->m_InternalImage = ITK_NULLPTR; } template< typename TInput > void BinaryImageToLevelSetImageAdaptor< TInput, ShiSparseLevelSetImage< TInput::ImageDimension > > ::FindActiveLayer() { LevelSetLabelObjectPointer labelObject = this->m_LabelMap->GetLabelObject( LevelSetType::MinusThreeLayer() ); LevelSetLayerType & layerMinus1 = this->m_LevelSet->GetLayer( LevelSetType::MinusOneLayer() ); LevelSetLayerType & layerPlus1 = this->m_LevelSet->GetLayer( LevelSetType::PlusOneLayer() ); typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); ZeroFluxNeumannBoundaryCondition< InternalImageType > im_nbc; NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &im_nbc ); typename NeighborhoodIteratorType::OffsetType neighOffset; neighOffset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { neighOffset[dim] = -1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 0; } typename LevelSetLabelObjectType::ConstIndexIterator lineIt( labelObject ); lineIt.GoToBegin(); while( !lineIt.IsAtEnd() ) { const LevelSetInputType & idx = lineIt.GetIndex(); neighIt.SetLocation( idx ); bool boundary = false; for( typename NeighborhoodIteratorType::Iterator it = neighIt.Begin(); !it.IsAtEnd(); ++it ) { if( it.Get() == LevelSetType::PlusThreeLayer() ) { LevelSetInputType tempIndex = neighIt.GetIndex( it.GetNeighborhoodOffset() ); layerPlus1.insert( LayerPairType( tempIndex, LevelSetOutputType(1.0) ) ); boundary = true; } } if( boundary ) { layerMinus1.insert( LayerPairType( idx, LevelSetOutputType(-1.0) ) ); } ++lineIt; } LevelSetLabelObjectPointer ObjectMinus1 = LevelSetLabelObjectType::New(); ObjectMinus1->SetLabel( LevelSetType::MinusOneLayer() ); LevelSetLayerConstIterator nodeIt = layerMinus1.begin(); LevelSetLayerConstIterator nodeEnd = layerMinus1.end(); while( nodeIt != nodeEnd ) { this->m_LabelMap->GetLabelObject( LevelSetType::MinusThreeLayer() )->RemoveIndex( nodeIt->first ); ObjectMinus1->AddIndex( nodeIt->first ); ++nodeIt; } ObjectMinus1->Optimize(); this->m_LabelMap->AddLabelObject( ObjectMinus1 ); LevelSetLabelObjectPointer ObjectPlus1 = LevelSetLabelObjectType::New(); ObjectPlus1->SetLabel( LevelSetType::PlusOneLayer() ); nodeIt = layerPlus1.begin(); nodeEnd = layerPlus1.end(); while( nodeIt != nodeEnd ) { ObjectPlus1->AddIndex( nodeIt->first ); ++nodeIt; } ObjectPlus1->Optimize(); this->m_LabelMap->AddLabelObject( ObjectPlus1 ); } //////////////////////////////////////////////////////////////////////////////// template< typename TInput > BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInput::ImageDimension > > ::BinaryImageToLevelSetImageAdaptor() : Superclass() {} template< typename TInput > BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInput::ImageDimension > > ::~BinaryImageToLevelSetImageAdaptor() { } template< typename TInput > void BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInput::ImageDimension > > ::Initialize() { if( this->m_InputImage.IsNull() ) { itkGenericExceptionMacro( << "m_InputImage is ITK_NULLPTR" ); } this->m_LabelMap = LevelSetLabelMapType::New(); this->m_LabelMap->SetBackgroundValue( LevelSetType::PlusOneLayer() ); this->m_LabelMap->CopyInformation( this->m_InputImage ); this->m_InternalImage = InternalImageType::New(); this->m_InternalImage->CopyInformation( this->m_InputImage ); this->m_InternalImage->SetRegions( this->m_InputImage->GetBufferedRegion() ); this->m_InternalImage->Allocate(); this->m_InternalImage->FillBuffer( LevelSetType::PlusOneLayer() ); LevelSetLabelObjectPointer innerPart = LevelSetLabelObjectType::New(); innerPart->SetLabel( LevelSetType::MinusOneLayer() ); // Precondition labelmap and phi InputIteratorType inputIt( this->m_InputImage, this->m_InputImage->GetLargestPossibleRegion() ); inputIt.GoToBegin(); InternalIteratorType internalIt( this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); internalIt.GoToBegin(); while( !inputIt.IsAtEnd() ) { if ( inputIt.Get() != NumericTraits< InputImagePixelType >::ZeroValue() ) { innerPart->AddIndex( inputIt.GetIndex() ); internalIt.Set( LevelSetType::MinusOneLayer() ); } ++internalIt; ++inputIt; } innerPart->Optimize(); this->m_LabelMap->AddLabelObject( innerPart ); this->FindActiveLayer(); this->CreateMinimalInterface(); this->m_LevelSet->SetLabelMap( this->m_LabelMap ); this->m_InternalImage = ITK_NULLPTR; } template< typename TInput > void BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInput::ImageDimension > > ::FindActiveLayer() { LevelSetLabelObjectPointer labelObject = this->m_LabelMap->GetLabelObject( LevelSetType::MinusOneLayer() ); LevelSetLayerType & layer = this->m_LevelSet->GetLayer( LevelSetType::ZeroLayer() ); typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); ZeroFluxNeumannBoundaryCondition< InternalImageType > im_nbc; NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &im_nbc ); typename NeighborhoodIteratorType::OffsetType neighOffset; neighOffset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { neighOffset[dim] = -1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 1; neighIt.ActivateOffset( neighOffset ); neighOffset[dim] = 0; } typename LevelSetLabelObjectType::ConstIndexIterator lineIt( labelObject ); lineIt.GoToBegin(); while( !lineIt.IsAtEnd() ) { const LevelSetInputType & idx = lineIt.GetIndex(); neighIt.SetLocation( idx ); bool ZeroSet = false; for( typename NeighborhoodIteratorType::Iterator it = neighIt.Begin(); !it.IsAtEnd(); ++it ) { if( it.Get() == LevelSetType::PlusOneLayer() ) { ZeroSet = true; } } if( ZeroSet ) { layer.insert( LayerPairType( idx, NumericTraits< LevelSetOutputType >::ZeroValue() ) ); this->m_InternalImage->SetPixel( idx, LevelSetType::ZeroLayer() ); } ++lineIt; } LevelSetLabelObjectPointer ObjectZero = LevelSetLabelObjectType::New(); ObjectZero->SetLabel( LevelSetType::ZeroLayer() ); LevelSetLayerIterator nodeIt = layer.begin(); LevelSetLayerIterator nodeEnd = layer.end(); while( nodeIt != nodeEnd ) { labelObject->RemoveIndex( nodeIt->first ); ObjectZero->AddIndex( nodeIt->first ); ++nodeIt; } ObjectZero->Optimize(); this->m_LabelMap->AddLabelObject( ObjectZero ); } template< typename TInput > void BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInput::ImageDimension > > ::CreateMinimalInterface() { LevelSetLayerType & list_0 = this->m_LevelSet->GetLayer( LevelSetType::ZeroLayer() ); ZeroFluxNeumannBoundaryCondition< InternalImageType > sp_nbc; typename NeighborhoodIteratorType::RadiusType radius; radius.Fill( 1 ); NeighborhoodIteratorType neighIt( radius, this->m_InternalImage, this->m_InternalImage->GetLargestPossibleRegion() ); neighIt.OverrideBoundaryCondition( &sp_nbc ); typename NeighborhoodIteratorType::OffsetType sparse_offset; sparse_offset.Fill( 0 ); for( unsigned int dim = 0; dim < ImageDimension; dim++ ) { sparse_offset[dim] = -1; neighIt.ActivateOffset( sparse_offset ); sparse_offset[dim] = 1; neighIt.ActivateOffset( sparse_offset ); sparse_offset[dim] = 0; } LevelSetLayerIterator nodeIt = list_0.begin(); LevelSetLayerIterator nodeEnd = list_0.end(); while( nodeIt != nodeEnd ) { LevelSetInputType currentIdx = nodeIt->first; neighIt.SetLocation( currentIdx ); bool hasPositiveLayerNeighbor = false; bool hasNegativeLayerNeighbor = false; for( typename NeighborhoodIteratorType::Iterator i = neighIt.Begin(); !i.IsAtEnd(); ++i ) { LayerIdType tempValue = i.Get(); if( tempValue != NumericTraits< LayerIdType >::ZeroValue() ) { if( tempValue == LevelSetType::MinusOneLayer() ) { hasNegativeLayerNeighbor = true; if( hasPositiveLayerNeighbor ) { break; } } else // ( tempValue == NumericTraits< LevelSetOutputType >::OneValue() ) { hasPositiveLayerNeighbor = true; if( hasNegativeLayerNeighbor ) { break; } } } } if( hasNegativeLayerNeighbor && !hasPositiveLayerNeighbor ) { LevelSetLayerIterator tempIt = nodeIt; ++nodeIt; list_0.erase( tempIt ); this->m_LabelMap->GetLabelObject( LevelSetType::ZeroLayer() )->RemoveIndex( currentIdx ); this->m_LabelMap->GetLabelObject( LevelSetType::MinusOneLayer() )->AddIndex( currentIdx ); } else { if( hasPositiveLayerNeighbor && !hasNegativeLayerNeighbor ) { LevelSetLayerIterator tempIt = nodeIt; ++nodeIt; list_0.erase( tempIt ); this->m_LabelMap->GetLabelObject( LevelSetType::ZeroLayer() )->RemoveIndex( currentIdx ); } else { ++nodeIt; } } } } } #endif // itkBinaryImageToLevelSetImageAdaptor_hxx
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
d6fa6da2038c8092c1e04f303c125699dd7ab36f
252c2ee58475a4db42984c311ce6528ad2239c7f
/qpainterwidget.h
c5542bbb10bbc3afee6ac564b311c5fbfa14b794
[]
no_license
lsl1229840757/GeoSystem
c7ed5053c03e9efa2867e1803d0ff6e6f754c61c
57de4d9935862e6c4b66efda7f4a78fb3fc0e1fd
refs/heads/master
2020-09-20T23:26:50.626722
2019-12-27T07:57:27
2019-12-27T07:57:27
224,615,990
0
1
null
2019-12-19T19:59:54
2019-11-28T09:23:21
C++
UTF-8
C++
false
false
352
h
#ifndef QPAINTERWIDGET_H #define QPAINTERWIDGET_H #include <QWidget> #include "ui_qpainterwidget.h" #include <qpainter.h> class QPainterWidget : public QWidget { Q_OBJECT public: QPainterWidget(QWidget *parent = 0); ~QPainterWidget(); protected: void paintEvent(QPaintEvent *event); private: Ui::QPainterWidget ui; }; #endif // QPAINTERWIDGET_H
[ "1229840757@qq.com" ]
1229840757@qq.com
e88c08b8fb596ce78ddc9ecab66db84f063d86cc
50c74a5dd38180e26f0608cb0002585489445555
/Codeforces Solutions/1025C.cpp
2dd25345d5180ceaeb18911f2b115e153df66af2
[]
no_license
ShobhitBehl/Competitive-Programming
1518fe25001cc57095c1643cc8c904523b2ac2ef
7a05897ca0ef5565655350803327f7f23bcf82fe
refs/heads/master
2020-04-17T05:20:52.302129
2019-03-18T10:17:47
2019-03-18T10:17:47
166,265,289
0
0
null
null
null
null
UTF-8
C++
false
false
3,137
cpp
#include <bits/stdc++.h> typedef long long int lli; using namespace std; //#define pi 3.141592653589793238 typedef pair<lli,lli> pll; typedef map<lli,lli> mll; typedef set<lli> sl; typedef map<int,int> mii; typedef set<int> si; typedef pair<double,double> pdd; typedef map<double,lli> mdl; typedef set<double> sd; #define x first #define y second #define mp make_pair #define pb push_back const lli mod = 1e9 + 7; #define tr(...) cout<<__FUNCTION__<<' '<<__LINE__<<" = ";trace(#__VA_ARGS__, __VA_ARGS__) template<typename S, typename T> ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;} template<typename T> ostream& operator<<(ostream& out,vector<T> const& v){ lli l=v.size();for(lli i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;} template<typename T> void trace(const char* name, T&& arg1){cout<<name<<" : "<<arg1<<endl;} template<typename T, typename... Args> void trace(const char* names, T&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cout.write(names, comma-names)<<" : "<<arg1<<" | ";trace(comma+1,args...);} lli gcd(lli a, lli b) { if(b < a) { int temp = a; a = b; b = temp; } if(a == 0) { return b; } return gcd(b%a,a); } lli lcm(lli a, lli b) { return (a*b/gcd(a,b)); } vector<lli> getprimes() { vector <lli> pl(101,1); for(int i = 2; i<=100; i++) { if(pl[i] == 1) { for(int j = 2*i; j<=100; j+=i) { pl[j] = 0; } } } return pl; } lli primefactorise(int n) { if(n == 1) { return 1; } lli ans = n; while (n%2 == 0) { n = n/2; if(n != 1) { ans += n; } } for (int i = 3; i <= sqrt(n); i = i+2) { while (n%i == 0) { n = n/i; if(n != 1) { ans += n; } } } ans += 1; return ans; } lli power(lli a,lli b) { lli ans = 1; while(b > 0) { if(b%2 == 1) { ans *= a; ans = ans; } b/=2; a*=a; a = a; } return ans; } vector<lli> getbinary(lli x, lli size) { vector <lli> bin(size,0); lli iter = 0; while(x > 0) { if(x%2 == 0) { bin[iter] = 0; } else { bin[iter] = 1; } x/=2; iter++; } return bin; } lli dist(pll a, pll b) { return (b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y - a.y); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cout.precision(50); string s; cin >> s; s += s; lli ans = 1; lli maxx = 1; for(int i = 1; i<s.size(); i++) { if(s[i]!=s[i-1]) { ans++; } else { maxx = max(maxx,ans); ans = 1; } } maxx = max(ans,maxx); if(maxx > s.size()/2) { maxx = s.size()/2; } cout << maxx << endl; }
[ "shobhitbehl1@gmail.com" ]
shobhitbehl1@gmail.com
2510b15372f00d93d864a01df459bfea603da625
2cbdcb198b63dbdc63b9d3ec6f3c7741283b0e71
/src/underTest/hip/application/UDPEchoStream.h
1846302f4e763b8f06d024bc37f00c480d18999a
[]
no_license
lasfar1008/inetmanet-2.0
2a4245ae864ee5222d601ce32bc0c94cd7fdf63d
6691287e2c2c03025c2ab238ed3ffd967bad0ec2
refs/heads/master
2021-01-16T09:51:11.479991
2011-11-05T12:30:30
2011-11-05T12:30:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,381
h
//********************************************************************************* // File: UDPEchoStream.h // // Authors: Laszlo Tamas Zeke, Levente Mihalyi, Laszlo Bokor // // Copyright: (C) 2008-2009 BME-HT (Department of Telecommunications, // Budapest University of Technology and Economics), Budapest, Hungary // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //********************************************************************************** // Part of: HIPSim++ Host Identity Protocol Simulation Framework developed by BME-HT //********************************************************************************** #ifndef __UDPECHOSTREAM_H__ #define __UDPECHOSTREAM_H__ #include <vector> #include <omnetpp.h> #include "UDPAppBase.h" #include "IPvXAddress.h" class UDPEchoStream : public UDPAppBase { protected: // module parameters int port; cPar *waitInterval; cPar *packetLen; bool first; IPvXAddress destAddr; int destPort; // statistics unsigned long numPkRec; unsigned long numPkSent; // total number of packets sent cOutVector rttVector; cOutVector jitterVector; cStdDev rttStat; cStdDev jitterStat; simtime_t lastrtt; protected: // process stream request from client // void processStreamRequest(cMessage *msg); // send a packet of the given video stream void processStreamData(cMessage *msg); void sendStreamData(cMessage *timer); void sendRequest(); public: UDPEchoStream(); virtual ~UDPEchoStream(); protected: ///@name Overidden cSimpleModule functions //@{ virtual void initialize(); virtual void finish(); virtual void handleMessage(cMessage* msg); //@} }; #endif
[ "alfonso@.(none)" ]
alfonso@.(none)
fe2ab0ddb13dda9fd96869f5156eddec92a0a5b4
8ff2ea9e811a710fbdf4722cf079ffb43f9ef9f0
/sqrt.cpp
2e799e7cce1124f5176f5c902dee1f09ab7736aa
[]
no_license
mridul2101/CollegeCode
3281d6e73566b6148ecf4d399386ed8cf97fdcdf
43ad3343fadfd9d23a9454e2747fdabaea5a7361
refs/heads/master
2020-03-18T15:03:31.139459
2018-06-04T20:49:03
2018-06-04T20:49:03
134,884,563
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include<iostream> #include<cmath> using namespace std; int main() { float f; cin>>f; cout<<sqrt(f)<<endl; return 1; }
[ "window.buy@gmail.com" ]
window.buy@gmail.com
0394d654000dd01a1963d314a998eb35a955bb77
a3c2b8e59db2761a68cd81431ef0f43b07629e7f
/Source/GameEngine/Graphic/Renderer/DirectX11/HLSL/HLSLProgramFactory.h
9c82c8c84f8b468d07c7400e995b5f7005280140
[]
no_license
enriquegr84/GameEngineTutorial
13eeae4b8c65cf94254c4cb7f879f52614fed185
dd6507839a34746dc9b25d28c879f180c62eaab8
refs/heads/master
2021-08-23T09:35:28.257239
2021-08-06T16:52:38
2021-08-06T16:52:38
83,200,106
6
0
null
null
null
null
UTF-8
C++
false
false
3,332
h
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2017 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #ifndef HLSLPROGRAMFACTORY_H #define HLSLPROGRAMFACTORY_H #include "Graphic/Shader/ProgramFactory.h" class GRAPHIC_ITEM HLSLProgramFactory : public ProgramFactory { public: // The 'defaultVersion' can be set once on application initialization if // you want an HLSL version different from our default when constructing a // program factory. static eastl::string defaultVersion; // "5_0" (Shader Model 5) static eastl::string defaultVSEntry; // "VSMain" static eastl::string defaultPSEntry; // "PSMain" static eastl::string defaultGSEntry; // "GSMain" static eastl::string defaultCSEntry; // "CSMain" static unsigned int defaultFlags; // enable strictness, ieee strictness, optimization level 3 // Construction. The 'version' member is set to 'defaultVersion'. The // 'defines' are empty. virtual ~HLSLProgramFactory(); HLSLProgramFactory(); // The returned value is used as a lookup index into arrays of strings // corresponding to shader programs. virtual int GetAPI() const; // Create a program for GPU display. eastl::shared_ptr<VisualProgram> CreateFromByteCode( eastl::vector<unsigned char> const& vsBytecode, eastl::vector<unsigned char> const& psBytecode, eastl::vector<unsigned char> const& gsBytecode); // Create a program for GPU computing. eastl::shared_ptr<ComputeProgram> CreateFromByteCode( eastl::vector<unsigned char> const& csBytecode); private: // Create a program for GPU display. The files are // passed as parameters in case the shader compiler needs // this for #include path searches. virtual eastl::shared_ptr<VisualProgram> CreateFromNamedFiles( eastl::string const& vsName, eastl::string const& vsFile, eastl::string const& psName, eastl::string const& psFile, eastl::string const& gsName, eastl::string const& gsFile); // Create a program for GPU display. The files are loaded, converted to // strings, and passed to CreateFromNamedSources. The filenames are // passed as the 'xsName' parameters in case the shader compiler needs // this for #include path searches. virtual eastl::shared_ptr<VisualProgram> CreateFromNamedSources( eastl::string const& vsName, eastl::string const& vsSource, eastl::string const& psName, eastl::string const& psSource, eastl::string const& gsName, eastl::string const& gsSource); // Create a program for GPU computing. The filename is passed as parameters // in case the shader compiler needs this for #include path searches. virtual eastl::shared_ptr<ComputeProgram> CreateFromNamedFile( eastl::string const& csName, eastl::string const& csFile); // Create a program for GPU computing. The file is loaded, converted to // a string, and passed to CreateFromNamedSource. The filename is passed // as the 'csName' parameters in case the shader compiler needs this for // #include path searches. virtual eastl::shared_ptr<ComputeProgram> CreateFromNamedSource( eastl::string const& csName, eastl::string const& csSource); }; #endif
[ "enriquegr84@hotmail.es" ]
enriquegr84@hotmail.es
2cbbafdd6031cf5156e060d3dc83226f64784885
418aa6c4486e255f482b6c9bee12a08cda829503
/Network/FtpClient/FTPClient.cpp
f30230f65629d3471b9d03265f22954b0ce92b71
[ "MIT" ]
permissive
jjuiddong/Common
b21c9a98474fc45aa30b316808498381c2030ad3
3097b60988464000e2885a07cdd6e433e43de386
refs/heads/master
2023-08-31T07:35:31.425468
2023-08-29T11:38:29
2023-08-29T11:38:29
77,737,521
3
8
null
null
null
null
UTF-8
C++
false
false
73,596
cpp
//////////////////////////////////////////////////////////////////////////////// // // The official specification of the File Transfer Protocol (FTP) is the RFC 959. // Most of the documentation are taken from this RFC. // This is an implementation of an simple FTP client. I have tried to implement // platform independent. For the communication i used the classes CBlockingSocket, // CSockAddr, ... from David J. Kruglinski (Inside Visual C++). These classes are // only small wrappers for the sockets-API. // Further I used a smart pointer-implementation from Scott Meyers (Effective C++, // More Effective C++, Effective STL). // The implementation of the logon-sequence (with firewall support) was published // in an article on Codeguru by Phil Anderson. // The code for the parsing of the different FTP LIST responses is taken from // D. J. Bernstein (http://cr.yp.to/ftpparse.html). I only wrapped the c-code in // a class. // I have tested the code on Windows and Linux (Kubuntu). // // Copyright (c) 2004-2012 Thomas Oswald // // Permission to copy, use, sell and distribute this software is granted // provided this copyright notice appears in all copies. // Permission to modify the code and to distribute modified code is granted // provided this copyright notice appears in all copies, and a notice // that the code was modified is included with the copyright notice. // // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // // History: // v1.5 released 2007-06-01 //+# TODO // v1.1 released 2005-12-04 // - Bug in OpenPassiveDataConnection removed: SendCommand was called before data connection was established. // - Bugs in GetSingleResponseLine removed: // * Infinite loop if response line doesn't end with CRLF. // * Return value of std:string->find must be checked against npos. // - Now runs in unicode. // - Streams removed. // - Explicit detaching of observers are not necessary anymore. // - ExecuteDatachannelCommand now accepts an ITransferNotification object. // Through this concept there is no need to write the received files to a file. // For example the bytes can be written only in memory or an other tcp stream. // - Added an interface for the blocking socket (IBlockingSocket). // Therefore it is possible to exchange the socket implementation, e.g. for // writing unit tests (by simulating an specific scenario of a FTP communication). // - Replaced the magic numbers concerning the reply codes by a class. // v1.0 released 2004-10-25 //////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FTPClient.h" #include <limits> #include <algorithm> #include <iterator> #include <assert.h> #include <stdio.h> #include "FTPListParse.h" #include "FTPFileStatus.h" #undef max #ifdef __AFX_H__ // MFC only #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #endif using namespace nsHelper; namespace nsFTP { class CMakeString { public: CMakeString& operator<<(DWORD dwNum) { DWORD dwTemp = dwNum; int iCnt=1; // name lookup of 'iCnt' changed for new ISO 'for' scoping for( ; (dwTemp/=10) != 0; iCnt++ ) ; m_str.resize(m_str.size() + iCnt); // string size +1 because tsprintf needs the size including the terminating NULL character; // the size method returns the size without the terminating NULL character tsprintf(&(*m_str.begin()), m_str.size()+1, _T("%s%u"), m_str.c_str(), dwNum); return *this; } CMakeString& operator<<(const tstring& strAdd) { m_str += strAdd; return *this; } operator tstring() const { return m_str; } private: tstring m_str; }; tstring& ReplaceStr(tstring& strTarget, const tstring& strToReplace, const tstring& strReplacement) { size_t pos = strTarget.find(strToReplace); while( pos != tstring::npos ) { strTarget.replace(pos, strToReplace.length(), strReplacement); pos = strTarget.find(strToReplace, pos+1); } return strTarget; } class CFile : public CFTPClient::ITransferNotification { FILE* m_pFile; tstring m_strFileName; public: enum TOriginEnum { orBegin=SEEK_SET, orEnd=SEEK_END, orCurrent=SEEK_CUR }; CFile() : m_pFile(NULL) {} virtual ~CFile() { Close(); } bool Open(const tstring& strFileName, const tstring& strMode) { m_strFileName = strFileName; #if _MSC_VER >= 1500 return fopen_s(&m_pFile, CCnv::ConvertToString(strFileName).c_str(), CCnv::ConvertToString(strMode).c_str()) == 0; #else m_pFile = fopen(CCnv::ConvertToString(strFileName).c_str(), CCnv::ConvertToString(strMode).c_str()); return m_pFile!=NULL; #endif } bool Close() { FILE* pFile = m_pFile; m_pFile = NULL; return pFile && fclose(pFile)==0; } bool Seek(long lOffset, TOriginEnum enOrigin) { return m_pFile && fseek(m_pFile, lOffset, enOrigin)==0; } long Tell() { if( !m_pFile ) return -1L; return ftell(m_pFile); } size_t Write(const void* pBuffer, size_t itemSize, size_t itemCount) { if( !m_pFile ) return 0; return fwrite(pBuffer, itemSize, itemCount, m_pFile); } size_t Read(void* pBuffer, size_t itemSize, size_t itemCount) { if( !m_pFile ) return 0; return fread(pBuffer, itemSize, itemCount, m_pFile); } virtual tstring GetLocalStreamName() const override { return m_strFileName; } virtual UINT GetLocalStreamSize() const override { if( !m_pFile ) return 0; const long lCurPos = ftell(m_pFile); fseek(m_pFile, 0, SEEK_END); const long lEndPos = ftell(m_pFile); fseek(m_pFile, lCurPos, SEEK_SET); return lEndPos; } virtual void SetLocalStreamOffset(DWORD dwOffsetFromBeginOfStream) override { Seek(dwOffsetFromBeginOfStream, CFile::orBegin); } virtual void OnBytesReceived(const TByteVector& vBuffer, long lReceivedBytes) override { Write(&(*vBuffer.begin()), sizeof(TByteVector::value_type), lReceivedBytes); } virtual void OnPreBytesSend(char* pszBuffer, size_t bufferSize, size_t& bytesToSend) override { bytesToSend = Read(pszBuffer, sizeof(char), bufferSize); } }; class COutputStream::CPimpl { CPimpl& operator=(const CPimpl&); // no implementation for assignment operator public: CPimpl(const tstring& strEolCharacterSequence, const tstring& strStreamName) : mc_strEolCharacterSequence(strEolCharacterSequence), m_itCurrentPos(m_vBuffer.end()), m_strStreamName(strStreamName) { } const tstring mc_strEolCharacterSequence; tstring m_vBuffer; tstring::iterator m_itCurrentPos; tstring m_strStreamName; }; COutputStream::COutputStream(const tstring& strEolCharacterSequence, const tstring& strStreamName) : m_spPimpl(new CPimpl(strEolCharacterSequence, strStreamName)) { } COutputStream::~COutputStream() {} void COutputStream::SetBuffer(const tstring& strBuffer) { m_spPimpl->m_vBuffer = strBuffer; } const tstring& COutputStream::GetBuffer() const { return m_spPimpl->m_vBuffer; } void COutputStream::SetStartPosition() { m_spPimpl->m_itCurrentPos = m_spPimpl->m_vBuffer.begin(); } bool COutputStream::GetNextLine(tstring& strLine)// const { tstring::iterator it = std::search(m_spPimpl->m_itCurrentPos, m_spPimpl->m_vBuffer.end(), m_spPimpl->mc_strEolCharacterSequence.begin(), m_spPimpl->mc_strEolCharacterSequence.end()); if( it == m_spPimpl->m_vBuffer.end() ) return false; strLine.assign(m_spPimpl->m_itCurrentPos, it); m_spPimpl->m_itCurrentPos = it + m_spPimpl->mc_strEolCharacterSequence.size(); return true; } tstring COutputStream::GetLocalStreamName() const { return m_spPimpl->m_strStreamName; } UINT COutputStream::GetLocalStreamSize() const { return (UINT)m_spPimpl->m_vBuffer.size(); } void COutputStream::SetLocalStreamOffset(DWORD dwOffsetFromBeginOfStream) { m_spPimpl->m_itCurrentPos = m_spPimpl->m_vBuffer.begin() + dwOffsetFromBeginOfStream; } void COutputStream::OnBytesReceived(const TByteVector& vBuffer, long lReceivedBytes) { std::copy(vBuffer.begin(), vBuffer.begin()+lReceivedBytes, std::back_inserter(m_spPimpl->m_vBuffer)); } void COutputStream::OnPreBytesSend(char* pszBuffer, size_t bufferSize, size_t& bytesToSend) { for( bytesToSend=0; m_spPimpl->m_itCurrentPos!=m_spPimpl->m_vBuffer.end() && bytesToSend < bufferSize; ++m_spPimpl->m_itCurrentPos, ++bytesToSend ) pszBuffer[bytesToSend] = (char)*m_spPimpl->m_itCurrentPos; } } using namespace nsFTP; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// /// constructor /// @param[in] apSocket Instance of socket class which will be used for /// communication with the FTP server. /// CFTPClient class takes ownership of this instance. /// It will be deleted on destruction of this object. /// If this pointer is NULL, the CBlockingSocket implementation /// will be used. /// This gives the ability to set an other socket class. /// For example a socket class can be implemented which simulates /// a FTP server (for unit testing). /// @param[in] uiTimeout Timeout used for socket operation. /// @param[in] uiBufferSize Size of the buffer used for sending and receiving /// data via sockets. The size have an influence on /// the performance. Through empiric test i come to the /// conclusion that 2048 is a good size. /// @param[in] uiResponseWait Sleep time between receive calls to socket when getting /// the response. Sometimes the socket hangs if no wait time /// is set. Normally not wait time is necessary. CFTPClient::CFTPClient(std::auto_ptr<IBlockingSocket> apSocket, unsigned int uiTimeout/*=10*/, unsigned int uiBufferSize/*=2048*/, unsigned int uiResponseWait/*=0*/, const tstring& strRemoteDirectorySeparator/*=_T("/")*/) : mc_uiTimeout(uiTimeout), mc_uiResponseWait(uiResponseWait), mc_strEolCharacterSequence(_T("\r\n")), mc_strRemoteDirectorySeparator(strRemoteDirectorySeparator),//+# documentation missing m_vBuffer(uiBufferSize), m_apSckControlConnection(apSocket), m_apFileListParser(new CFTPListParser()), m_fTransferInProgress(false), m_fAbortTransfer(false), m_fResumeIfPossible(true) { ASSERT( m_apSckControlConnection.get() ); } /// destructor CFTPClient::~CFTPClient() { if( IsTransferringData() ) Abort(); if( IsConnected() ) Logout(); } /// Attach an observer to the client. You can attach as many observers as you want. /// The client send notifications (more precisely the virtual functions are called) /// to the observers. void CFTPClient::AttachObserver(CFTPClient::CNotification* pObserver) { ASSERT( pObserver ); if( pObserver ) m_setObserver.Attach(pObserver); } /// Detach an observer from the client. void CFTPClient::DetachObserver(CFTPClient::CNotification* pObserver) { ASSERT( pObserver ); if( pObserver ) m_setObserver.Detach(pObserver); } /// Sets the file list parser which is used for parsing the results of the LIST command. void CFTPClient::SetFileListParser(std::auto_ptr<IFileListParser> apFileListParser) { m_apFileListParser = apFileListParser; } /// Returns a set of all observers currently attached to the client. CFTPClient::TObserverSet& CFTPClient::GetObservers() { return m_setObserver; } /// Enables or disables resuming for file transfer operations. /// @param[in] fEnable True enables resuming, false disables it. void CFTPClient::SetResumeMode(bool fEnable/*=true*/) { m_fResumeIfPossible=fEnable; } /// Indicates if the resume mode is set. bool CFTPClient::IsResumeModeEnabled() const { return m_fResumeIfPossible; } /// Opens the control channel to the FTP server. /// @param[in] strServerHost IP-address or name of the server /// @param[in] iServerPort Port for channel. Usually this is port 21. bool CFTPClient::OpenControlChannel(const tstring& strServerHost, USHORT ushServerPort/*=DEFAULT_FTP_PORT*/) { CloseControlChannel(); try { m_apSckControlConnection->Create(SOCK_STREAM); CSockAddr adr = m_apSckControlConnection->GetHostByName(CCnv::ConvertToString(strServerHost).c_str(), ushServerPort); m_apSckControlConnection->Connect(adr); } catch(CBlockingSocketException& blockingException) { ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); m_apSckControlConnection->Cleanup(); return false; } return true; } /// Returns the connection state of the client. bool CFTPClient::IsConnected() const { return m_apSckControlConnection->operator SOCKET()!=INVALID_SOCKET; } /// Returns true if a download/upload is running, otherwise false. bool CFTPClient::IsTransferringData() const { return m_fTransferInProgress; } /// Closes the control channel to the FTP server. void CFTPClient::CloseControlChannel() { try { m_apSckControlConnection->Close(); m_apCurrentRepresentation.reset(NULL); } catch(CBlockingSocketException& blockingException) { blockingException.GetErrorMessage(); m_apSckControlConnection->Cleanup(); } } /// Analyse the repy code of a FTP server-response. /// @param[in] Reply Reply of a FTP server. /// @retval FTP_OK All runs perfect. /// @retval FTP_ERROR Something went wrong. An other response was expected. /// @retval NOT_OK The command was not accepted. int CFTPClient::SimpleErrorCheck(const CReply& Reply) const { if( Reply.Code().IsNegativeReply() ) return FTP_NOTOK; else if( Reply.Code().IsPositiveCompletionReply() ) return FTP_OK; ASSERT( Reply.Code().IsPositiveReply() ); return FTP_ERROR; } /// Logs on to a FTP server. /// @param[in] logonInfo Structure with logon information. bool CFTPClient::Login(const CLogonInfo& logonInfo) { m_LastLogonInfo = logonInfo; enum {LO=-2, ///< Logged On ER=-1, ///< Error NUMLOGIN=9, ///< currently supports 9 different login sequences }; int iLogonSeq[NUMLOGIN][18] = { // this array stores all of the logon sequences for the various firewalls // in blocks of 3 nums. // 1st num is command to send, // 2nd num is next point in logon sequence array if 200 series response // is rec'd from server as the result of the command, // 3rd num is next point in logon sequence if 300 series rec'd { 0,LO,3, 1,LO, 6, 2,LO,ER }, // no firewall { 3, 6,3, 4, 6,ER, 5,ER, 9, 0,LO,12, 1,LO,15, 2,LO,ER }, // SITE hostname { 3, 6,3, 4, 6,ER, 6,LO, 9, 1,LO,12, 2,LO,ER }, // USER after logon { 7, 3,3, 0,LO, 6, 1,LO, 9, 2,LO,ER }, // proxy OPEN { 3, 6,3, 4, 6,ER, 0,LO, 9, 1,LO,12, 2,LO,ER }, // Transparent { 6,LO,3, 1,LO, 6, 2,LO,ER }, // USER with no logon { 8, 6,3, 4, 6,ER, 0,LO, 9, 1,LO,12, 2,LO,ER }, // USER fireID@remotehost { 9,ER,3, 1,LO, 6, 2,LO,ER }, // USER remoteID@remotehost fireID {10,LO,3, 11,LO, 6, 2,LO,ER } // USER remoteID@fireID@remotehost }; // are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0) tstring strTemp; USHORT ushPort=0; if( logonInfo.FwType() == CFirewallType::None()) { strTemp = logonInfo.Hostname(); ushPort = logonInfo.Hostport(); } else { strTemp = logonInfo.FwHost(); ushPort = logonInfo.FwPort(); } tstring strHostnamePort(logonInfo.Hostname()); if( logonInfo.Hostport()!=DEFAULT_FTP_PORT ) strHostnamePort = CMakeString() << logonInfo.Hostname() << _T(":") << logonInfo.Hostport(); // add port to hostname (only if port is not 21) if( IsConnected() ) Logout(); if( !OpenControlChannel(strTemp, ushPort) ) return false; // get initial connect msg off server CReply Reply; if( !GetResponse(Reply) || !Reply.Code().IsPositiveCompletionReply() ) return false; int iLogonPoint=0; // go through appropriate logon procedure for ( ; ; ) { // send command, get response CReply Reply; switch(iLogonSeq[logonInfo.FwType().AsEnum()][iLogonPoint]) { // state command command argument success fail case 0: if( SendCommand(CCommand::USER(), logonInfo.Username(), Reply) ) break; else return false; case 1: if( SendCommand(CCommand::PASS(), logonInfo.Password(), Reply) ) break; else return false; case 2: if( SendCommand(CCommand::ACCT(), logonInfo.Account(), Reply) ) break; else return false; case 3: if( SendCommand(CCommand::USER(), logonInfo.FwUsername(), Reply) ) break; else return false; case 4: if( SendCommand(CCommand::PASS(), logonInfo.FwPassword(), Reply) ) break; else return false; case 5: if( SendCommand(CCommand::SITE(), strHostnamePort, Reply) ) break; else return false; case 6: if( SendCommand(CCommand::USER(), logonInfo.Username() + _T("@") + strHostnamePort, Reply) ) break; else return false; case 7: if( SendCommand(CCommand::OPEN(), strHostnamePort, Reply) ) break; else return false; case 8: if( SendCommand(CCommand::USER(), logonInfo.FwUsername() + _T("@") + strHostnamePort, Reply) ) break; else return false; case 9: if( SendCommand(CCommand::USER(), logonInfo.Username() + _T("@") + strHostnamePort + _T(" ") + logonInfo.FwUsername(), Reply) ) break; else return false; case 10: if( SendCommand(CCommand::USER(), logonInfo.Username() + _T("@") + logonInfo.FwUsername() + _T("@") + strHostnamePort, Reply) ) break; else return false; case 11: if( SendCommand(CCommand::PASS(), logonInfo.Password() + _T("@") + logonInfo.FwPassword(), Reply) ) break; else return false; } if( !Reply.Code().IsPositiveCompletionReply() && !Reply.Code().IsPositiveIntermediateReply() ) return false; const unsigned int uiFirstDigitOfReplyCode = CCnv::TStringToLong(Reply.Code().Value())/100; iLogonPoint=iLogonSeq[logonInfo.FwType().AsEnum()][iLogonPoint + uiFirstDigitOfReplyCode-1]; //get next command from array switch(iLogonPoint) { case ER: // ER means somewhat has gone wrong { ReportError(_T("Logon failed."), CCnv::ConvertToTString(__FILE__), __LINE__); } return false; case LO: // LO means we're fully logged on if( ChangeWorkingDirectory(mc_strRemoteDirectorySeparator)!=FTP_OK ) return false; return true; } } //return false; } /// Rename a file on the FTP server. /// @remarks Can be used for moving the file to another directory. /// @param[in] strOldName Name of the file to rename. /// @param[in] strNewName The new name for the file. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Rename(const tstring& strOldName, const tstring& strNewName) const { CReply Reply; if( !SendCommand(CCommand::RNFR(), strOldName, Reply) ) return FTP_ERROR; if( Reply.Code().IsNegativeReply() ) return FTP_NOTOK; else if( !Reply.Code().IsPositiveIntermediateReply() ) { ASSERT( Reply.Code().IsPositiveCompletionReply() || Reply.Code().IsPositivePreliminaryReply() ); return FTP_ERROR; } if( !SendCommand(CCommand::RNTO(), strNewName, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Moves a file within the FTP server. /// @param[in] strFullSourceFilePath Name of the file which should be moved. /// @param[in] strFullTargetFilePath The destination where the file should be moved to (file name must be also given). /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Move(const tstring& strFullSourceFilePath, const tstring& strFullTargetFilePath) const { return Rename(strFullSourceFilePath, strFullTargetFilePath); } /// Gets the directory listing of the FTP server. Sends the LIST command to /// the FTP server. /// @param[in] strPath Starting path for the list command. /// @param[out] vstrFileList Returns a simple list of the files and folders of the specified directory. /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::List(const tstring& strPath, TStringVector& vstrFileList, bool fPasv) const { COutputStream outputStream(mc_strEolCharacterSequence, CCommand::LIST().AsString()); if( !ExecuteDatachannelCommand(CCommand::LIST(), strPath, CRepresentation(CType::ASCII()), fPasv, 0, outputStream) ) return false; vstrFileList.clear(); tstring strLine; outputStream.SetStartPosition(); while( outputStream.GetNextLine(strLine) ) vstrFileList.push_back(strPath + strLine.c_str()); return true; } /// Gets the directory listing of the FTP server. Sends the NLST command to /// the FTP server. /// @param[in] strPath Starting path for the list command. /// @param[out] vstrFileList Returns a simple list of the files and folders of the specified the directory. /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::NameList(const tstring& strPath, TStringVector& vstrFileList, bool fPasv) const { COutputStream outputStream(mc_strEolCharacterSequence, CCommand::NLST().AsString()); if( !ExecuteDatachannelCommand(CCommand::NLST(), strPath, CRepresentation(CType::ASCII()), fPasv, 0, outputStream) ) return false; vstrFileList.clear(); tstring strLine; outputStream.SetStartPosition(); while( outputStream.GetNextLine(strLine) ) vstrFileList.push_back(strLine.c_str()); // jjuiddong, 2017-01-07 //vstrFileList.push_back(strPath + strLine.c_str()); return true; } /// Gets the directory listing of the FTP server. Sends the LIST command to /// the FTP server. /// @param[in] strPath Starting path for the list command. /// @param[out] vFileList Returns a detailed list of the files and folders of the specified directory. /// vFileList contains CFTPFileStatus-Objects. These Objects provide a lot of /// information about the file/folder. /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::List(const tstring& strPath, TFTPFileStatusShPtrVec& vFileList, bool fPasv) const { ASSERT( m_apFileListParser.get() ); COutputStream outputStream(mc_strEolCharacterSequence, CCommand::LIST().AsString()); if( !ExecuteDatachannelCommand(CCommand::LIST(), strPath, CRepresentation(CType::ASCII()), fPasv, 0, outputStream) ) return false; vFileList.clear(); tstring strLine; outputStream.SetStartPosition(); while( outputStream.GetNextLine(strLine) ) { TFTPFileStatusShPtr spFtpFileStatus(new CFTPFileStatus()); if( m_apFileListParser->Parse(*spFtpFileStatus, strLine) ) { spFtpFileStatus->Path() = strPath; vFileList.push_back(spFtpFileStatus); } } return true; } /// Gets the directory listing of the FTP server. Sends the NLST command to /// the FTP server. /// @param[in] strPath Starting path for the list command. /// @param[out] vFileList Returns a simple list of the files and folders of the specified directory. /// vFileList contains CFTPFileStatus-Objects. Normally these Objects provide /// a lot of information about the file/folder. But the NLST-command provide /// only a simple list of the directory content (no specific information). /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::NameList(const tstring& strPath, TFTPFileStatusShPtrVec& vFileList, bool fPasv) const { COutputStream outputStream(mc_strEolCharacterSequence, CCommand::NLST().AsString()); if( !ExecuteDatachannelCommand(CCommand::NLST(), strPath, CRepresentation(CType::ASCII()), fPasv, 0, outputStream) ) return false; vFileList.clear(); tstring strLine; outputStream.SetStartPosition(); while( outputStream.GetNextLine(strLine) ) { TFTPFileStatusShPtr spFtpFileStatus(new CFTPFileStatus()); spFtpFileStatus->Path() = strPath; spFtpFileStatus->Name() = strLine; vFileList.push_back(spFtpFileStatus); } return true; } /// Gets a file from the FTP server. /// Uses C functions for file access (very fast). /// @param[in] strRemoteFile Filename of the sourcefile on the FTP server. /// @param[in] strLocalFile Filename of the target file on the local computer. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::DownloadFile(const tstring& strRemoteFile, const tstring& strLocalFile, const CRepresentation& repType, bool fPasv) const { CFile file; if( !file.Open(strLocalFile, m_fResumeIfPossible?_T("ab"):_T("wb")) ) { ReportError(CError::GetErrorDescription(), CCnv::ConvertToTString(__FILE__), __LINE__); return false; } file.Seek(0, CFile::orEnd); return DownloadFile(strRemoteFile, file, repType, fPasv); } /// Gets a file from the FTP server. /// Uses C functions for file access (very fast). /// @param[in] strRemoteFile Filename of the sourcefile on the FTP server. /// @param[in] Observer Object which receives the transfer notifications. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::DownloadFile(const tstring& strRemoteFile, ITransferNotification& Observer, const CRepresentation& repType, bool fPasv) const { long lRemoteFileSize = 0; FileSize(strRemoteFile, lRemoteFileSize); for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnPreReceiveFile(strRemoteFile, Observer.GetLocalStreamName(), lRemoteFileSize); const bool fRet = ExecuteDatachannelCommand(CCommand::RETR(), strRemoteFile, repType, fPasv, m_fResumeIfPossible ? Observer.GetLocalStreamSize() : 0, Observer); for( TObserverSet::const_iterator it2=m_setObserver.begin(); it2!=m_setObserver.end(); it2++ ) (*it2)->OnPostReceiveFile(strRemoteFile, Observer.GetLocalStreamName(), lRemoteFileSize); return fRet; } /// Gets a file from the FTP server. /// The target file is on an other FTP server (FXP). /// NOTICE: The file is directly transferred from one server to the other server. /// @param[in] strSourceFile File which is on the source FTP server. /// @param[in] TargetFtpServer The FTP server where the downloaded file will be stored. /// @param[in] strTargetFile Filename of the target file on the target FTP server. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::DownloadFile(const tstring& strSourceFile, const CFTPClient& TargetFtpServer, const tstring& strTargetFile, const CRepresentation& repType/*=CRepresentation(CType::Image())*/, bool fPasv/*=true*/) const { return TransferFile(*this, strSourceFile, TargetFtpServer, strTargetFile, repType, fPasv); } /// Puts a file on the FTP server. /// Uses C functions for file access (very fast). /// @param[in] strLocalFile Filename of the the local sourcefile which to put on the FTP server. /// @param[in] strRemoteFile Filename of the target file on the FTP server. /// @param[in] fStoreUnique if true, the FTP command STOU is used for saving /// else the FTP command STOR is used. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::UploadFile(const tstring& strLocalFile, const tstring& strRemoteFile, bool fStoreUnique, const CRepresentation& repType, bool fPasv) const { CFile file; if( !file.Open(strLocalFile, _T("rb")) ) { ReportError(CError::GetErrorDescription(), CCnv::ConvertToTString(__FILE__), __LINE__); return false; } return UploadFile(file, strRemoteFile, fStoreUnique, repType, fPasv); } /// Puts a file on the FTP server. /// Uses C functions for file access (very fast). /// @param[in] Observer Object which receives the transfer notifications for upload requests. /// @param[in] strRemoteFile Filename of the target file on the FTP server. /// @param[in] fStoreUnique if true, the FTP command STOU is used for saving /// else the FTP command STOR is used. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::UploadFile(ITransferNotification& Observer, const tstring& strRemoteFile, bool fStoreUnique, const CRepresentation& repType, bool fPasv) const { long lRemoteFileSize = 0; if( m_fResumeIfPossible ) FileSize(strRemoteFile, lRemoteFileSize); CCommand cmd(CCommand::STOR()); if( lRemoteFileSize > 0 ) cmd = CCommand::APPE(); else if( fStoreUnique ) cmd = CCommand::STOU(); const long lLocalFileSize = Observer.GetLocalStreamSize(); Observer.SetLocalStreamOffset(lRemoteFileSize); TObserverSet::const_iterator it; for( it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnPreSendFile(Observer.GetLocalStreamName(), strRemoteFile, lLocalFileSize); const bool fRet = ExecuteDatachannelCommand(cmd, strRemoteFile, repType, fPasv, 0, Observer); for( it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnPostSendFile(Observer.GetLocalStreamName(), strRemoteFile, lLocalFileSize); return fRet; } /// Puts a file on the FTP server. /// The source file is on an other FTP server (FXP). /// NOTICE: The file is directly transferred from one server to the other server. /// @param[in] SourceFtpServer A FTP server from which the file is taken for upload action. /// @param[in] strSourceFile File which is on the source FTP server. /// @param[in] strTargetFile Filename of the target file on the FTP server. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive bool CFTPClient::UploadFile(const CFTPClient& SourceFtpServer, const tstring& strSourceFile, const tstring& strTargetFile, const CRepresentation& repType/*=CRepresentation(CType::Image())*/, bool fPasv/*=true*/) const { return TransferFile(SourceFtpServer, strSourceFile, *this, strTargetFile, repType, !fPasv); } /// Transfers a file from a FTP server to another FTP server. /// The source file is on an other FTP server (FXP). /// NOTICE: The file is directly transferred from one server to the other server. /// @param[in] SourceFtpServer A FTP server from which the file which is copied. /// @param[in] strSourceFile Name of the file which is on the source FTP server. /// @param[in] TargetFtpServer A FTP server to which the file is copied. /// @param[in] strTargetFile Name of the file on the target FTP server. /// @param[in] repType Representation Type (see documentation of CRepresentation) /// @param[in] fPasv see documentation of CFTPClient::Passive /*static*/ bool CFTPClient::TransferFile(const CFTPClient& SourceFtpServer, const tstring& strSourceFile, const CFTPClient& TargetFtpServer, const tstring& strTargetFile, const CRepresentation& repType/*=CRepresentation(CType::Image())*/, bool fSourcePasv/*=false*/) { // transmit representation to server if( SourceFtpServer.RepresentationType(repType)!=FTP_OK ) return false; if( TargetFtpServer.RepresentationType(repType)!=FTP_OK ) return false; const CFTPClient& PassiveServer = fSourcePasv ? SourceFtpServer : TargetFtpServer; const CFTPClient& ActiveServer = fSourcePasv ? TargetFtpServer : SourceFtpServer; // set one FTP server in passive mode // the FTP server opens a port and tell us the socket (ip address + port) // this socket is used for opening the data connection ULONG ulIP = 0; USHORT ushSock = 0; if( PassiveServer.Passive(ulIP, ushSock)!=FTP_OK ) return false; CSockAddr csaPassiveServer(ulIP, ushSock); // transmit the socket (ip address + port) of the first FTP server to the // second server // the second FTP server establishes then the data connection to the first if( ActiveServer.DataPort(csaPassiveServer.DottedDecimal(), ushSock)!=FTP_OK ) return false; if( !SourceFtpServer.SendCommand(CCommand::RETR(), strSourceFile) ) return false; CReply ReplyTarget; if( !TargetFtpServer.SendCommand(CCommand::STOR(), strTargetFile, ReplyTarget) || !ReplyTarget.Code().IsPositivePreliminaryReply() ) return false; CReply ReplySource; if( !SourceFtpServer.GetResponse(ReplySource) || !ReplySource.Code().IsPositivePreliminaryReply() ) return false; // get response from FTP servers if( !SourceFtpServer.GetResponse(ReplySource) || !ReplySource.Code().IsPositiveCompletionReply() || !TargetFtpServer.GetResponse(ReplyTarget) || !ReplyTarget.Code().IsPositiveCompletionReply() ) return false; return true; } /// Executes a commando that result in a communication over the data port. /// @param[in] crDatachannelCmd Command to be executeted. /// @param[in] strPath Parameter for the command usually a path. /// @param[in] representation see documentation of CFTPClient::CRepresentation /// @param[in] fPasv see documentation of CFTPClient::Passive /// @param[in] dwByteOffset Server marker at which file transfer is to be restarted. /// @param[in] Observer Object for observing the execution of the command. bool CFTPClient::ExecuteDatachannelCommand(const CCommand& crDatachannelCmd, const tstring& strPath, const CRepresentation& representation, bool fPasv, DWORD dwByteOffset, ITransferNotification& Observer) const { if( !crDatachannelCmd.IsDatachannelCommand() ) { ASSERT(false); return false; } if( m_fTransferInProgress ) return false; if( !IsConnected() ) return false; // transmit representation to server if( RepresentationType(representation)!=FTP_OK ) return false; std::auto_ptr<IBlockingSocket> apSckDataConnection(m_apSckControlConnection->CreateInstance()); if( fPasv ) { if( !OpenPassiveDataConnection(*apSckDataConnection, crDatachannelCmd, strPath, dwByteOffset) ) return false; } else { if( !OpenActiveDataConnection(*apSckDataConnection, crDatachannelCmd, strPath, dwByteOffset) ) return false; } const bool fTransferOK = TransferData(crDatachannelCmd, Observer, *apSckDataConnection); apSckDataConnection->Close(); // get response from FTP server CReply Reply; if( !fTransferOK || !GetResponse(Reply) || !Reply.Code().IsPositiveCompletionReply() ) return false; return true; } /// Executes a commando that result in a communication over the data port. /// @param[in] crDatachannelCmd Command to be executeted. /// @param[in] Observer Object for observing the execution of the command. /// @param[in] sckDataConnection Socket which is used for sending/receiving data. bool CFTPClient::TransferData(const CCommand& crDatachannelCmd, ITransferNotification& Observer, IBlockingSocket& sckDataConnection) const { if( crDatachannelCmd.IsDatachannelWriteCommand() ) { if( !SendData(Observer, sckDataConnection) ) return false; } else if( crDatachannelCmd.IsDatachannelReadCommand() ) { if( !ReceiveData(Observer, sckDataConnection) ) return false; } else { ASSERT( false ); return false; } return true; } /// Opens an active data connection. /// @param[out] sckDataConnection /// @param[in] crDatachannelCmd Command to be executeted. /// @param[in] strPath Parameter for the command usually a path. /// @param[in] dwByteOffset Server marker at which file transfer is to be restarted. bool CFTPClient::OpenActiveDataConnection(IBlockingSocket& sckDataConnection, const CCommand& crDatachannelCmd, const tstring& strPath, DWORD dwByteOffset) const { if( !crDatachannelCmd.IsDatachannelCommand() ) { ASSERT(false); return false; } std::auto_ptr<IBlockingSocket> apSckServer(m_apSckControlConnection->CreateInstance()); USHORT ushLocalSock = 0; try { // INADDR_ANY = ip address of localhost // second parameter "0" means that the WINSOCKAPI ask for a port CSockAddr csaAddressTemp(INADDR_ANY, 0); apSckServer->Create(SOCK_STREAM); apSckServer->Bind(csaAddressTemp); apSckServer->GetSockAddr(csaAddressTemp); ushLocalSock=csaAddressTemp.Port(); apSckServer->Listen(); } catch(CBlockingSocketException& blockingException) { ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); apSckServer->Cleanup(); return false; } // get own ip address CSockAddr csaLocalAddress; m_apSckControlConnection->GetSockAddr(csaLocalAddress); // transmit the socket (ip address + port) to the server // the FTP server establishes then the data connection if( DataPort(csaLocalAddress.DottedDecimal(), ushLocalSock)!=FTP_OK ) return false; // if resuming is activated then set offset if( m_fResumeIfPossible && (crDatachannelCmd==CCommand::STOR() || crDatachannelCmd==CCommand::RETR() || crDatachannelCmd==CCommand::APPE() ) && (dwByteOffset!=0 && Restart(dwByteOffset)!=FTP_OK) ) return false; // send FTP command RETR/STOR/NLST/LIST to the server CReply Reply; if( !SendCommand(crDatachannelCmd, strPath, Reply) || !Reply.Code().IsPositivePreliminaryReply() ) return false; // accept the data connection CSockAddr sockAddrTemp; if( !apSckServer->Accept(sckDataConnection, sockAddrTemp) ) return false; return true; } /// Opens a passive data connection. /// @param[out] sckDataConnection /// @param[in] crDatachannelCmd Command to be executeted. /// @param[in] strPath Parameter for the command usually a path. /// @param[in] dwByteOffset Server marker at which file transfer is to be restarted. bool CFTPClient::OpenPassiveDataConnection(IBlockingSocket& sckDataConnection, const CCommand& crDatachannelCmd, const tstring& strPath, DWORD dwByteOffset) const { if( !crDatachannelCmd.IsDatachannelCommand() ) { ASSERT(false); return false; } ULONG ulRemoteHostIP = 0; USHORT ushServerSock = 0; // set passive mode // the FTP server opens a port and tell us the socket (ip address + port) // this socket is used for opening the data connection if( Passive(ulRemoteHostIP, ushServerSock)!=FTP_OK ) return false; // establish connection CSockAddr sockAddrTemp; try { sckDataConnection.Create(SOCK_STREAM); CSockAddr csaAddress(ulRemoteHostIP, ushServerSock); sckDataConnection.Connect(csaAddress); } catch(CBlockingSocketException& blockingException) { ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); sckDataConnection.Cleanup(); return false; } // if resuming is activated then set offset if( m_fResumeIfPossible && (crDatachannelCmd==CCommand::STOR() || crDatachannelCmd==CCommand::RETR() || crDatachannelCmd==CCommand::APPE() ) && (dwByteOffset!=0 && Restart(dwByteOffset)!=FTP_OK) ) return false; // send FTP command RETR/STOR/NLST/LIST to the server CReply Reply; if( !SendCommand(crDatachannelCmd, strPath, Reply) || !Reply.Code().IsPositivePreliminaryReply() ) return false; return true; } /// Sends data over a socket to the server. /// @param[in] Observer Object for observing the execution of the command. /// @param[in] sckDataConnection Socket which is used for the send action. bool CFTPClient::SendData(ITransferNotification& Observer, IBlockingSocket& sckDataConnection) const { try { m_fTransferInProgress=true; int iNumWrite = 0; size_t bytesRead = 0; Observer.OnPreBytesSend(&m_vBuffer.front(), m_vBuffer.size(), bytesRead); while( !m_fAbortTransfer && bytesRead!=0 ) { iNumWrite = sckDataConnection.Write(&(*m_vBuffer.begin()), static_cast<int>(bytesRead), mc_uiTimeout); ASSERT( iNumWrite == static_cast<int>(bytesRead) ); for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnBytesSent(m_vBuffer, iNumWrite); Observer.OnPreBytesSend(&m_vBuffer.front(), m_vBuffer.size(), bytesRead); } m_fTransferInProgress=false; if( m_fAbortTransfer ) { Abort(); return false; } } catch(CBlockingSocketException& blockingException) { m_fTransferInProgress=false; ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); sckDataConnection.Cleanup(); return false; } return true; } /// Receives data over a socket from the server. /// @param[in] Observer Object for observing the execution of the command. /// @param[in] sckDataConnection Socket which is used for receiving the data. bool CFTPClient::ReceiveData(ITransferNotification& Observer, IBlockingSocket& sckDataConnection) const { try { m_fTransferInProgress = true; for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnBeginReceivingData(); int iNumRead=sckDataConnection.Receive(&(*m_vBuffer.begin()), static_cast<int>(m_vBuffer.size()), mc_uiTimeout); long lTotalBytes = iNumRead; while( !m_fAbortTransfer && iNumRead!=0 ) { for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnBytesReceived(m_vBuffer, iNumRead); Observer.OnBytesReceived(m_vBuffer, iNumRead); iNumRead=sckDataConnection.Receive(&(*m_vBuffer.begin()), static_cast<int>(m_vBuffer.size()), mc_uiTimeout); lTotalBytes += iNumRead; } for( TObserverSet::const_iterator it2=m_setObserver.begin(); it2!=m_setObserver.end(); it2++ ) (*it2)->OnEndReceivingData(lTotalBytes); m_fTransferInProgress=false; if( m_fAbortTransfer ) { Abort(); return false; } } catch(CBlockingSocketException& blockingException) { m_fTransferInProgress=false; ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); sckDataConnection.Cleanup(); return false; } return true; } /// Sends a command to the server. /// @param[in] Command Command to send. bool CFTPClient::SendCommand(const CCommand& Command, const CArg& Arguments) const { if( !IsConnected() ) return false; try { for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnSendCommand(Command, Arguments); const std::string strCommand = CCnv::ConvertToString(Command.AsString(Arguments)) + "\r\n"; m_apSckControlConnection->Write(strCommand.c_str(), static_cast<int>(strCommand.length()), mc_uiTimeout); } catch(CBlockingSocketException& blockingException) { ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); const_cast<CFTPClient*>(this)->m_apSckControlConnection->Cleanup(); return false; } return true; } /// Sends a command to the server. /// @param[in] Command Command to send. /// @param[out] Reply The Reply of the server to the sent command. bool CFTPClient::SendCommand(const CCommand& Command, const CArg& Arguments, CReply& Reply) const { if( !SendCommand(Command, Arguments) || !GetResponse(Reply) ) return false; return true; } /// This function gets the server response. /// A server response can exists of more than one line. This function /// returns the full response (multiline). /// @param[out] Reply Reply of the server to a command. bool CFTPClient::GetResponse(CReply& Reply) const { tstring strResponse; if( !GetSingleResponseLine(strResponse) ) return false; if( strResponse.length()>3 && strResponse.at(3)==_T('-') ) { tstring strSingleLine(strResponse); const int iRetCode=CCnv::TStringToLong(strResponse); // handle multi-line server responses while( !(strSingleLine.length()>3 && strSingleLine.at(3)==_T(' ') && CCnv::TStringToLong(strSingleLine)==iRetCode) ) { if( !GetSingleResponseLine(strSingleLine) ) return false; strResponse += mc_strEolCharacterSequence + strSingleLine; } } bool fRet = Reply.Set(strResponse); for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnResponse(Reply); return fRet; } /// Reads a single response line from the server control channel. /// @param[out] strResponse Response of the server as string. bool CFTPClient::GetSingleResponseLine(tstring& strResponse) const { if( !IsConnected() ) return false; try { if( m_qResponseBuffer.empty() ) { // internal buffer is empty ==> get response from FTP server int iNum=0; std::string strTemp; do { iNum=m_apSckControlConnection->Receive(&(*m_vBuffer.begin()), static_cast<int>(m_vBuffer.size())-1, mc_uiTimeout); if( mc_uiResponseWait !=0 ) Sleep(mc_uiResponseWait); m_vBuffer[iNum] = '\0'; strTemp+=&(*m_vBuffer.begin()); } while( iNum==static_cast<int>(m_vBuffer.size())-1 && m_apSckControlConnection->CheckReadability() ); // each line in response is a separate entry in the internal buffer while( strTemp.length() ) { size_t iCRLF=strTemp.find('\n'); if( iCRLF != std::string::npos ) { m_qResponseBuffer.push(strTemp.substr(0, iCRLF+1)); strTemp.erase(0, iCRLF+1); } else { // this is not rfc standard; normally each command must end with CRLF // in this case it doesn't m_qResponseBuffer.push(strTemp); strTemp.clear(); } } if( m_qResponseBuffer.empty() ) return false; } // get first response-line from buffer strResponse = CCnv::ConvertToTString(m_qResponseBuffer.front().c_str()); m_qResponseBuffer.pop(); // remove CrLf if exists (don't use mc_strEolCharacterSequence here) if( strResponse.length()> 1 && strResponse.substr(strResponse.length()-2)==_T("\r\n") ) strResponse.erase(strResponse.length()-2, 2); } catch(CBlockingSocketException& blockingException) { ReportError(blockingException.GetErrorMessage(), CCnv::ConvertToTString(__FILE__), __LINE__); const_cast<CFTPClient*>(this)->m_apSckControlConnection->Cleanup(); return false; } return true; } /// Executes the FTP command CDUP (change to parent directory). /// This command is a special case of CFTPClient::ChangeWorkingDirectory /// (CWD), and is included to simplify the implementation of programs for /// transferring directory trees between operating systems having different /// syntaxes for naming the parent directory. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::ChangeToParentDirectory() const { CReply Reply; if( !SendCommand(CCommand::CDUP(), CArg(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command QUIT. /// This command terminates a USER and if file transfer is not in progress, /// the server closes the control connection. If file transfer is in progress, /// the connection will remain open for result response and the server will /// then close it. /// If the user-process is transferring files for several USERs but does not /// wish to close and then reopen connections for each, then the REIN command /// should be used instead of QUIT. /// An unexpected close on the control connection will cause the server to take /// the effective action of an abort (ABOR) and a logout. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Logout() { CReply Reply; if( !SendCommand(CCommand::QUIT(), CArg(), Reply) ) return FTP_ERROR; CloseControlChannel(); return SimpleErrorCheck(Reply); } /// Executes the FTP command PASV. Set the passive mode. /// This command requests the server-DTP (data transfer process) on a data to /// "listen" port (which is not its default data port) and to wait for a /// connection rather than initiate one upon receipt of a transfer command. /// The response to this command includes the host and port address this /// server is listening on. /// @param[out] ulIpAddress IP address the server is listening on. /// @param[out] ushPort Port the server is listening on. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Passive(ULONG& ulIpAddress, USHORT& ushPort) const { CReply Reply; if( !SendCommand(CCommand::PASV(), CArg(), Reply) ) return FTP_ERROR; if( Reply.Code().IsPositiveCompletionReply() ) { if( !GetIpAddressFromResponse(Reply.Value(), ulIpAddress, ushPort) ) return FTP_ERROR; } return SimpleErrorCheck(Reply); } /// Parses a response string and extracts the ip address and port information. /// @param[in] strResponse The response string of a FTP server which holds /// the ip address and port information. /// @param[out] ulIpAddress Buffer for the ip address. /// @param[out] ushPort Buffer for the port information. /// @retval true Everything went ok. /// @retval false An error occurred (invalid format). bool CFTPClient::GetIpAddressFromResponse(const tstring& strResponse, ULONG& ulIpAddress, USHORT& ushPort) const { // parsing of ip-address and port implemented with a finite state machine // ...(192,168,1,1,3,44)... enum T_enState { state0, state1, state2, state3, state4 } enState = state0; tstring strIpAddress, strPort; USHORT ushTempPort = 0; ULONG ulTempIpAddress = 0; int iCommaCnt = 4; for( tstring::const_iterator it=strResponse.begin(); it!=strResponse.end(); ++it ) { switch( enState ) { case state0: if( *it == _T('(') ) enState = state1; break; case state1: if( *it == _T(',') ) { if( --iCommaCnt == 0 ) { enState = state2; ulTempIpAddress += CCnv::TStringToLong(strIpAddress.c_str()); } else { ulTempIpAddress += CCnv::TStringToLong(strIpAddress.c_str())<<8*iCommaCnt; strIpAddress.clear(); } } else { if( !tisdigit(*it) ) return false; strIpAddress += *it; } break; case state2: if( *it == _T(',') ) { ushTempPort = static_cast<USHORT>(CCnv::TStringToLong(strPort.c_str())<<8); strPort.clear(); enState = state3; } else { if( !tisdigit(*it) ) return false; strPort += *it; } break; case state3: if( *it == _T(')') ) { // compiler warning if using +=operator ushTempPort = ushTempPort + static_cast<USHORT>(CCnv::TStringToLong(strPort.c_str())); enState = state4; } else { if( !tisdigit(*it) ) return false; strPort += *it; } break; case state4: break; // some compilers complain if not all enumeration values are listet } } if( enState==state4 ) { ulIpAddress = ulTempIpAddress; ushPort = ushTempPort; } return enState==state4; } /// Executes the FTP command ABOR. /// This command tells the server to abort the previous FTP service command /// and any associated transfer of data. The abort command may require /// "special action", as discussed in the Section on FTP Commands, to force /// recognition by the server. No action is to be taken if the previous /// command has been completed (including data transfer). The control /// connection is not to be closed by the server, but the data connection /// must be closed. /// There are two cases for the server upon receipt of this command:<BR> /// (1) the FTP service command was already completed, or <BR> /// (2) the FTP service command is still in progress.<BR> /// In the first case, the server closes the data connection (if it is open) /// and responds with a 226 reply, indicating that the abort command was /// successfully processed. /// In the second case, the server aborts the FTP service in progress and /// closes the data connection, returning a 426 reply to indicate that the /// service request terminated abnormally. The server then sends a 226 reply, /// indicating that the abort command was successfully processed. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Abort() const { if( m_fTransferInProgress ) { m_fAbortTransfer = true; return FTP_OK; } m_fAbortTransfer = false; CReply Reply; if( !SendCommand(CCommand::ABOR(), CArg(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command PWD (PRINT WORKING DIRECTORY) /// This command causes the name of the current working directory /// to be returned in the reply. int CFTPClient::PrintWorkingDirectory() const { CReply Reply; if( !SendCommand(CCommand::PWD(), CArg(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command SYST (SYSTEM) /// This command is used to find out the type of operating system at the server. /// The reply shall have as its first word one of the system names listed in the /// current version of the Assigned Numbers document [Reynolds, Joyce, and /// Jon Postel, "Assigned Numbers", RFC 943, ISI, April 1985.]. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::System() const { CReply Reply; if( !SendCommand(CCommand::SYST(), CArg(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command NOOP /// This command does not affect any parameters or previously entered commands. /// It specifies no action other than that the server send an FTP_OK reply. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Noop() const { CReply Reply; if( !SendCommand(CCommand::NOOP(), CArg(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command PORT (DATA PORT) /// The argument is a HOST-PORT specification for the data port to be used in data /// connection. There are defaults for both the user and server data ports, and /// under normal circumstances this command and its reply are not needed. If /// this command is used, the argument is the concatenation of a 32-bit internet /// host address and a 16-bit TCP port address. /// @param[in] strHostIP IP-address like xxx.xxx.xxx.xxx /// @param[in] uiPort 16-bit TCP port address. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::DataPort(const tstring& strHostIP, USHORT ushPort) const { tstring strPortArguments; // convert the port number to 2 bytes + add to the local IP strPortArguments = CMakeString() << strHostIP << _T(",") << (ushPort>>8) << _T(",") << (ushPort&0xFF); ReplaceStr(strPortArguments, _T("."), _T(",")); CReply Reply; if( !SendCommand(CCommand::PORT(), strPortArguments, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command TYPE (REPRESENTATION TYPE) /// Caches the representation state if successful. /// see Documentation of nsFTP::CRepresentation /// @param[in] representation see Documentation of nsFTP::CRepresentation /// @param[in] iSize Indicates Bytesize for type LocalByte. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::RepresentationType(const CRepresentation& representation, DWORD dwSize) const { // check representation if( m_apCurrentRepresentation.get()!=NULL && representation==*m_apCurrentRepresentation ) return FTP_OK; const int iRet = _RepresentationType(representation, dwSize); if( iRet==FTP_OK ) { if( m_apCurrentRepresentation.get()==NULL ) m_apCurrentRepresentation.reset(new CRepresentation(representation)); else *m_apCurrentRepresentation = representation; } else m_apCurrentRepresentation.reset(NULL); return iRet; } /// Executes the FTP command TYPE (REPRESENTATION TYPE) /// see Documentation of nsFTP::CRepresentation /// @param[in] representation see Documentation of nsFTP::CRepresentation /// @param[in] dwSize Indicates Bytesize for type LocalByte. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::_RepresentationType(const CRepresentation& representation, DWORD dwSize) const { CArg Arguments(representation.Type().AsString()); switch( representation.Type().AsEnum() ) { case CType::tyLocalByte: Arguments.push_back(CMakeString() << dwSize); break; case CType::tyASCII: case CType::tyEBCDIC: case CType::tyImage: if( representation.Format().IsValid() ) Arguments.push_back(representation.Format().AsString()); } CReply Reply; if( !SendCommand(CCommand::TYPE(), Arguments, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command CWD (CHANGE WORKING DIRECTORY) /// This command allows the user to work with a different directory or dataset /// for file storage or retrieval without altering his login or accounting /// information. Transfer parameters are similarly unchanged. /// @param[in] strDirectory Pathname specifying a directory or other system /// dependent file group designator. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::ChangeWorkingDirectory(const tstring& strDirectory) const { ASSERT( !strDirectory.empty() ); CReply Reply; if( !SendCommand(CCommand::CWD(), strDirectory, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command MKD (MAKE DIRECTORY) /// This command causes the directory specified in the pathname to be created /// as a directory (if the pathname is absolute) or as a subdirectory of the /// current working directory (if the pathname is relative). /// @pararm[in] strDirectory Pathname specifying a directory to be created. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::MakeDirectory(const tstring& strDirectory) const { ASSERT( !strDirectory.empty() ); CReply Reply; if( !SendCommand(CCommand::MKD(), strDirectory, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command SITE (SITE PARAMETERS) /// This command is used by the server to provide services specific to his /// system that are essential to file transfer but not sufficiently universal /// to be included as commands in the protocol. The nature of these services /// and the specification of their syntax can be stated in a reply to the HELP /// SITE command. /// @param[in] strCmd Command to be executed. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::SiteParameters(const tstring& strCmd) const { ASSERT( !strCmd.empty() ); CReply Reply; if( !SendCommand(CCommand::SITE(), strCmd, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command HELP /// This command shall cause the server to send helpful information regarding /// its implementation status over the control connection to the user. /// The command may take an argument (e.g., any command name) and return more /// specific information as a response. The reply is type 211 or 214. /// It is suggested that HELP be allowed before entering a USER command. The /// server may use this reply to specify site-dependent parameters, e.g., in /// response to HELP SITE. /// @param[in] strTopic Topic of the requested help. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Help(const tstring& strTopic) const { CReply Reply; if( !SendCommand(CCommand::HELP(), strTopic, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command DELE (DELETE) /// This command causes the file specified in the pathname to be deleted at the /// server site. If an extra level of protection is desired (such as the query, /// "Do you really wish to delete?"), it should be provided by the user-FTP process. /// @param[in] strFile Pathname of the file to delete. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Delete(const tstring& strFile) const { ASSERT( !strFile.empty() ); CReply Reply; if( !SendCommand(CCommand::DELE(), strFile, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command RMD (REMOVE DIRECTORY) /// This command causes the directory specified in the pathname to be removed /// as a directory (if the pathname is absolute) or as a subdirectory of the /// current working directory (if the pathname is relative). /// @param[in] strDirectory Pathname of the directory to delete. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::RemoveDirectory(const tstring& strDirectory) const { ASSERT( !strDirectory.empty() ); CReply Reply; if( !SendCommand(CCommand::RMD(), strDirectory, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command STRU (FILE STRUCTURE) /// see documentation of nsFTP::CStructure /// The default structure is File. /// @param[in] crStructure see Documentation of nsFTP::CStructure /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::FileStructure(const CStructure& crStructure) const { CReply Reply; if( !SendCommand(CCommand::STRU(), crStructure.AsString(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command MODE (TRANSFER MODE) /// see documentation of nsFTP::CTransferMode /// The default transfer mode is Stream. /// @param[in] crTransferMode see Documentation of nsFTP::CTransferMode /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::TransferMode(const CTransferMode& crTransferMode) const { CReply Reply; if( !SendCommand(CCommand::MODE(), crTransferMode.AsString(), Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command STAT (STATUS) /// This command shall cause a status response to be sent over the control /// connection in the form of a reply. The command may be sent during a file /// transfer (along with the Telnet IP and Synch signals--see the Section on /// FTP Commands) in which case the server will respond with the status of the /// operation in progress, or it may be sent between file transfers. In the /// latter case, the command may have an argument field. /// @param[in] strPath If the argument is a pathname, the command is analogous /// to the "list" command except that data shall be transferred /// over the control connection. If a partial pathname is /// given, the server may respond with a list of file names or /// attributes associated with that specification. If no argument /// is given, the server should return general status information /// about the server FTP process. This should include current /// values of all transfer parameters and the status of connections. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Status(const tstring& strPath) const { CReply Reply; if( !SendCommand(CCommand::STAT(), strPath, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command ALLO (ALLOCATE) /// This command may be required by some servers to reserve sufficient storage /// to accommodate the new file to be transferred. /// @param[in] iReserveBytes The argument shall be a decimal integer representing /// the number of bytes (using the logical byte size) of /// storage to be reserved for the file. For files sent /// with record or page structure a maximum record or page /// size (in logical bytes) might also be necessary; this /// is indicated by a decimal integer in a second argument /// field of the command. /// @pararm[in] piMaxPageOrRecordSize This second argument is optional. This command /// shall be followed by a STORe or APPEnd command. /// The ALLO command should be treated as a NOOP (no operation) /// by those servers which do not require that the maximum /// size of the file be declared beforehand, and those servers /// interested in only the maximum record or page size should /// accept a dummy value in the first argument and ignore it. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Allocate(int iReserveBytes, const int* piMaxPageOrRecordSize/*=NULL*/) const { CArg Arguments(CMakeString() << iReserveBytes); if( piMaxPageOrRecordSize!=NULL ) { Arguments.push_back(_T("R")); Arguments.push_back(CMakeString() << *piMaxPageOrRecordSize); } CReply Reply; if( !SendCommand(CCommand::ALLO(), Arguments, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command SMNT () /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::StructureMount(const tstring& strPath) const { CReply Reply; if( !SendCommand(CCommand::SMNT(), strPath, Reply) ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Executes the FTP command (STRUCTURE MOUNT) /// This command allows the user to mount a different file system data structure /// without altering his login or accounting information. Transfer parameters /// are similarly unchanged. The argument is a pathname specifying a directory /// or other system dependent file group designator. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Reinitialize() const { CReply Reply; if( !SendCommand(CCommand::REIN(), CArg(), Reply) ) return FTP_ERROR; if( Reply.Code().IsPositiveCompletionReply() ) return FTP_OK; else if( Reply.Code().IsPositivePreliminaryReply() ) { if( !GetResponse(Reply) || !Reply.Code().IsPositiveCompletionReply() ) return FTP_ERROR; } else if( Reply.Code().IsNegativeReply() ) return FTP_NOTOK; ASSERT( Reply.Code().IsPositiveIntermediateReply() ); return FTP_ERROR; } /// Executes the FTP command REST (RESTART) /// This command does not cause file transfer but skips over the file to the /// specified data checkpoint. This command shall be immediately followed /// by the appropriate FTP service command which shall cause file transfer /// to resume. /// @param[in] dwPosition Represents the server marker at which file transfer /// is to be restarted. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::Restart(DWORD dwPosition) const { CReply Reply; if( !SendCommand(CCommand::REST(), CArg(CMakeString() << dwPosition), Reply) ) return FTP_ERROR; if( Reply.Code().IsPositiveIntermediateReply() ) return FTP_OK; else if( Reply.Code().IsNegativeReply() ) return FTP_NOTOK; ASSERT( Reply.Code().IsPositiveReply() ); return FTP_ERROR; } /// Executes the FTP command SIZE /// Return size of file. /// SIZE is not specified in RFC 959. /// @param[in] Pathname of a file. /// @param[out] Size of the file specified in pathname. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::FileSize(const tstring& strPath, long& lSize) const { CReply Reply; if( !SendCommand(CCommand::SIZE(), strPath, Reply) ) return FTP_ERROR; lSize = CCnv::TStringToLong(Reply.Value().substr(4).c_str()); return SimpleErrorCheck(Reply); } /// Executes the FTP command MDTM /// Show last modification time of file. /// MDTM is not specified in RFC 959. /// @param[in] strPath Pathname of a file. /// @param[out] strModificationTime Modification time of the file specified in pathname. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::FileModificationTime(const tstring& strPath, tstring& strModificationTime) const { strModificationTime.erase(); CReply Reply; if( !SendCommand(CCommand::MDTM(), strPath, Reply) ) return FTP_ERROR; if( Reply.Value().length()>=18 ) { tstring strTemp(Reply.Value().substr(4)); size_t iPos=strTemp.find(_T('.')); if( iPos!=tstring::npos ) strTemp = strTemp.substr(0, iPos); if( strTemp.length()==14 ) strModificationTime=strTemp; } if( strModificationTime.empty() ) return FTP_ERROR; return SimpleErrorCheck(Reply); } /// Show last modification time of file. /// @param[in] strPath Pathname of a file. /// @param[out] tmModificationTime Modification time of the file specified in pathname. /// @return see return values of CFTPClient::SimpleErrorCheck int CFTPClient::FileModificationTime(const tstring& strPath, tm& tmModificationTime) const { tstring strTemp; const int iRet = FileModificationTime(strPath, strTemp); memset(&tmModificationTime, 0, sizeof(tmModificationTime)); if( iRet==FTP_OK ) { tmModificationTime.tm_year = CCnv::TStringToLong(strTemp.substr(0, 4).c_str()); tmModificationTime.tm_mon = CCnv::TStringToLong(strTemp.substr(4, 2).c_str()); tmModificationTime.tm_mday = CCnv::TStringToLong(strTemp.substr(6, 2).c_str()); tmModificationTime.tm_hour = CCnv::TStringToLong(strTemp.substr(8, 2).c_str()); tmModificationTime.tm_min = CCnv::TStringToLong(strTemp.substr(10, 2).c_str()); tmModificationTime.tm_sec = CCnv::TStringToLong(strTemp.substr(12).c_str()); } return iRet; } /// Notifies all observers that an error occurred. /// @param[in] strErrorMsg Error message which is reported to all observers. /// @param[in] Name of the sourcecode file where the error occurred. /// @param[in] Line number in th sourcecode file where the error occurred. void CFTPClient::ReportError(const tstring& strErrorMsg, const tstring& strFile, DWORD dwLineNr) const { for( TObserverSet::const_iterator it=m_setObserver.begin(); it!=m_setObserver.end(); it++ ) (*it)->OnInternalError(strErrorMsg, strFile, dwLineNr); }
[ "jjuiddong@gmail.com" ]
jjuiddong@gmail.com
00f6b437beb05fd216b84ed618877e9150b5e744
4f7c53c128328f294e9b67a4eb00b72c459692e6
/app/Document/PurchaseDocument/PurchaseInvoiceManager.h
e794f938311e128b1dfd9d401b5346c8acd8bbe0
[]
no_license
milczarekIT/agila
a94d59c1acfe171eb361be67acda1c5babc69df6
ec0ddf53dfa54aaa21d48b5e7f334aabcba5227e
refs/heads/master
2021-01-10T06:39:56.117202
2013-08-24T20:15:22
2013-08-24T20:15:22
46,000,158
1
1
null
null
null
null
UTF-8
C++
false
false
748
h
#ifndef PURCHASEINVOICEMANAGER_H #define PURCHASEINVOICEMANAGER_H #include "Document/SaleDocument/InvoiceManager.h" #include "Document/PurchaseDocument/PurchaseInvoice.h" class PurchaseInvoiceManager : public InvoiceManager { public: PurchaseInvoiceManager(); ~PurchaseInvoiceManager(); void setPurchaseInvoiceData(PurchaseInvoice doc); PurchaseInvoice getPurchaseInvoiceOld(); PurchaseInvoice getPurchaseInvoice(); void setPurchaseInvoiceOld(PurchaseInvoice purchaseInvoiceOld); void setPurchaseInvoice(PurchaseInvoice purchaseInvoice); void setContractor(Contractor c); Contractor getContractor(); protected: PurchaseInvoice purchaseInvoice,purchaseInvoiceOld; }; #endif // PURCHASEINVOICEMANAGER_H
[ "milczarek@bluebraces.com" ]
milczarek@bluebraces.com
a1f56c0d1eb191ffd2df80a6e795fd036905bc73
938f2b39d3d145e91d4f2a0e8f85b473c37ef9ad
/dsp_hw1/hw1_b03901011/train.cpp
7d8b7a6635c4cc2d95f55c1542caa17f7e7deeac
[]
no_license
lfangin/DSP
5593820336b2d50351f97b46e9596a044311baa9
60c00cf4669873a4fd64d77886492f506f5794d2
refs/heads/master
2021-01-20T09:02:17.190288
2017-12-21T17:56:03
2017-12-21T17:56:03
90,215,440
0
0
null
null
null
null
UTF-8
C++
false
false
3,500
cpp
#include "hmm.h" #include <math.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <stdlib.h> using namespace std; #define T 50 #define N 6 #define S 10000 int main(int argc, char **argv)//[./train][iteration][model_init.txt][seq_model_01.txt][model_01.txt] { HMM iniModel; int iteration = atoi(argv[1]); char *iniName = argv[2], *seqName = argv[3], *outName = argv[4]; loadHMM( &iniModel, iniName ); double alpha[T][N],beta[T][N], gamma[N][T], epsilon[T-1][N][N]; double accGamma[N], accEpsilon[N][N], observGamma[N][N],firstGamma[N], lastGamma[N]; // vector<string> seq; string line; ifstream fs; fs.open(seqName); while(getline(fs,line)) seq.push_back(line); fs.close(); // for(; iteration > 0; iteration-- ){ for(int i = 0; i < N; i++){ accGamma[i] = 0.0; firstGamma[i] = 0.0; lastGamma[i] = 0.0; for(int j = 0; j < N; j++){ accEpsilon[i][j] = 0.0; observGamma[i][j] = 0.0; } } for(int lineNum = 0; lineNum < S; lineNum++){ string line = seq[lineNum]; //calculate alpha for(int i = 0; i < N; i++) alpha[0][i] = iniModel.initial[i] * iniModel.observation[line[0]-'A'][i]; for(int t = 1; t < T; t++){ for(int j = 0; j < N; j++){ double tmp_sum = 0; for(int i = 0; i < N; i++) tmp_sum += alpha[t-1][i] * iniModel.transition[i][j]; alpha[t][j] = tmp_sum * iniModel.observation[line[t]-'A'][j]; } } //calculate beta for(int i = 0; i < N; i++) beta[T-1][i] = 1; for(int t = T-1; t > 0; t--) for(int i = 0; i < N; i++){ double tmp_sum = 0; for(int j = 0; j < N; j++) tmp_sum += iniModel.transition[i][j] * iniModel.observation[line[t]-'A'][j] * beta[t][j]; beta[t-1][i] = tmp_sum; } //calculate gamma for(int t = 0; t < T; t++){ double tmp_sum = 0; for(int i = 0; i < N; i++) tmp_sum += alpha[t][i]*beta[t][i]; for(int i = 0; i < N; i++){ gamma[i][t] = alpha[t][i]*beta[t][i] / tmp_sum; if(t == T-1) lastGamma[i] += gamma[i][t]; else accGamma[i] += gamma[i][t];//accumulate gamma observGamma[line[t]-'A'][i] += gamma[i][t]; } } //calculate epsilon double p[N][N]; for(int t = 0; t < T-1; t++){ double tmp_sum = 0; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ p[i][j] = alpha[t][i]*iniModel.transition[i][j]*iniModel.observation[line[t+1]-'A'][j]*beta[t+1][j]; tmp_sum += p[i][j]; } } for(int i = 0; i < N; i++) for(int j = 0; j < N; j++){ epsilon[t][i][j] = p[i][j]/tmp_sum; accEpsilon[i][j]+= epsilon[t][i][j];//accumulate epsilon } } //accumulate firstGamma for(int i = 0; i < N; i++) firstGamma[i] += gamma[i][0]; }//end of one sample for(int i = 0; i < N; i++){ iniModel.initial[i] = firstGamma[i]/S; for(int j = 0; j < N; j++) iniModel.transition[i][j] = accEpsilon[i][j]/accGamma[i]; for(int k = 0; k < N; k++) iniModel.observation[k][i] = observGamma[k][i]/(accGamma[i]+lastGamma[i]); } }//end of iteration //HMM *result; strcpy(iniModel.model_name,argv[4]); FILE *fp = fopen(argv[4],"w"); dumpHMM(fp,&iniModel); fclose(fp); return 0; }
[ "b0390011@ntu.edu.tw" ]
b0390011@ntu.edu.tw
c38f50f2e8243a1bc4ffa9e3e5e804b8331d8726
162d4b6d1ddad4d3e52b309feba3e4c26e69a5ed
/03_Simple_2D_game/Asteroid/include/SFML-Book/Game.hpp
43e3a1a80a4e56cc928fcb37c858037d31f64653
[]
no_license
akashdeepk/SFML-book
bcdf01b47e4f5933fefcbb15b4c294d7d2f48ba7
8b92e1636ac5cd44413145cdbdd20d8e59233e71
refs/heads/master
2021-01-22T15:58:47.915829
2014-11-27T21:13:12
2014-11-27T21:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
hpp
#ifndef BOOK_GAME_HPP #define BOOK_GAME_HPP #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML-Book/World.hpp> /** * \brief namespace for the book */ namespace book { /** * \brief A class to manage the game */ class Game { public: //non copyable class Game(const Game&) = delete; Game& operator=(const Game&) = delete; Game(int X=1600, int Y=900); //< constructor void run(int minimum_frame_per_seconds=30); void initLevel(); private: void processEvents();//< Process events void update(sf::Time deltaTime); //< do some updates void render();//< draw all the stuff void reset(); sf::RenderWindow _window; //< the window use to display the game World _world; sf::Time _next_saucer; sf::Text _txt; }; } #endif
[ "maxime.barbier1991@gmail.com" ]
maxime.barbier1991@gmail.com
eddba56380d82f1c1c0218f5e6c1e6a91d8bcc3f
20a9fecc11881edda151073c3ad3e39c091641d6
/proxygen/lib/http/connpool/SessionHolder.cpp
4eebce7b41da873bbc92ed562a5d00c8973cf5e5
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
KIKOU2016/proxygen
11fc5adb8d92cf0b0e86d607cbfad75a5c05e3ca
a235726328066a3c9de7d9c3c0c75e44e939fbe6
refs/heads/master
2020-06-28T03:32:51.857013
2019-08-01T21:11:20
2019-08-01T21:14:47
200,132,896
1
0
NOASSERTION
2019-08-01T23:44:12
2019-08-01T23:44:12
null
UTF-8
C++
false
false
9,871
cpp
/* * Copyright (c) 2015-present, Facebook, 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. * */ #include "proxygen/lib/http/connpool/SessionHolder.h" #include <folly/Random.h> #include <folly/io/async/AsyncSocket.h> #include <glog/logging.h> using folly::AsyncSocket; using folly::SocketAddress; namespace { const double kJitterPct = 0.3; } namespace proxygen { SessionHolder::SessionHolder(HTTPSessionBase* sess, Callback* parent, Stats* stats, Endpoint endpoint) : session_(CHECK_NOTNULL(sess)), parent_(CHECK_NOTNULL(parent)), stats_(stats), jitter_(folly::Random::randDouble(-kJitterPct, kJitterPct)), endpoint_(std::move(endpoint)), originalSessionInfoCb_(sess->getInfoCallback()) { session_->setInfoCallback(this); } SessionHolder::~SessionHolder() { CHECK(state_ == ListState::DETACHED); CHECK(!listHook.is_linked()); CHECK(!secondaryListHook.is_linked()); } bool SessionHolder::isPoolable(const HTTPSessionBase* sess) { return !sess->isClosing() && (sess->getNumOutgoingStreams() || sess->isReusable()); } bool SessionHolder::shouldAgeOut(std::chrono::milliseconds maxAge) const { if (maxAge.count() <= 0) { return false; } double sessMaxAge = (1 + jitter_) * maxAge.count(); auto age = millisecondsSince(session_->getSetupTransportInfo().acceptTime); return age >= std::chrono::milliseconds(int64_t(sessMaxAge)); } const HTTPSessionBase& SessionHolder::getSession() const { return *session_; } HTTPTransaction* SessionHolder::newTransaction( HTTPTransaction::Handler* handler) { return session_->newTransaction(handler); } std::chrono::steady_clock::time_point SessionHolder::getLastUseTime() const { return lastUseTime_; } void SessionHolder::drain() { VLOG(4) << "draining holder=" << *this; if (state_ != ListState::DETACHED) { unlink(); } if (stats_) { // The connection hasn't closed yet, but it will. We won't find out // about when it actually closes since we are setting the info // callback to nullptr. stats_->onConnectionClosed(); if (session_->hasActiveTransactions()) { stats_->onConnectionDeactivated(); } } session_->setInfoCallback(originalSessionInfoCb_); originalSessionInfoCb_ = nullptr; parent_->addDrainingSession(session_); session_->drain(); delete this; } void SessionHolder::closeWithReset() { if (state_ != ListState::DETACHED) { unlink(); } if (stats_) { // The connection hasn't closed yet, but it will. We won't find out // about when it actually closes since we are setting the info // callback to nullptr. stats_->onConnectionClosed(); if (session_->hasActiveTransactions()) { stats_->onConnectionDeactivated(); } } session_->setInfoCallback(originalSessionInfoCb_); originalSessionInfoCb_ = nullptr; session_->dropConnection(); delete this; } void SessionHolder::unlink() { CHECK(parent_); CHECK(listHook.is_linked()); switch (state_) { case ListState::IDLE: parent_->detachIdle(this); break; case ListState::PARTIAL: parent_->detachPartiallyFilled(this); break; case ListState::FULL: parent_->detachFilled(this); break; case ListState::DETACHED: LOG(FATAL) << "Inconsistentency between listHook.is_linked() and state_"; } state_ = ListState::DETACHED; } void SessionHolder::link() { CHECK(state_ == ListState::DETACHED); if (!parent_) { return; } if (!isPoolable(session_)) { VLOG(4) << *this << " Not pooling session since it is not poolable"; drain(); return; } lastUseTime_ = std::chrono::steady_clock::now(); auto curTxnCount = session_->getNumOutgoingStreams(); if (curTxnCount == 0 && session_->isDetachable(/*checkSocket=*/false)) { state_ = ListState::IDLE; parent_->attachIdle(this); } else if (curTxnCount < session_->getMaxConcurrentOutgoingStreams()) { state_ = ListState::PARTIAL; parent_->attachPartiallyFilled(this); } else { state_ = ListState::FULL; parent_->attachFilled(this); } } void SessionHolder::onCreate(const HTTPSessionBase&) { LOG(FATAL) << "onCreate() should not be reachable."; } void SessionHolder::onIngressError(const HTTPSessionBase& session, ProxygenError error) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onIngressError(session, error); } } void SessionHolder::onRead(const HTTPSessionBase& session, size_t bytesRead) { if (stats_) { stats_->onRead(bytesRead); } if (originalSessionInfoCb_) { originalSessionInfoCb_->onRead(session, bytesRead); } } void SessionHolder::onWrite(const HTTPSessionBase& session, size_t bytesWritten) { if (stats_) { stats_->onWrite(bytesWritten); } if (originalSessionInfoCb_) { originalSessionInfoCb_->onWrite(session, bytesWritten); } } void SessionHolder::onRequestBegin(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onRequestBegin(session); } } void SessionHolder::onRequestEnd(const HTTPSessionBase& session, uint32_t maxIngressQueueSize) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onRequestEnd(session, maxIngressQueueSize); } } void SessionHolder::onActivateConnection(const HTTPSessionBase& session) { if (stats_) { stats_->onConnectionActivated(); } if (originalSessionInfoCb_) { originalSessionInfoCb_->onActivateConnection(session); } } void SessionHolder::onDeactivateConnection(const HTTPSessionBase& sess) { if (stats_) { stats_->onConnectionDeactivated(); } if (originalSessionInfoCb_) { originalSessionInfoCb_->onDeactivateConnection(sess); } handleTransactionDetached(); } void SessionHolder::onDestroy(const HTTPSessionBase& session) { if (state_ != ListState::DETACHED) { unlink(); } if (stats_) { stats_->onConnectionClosed(); } if (originalSessionInfoCb_) { originalSessionInfoCb_->onDestroy(session); } VLOG(4) << *this << " connection to server was destroyed"; delete this; } void SessionHolder::onIngressMessage(const HTTPSessionBase& session, const HTTPMessage& msg) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onIngressMessage(session, msg); } } void SessionHolder::onIngressLimitExceeded(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onIngressLimitExceeded(session); } } void SessionHolder::onIngressPaused(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onIngressPaused(session); } } void SessionHolder::onTransactionDetached(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onTransactionDetached(session); } handleTransactionDetached(); } void SessionHolder::onPingReplySent(int64_t latency) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onPingReplySent(latency); } }; void SessionHolder::onPingReplyReceived() { if (originalSessionInfoCb_) { originalSessionInfoCb_->onPingReplyReceived(); } }; void SessionHolder::onSettingsOutgoingStreamsFull( const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onSettingsOutgoingStreamsFull(session); } if (state_ != ListState::DETACHED && state_ != ListState::FULL) { unlink(); link(); } } void SessionHolder::onSettingsOutgoingStreamsNotFull( const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onSettingsOutgoingStreamsNotFull(session); } if (state_ != ListState::DETACHED && state_ == ListState::FULL) { unlink(); link(); } } void SessionHolder::onFlowControlWindowClosed(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onFlowControlWindowClosed(session); } } void SessionHolder::onEgressBuffered(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onEgressBuffered(session); } } void SessionHolder::onEgressBufferCleared(const HTTPSessionBase& session) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onEgressBufferCleared(session); } } void SessionHolder::onSettings(const HTTPSessionBase& sess, const SettingsList& settings) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onSettings(sess, settings); } } void SessionHolder::onSettingsAck(const HTTPSessionBase& sess) { if (originalSessionInfoCb_) { originalSessionInfoCb_->onSettingsAck(sess); } } void SessionHolder::describe(std::ostream& os) const { const AsyncSocket* sock = session_->getTransport()->getUnderlyingTransport<AsyncSocket>(); if (sock) { os << "fd=" << sock->getNetworkSocket().toFd(); SocketAddress localAddr, serverAddr; try { sock->getLocalAddress(&localAddr); sock->getPeerAddress(&serverAddr); } catch (...) { // The socket might have been disconnected. } if (localAddr.isInitialized()) { os << ",lp=" << localAddr.getPort(); } else { os << ",lp=-1"; } if (serverAddr.isInitialized()) { os << "," << serverAddr; } else { os << ",-"; } } else { os << "fd=-1,lp=-1,-"; } os << ",listState=" << uint32_t(state_); } void SessionHolder::handleTransactionDetached() { CHECK(state_ != ListState::DETACHED); unlink(); link(); } } // namespace proxygen
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
87319c25035143223e3966965dfbc9492b540b49
249d978a0ee6bc5cafd69fbef31a829641be94a6
/basic c++ programs/TIME.CPP
a8155bfc1d4933d021b6ef84d458074fd84b0ff1
[]
no_license
jharinkesh/cplusplus
4d230840e6b61441a911625607e2649f23ab2b27
d5a7d5d4849fa59f8b9f5930294c9285148ef147
refs/heads/master
2020-06-29T08:04:51.797304
2019-08-04T17:12:28
2019-08-04T17:12:28
200,480,948
0
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
#include<iostream.h> #include<stdio.h> #include<time.h> #include<conio.h> void main() { clrscr(); time_t t; time(&t); //printf("Today's date and time: %s\n", ctime(&t)); cout<<(ctime(&t)); // time_t timer; //struct tm *tblock; /* gets time of day */ //timer = time(NULL); /* converts date/time to a structure */ //tblock = localtime(&timer); //printf("Local time is: %s", asctime(tblock)); // t = time(NULL); // printf("The number of seconds since January 1, 1970 is %ld",t); // cout<<t; getch(); }
[ "rinkeshjha7@gmail.com" ]
rinkeshjha7@gmail.com
6ba1bf3b0844492ec38aa2360373e404c0fdb577
671108efbc06a6876ddf3d49622ec2af9d2d82cf
/src/salsa/SalsaCallback.cpp
d7126a5788ec26eb65a6d1a8111add1d9c9cb101
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chrispbradley/scalasca
d545e2ef7c5b22963b8a554ecb5c8ba63f648f66
0f2cfe259ca452cd7e4c0968cfcd9ee3ade9c769
refs/heads/master
2022-02-07T07:51:09.725785
2022-02-04T03:54:56
2022-02-04T03:54:56
68,554,738
0
0
null
2016-09-19T00:16:28
2016-09-19T00:16:27
null
UTF-8
C++
false
false
5,500
cpp
/**************************************************************************** ** SCALASCA http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2014 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #include <config.h> #include "SalsaCallback.h" #include <algorithm> #include <pearl/Event.h> #include <pearl/Region.h> using namespace pearl; SalsaCallback::SalsaCallback(int r, int s, funcs f, modes m, MessageChecker mc) : result(s, 0), counter(s, 0), mc(mc) { rank = r; size = s; func = f; mode = m; } SalsaCallback::~SalsaCallback() { } void SalsaCallback::send(const CallbackManager& cbmanager, int user_event, const Event& event, CallbackData* data) { // Generate Message object MpiMessage* msg = new MpiMessage(*(event->getComm()), 512); // Register send event msg->put_event(event); // Send message msg->isend(event->getDestination(), event->getTag()); // Store Message object in vector m_pending.push_back(msg); m_requests.push_back(msg->get_request()); // Check for completion of previous messages completion_check(); } void SalsaCallback::recv(const CallbackManager& cbmanager, int user_event, const Event& event, CallbackData* data) { CallbackDataneu* dneu = static_cast< CallbackDataneu* >(data); double tmp_val = 0.0; MpiMessage msg(*(event->getComm()), 512); msg.recv(event->getSource(), event->getTag()); RemoteEvent send_event = msg.get_event(*(dneu->defs)); if (!mc.is_applicable(send_event)) { return; } uint64_t sent = send_event->getBytesSent(); timestamp_t send_time = send_event->getTimestamp(); timestamp_t recv_time = event->getTimestamp(); timestamp_t diff = recv_time - send_time; int id = send_event.get_location().getRank(); switch (func) { case COUNT: result[id]++; break; case LENGTH: tmp_val = sent; break; case DURATION: tmp_val = diff; break; case RATE: tmp_val = sent / diff; break; default: tmp_val = 0.0; break; } if (func != COUNT) { switch (mode) { case MINIMUM: if ( (result[id] == 0) || (tmp_val < result[id])) { result[id] = tmp_val; } break; case MAXIMUM: if ( (result[id] == 0) || (tmp_val > result[id])) { result[id] = tmp_val; } break; case AVERAGE: result[id] += tmp_val; counter[id]++; break; case SUM: result[id] += tmp_val; break; } } // Check for completion of previous messages completion_check(); } void SalsaCallback::enter(const CallbackManager& cbmanager, int user_event, const Event& event, CallbackData* data) { // Check whether entering MPI_Finalize if (is_mpi_finalize(event->getRegion())) { completion_check(); } } double* SalsaCallback::get_results() { if (mode == AVERAGE) { for (int i = 0; i < size; i++) { if (counter[i] != 0) { result[i] /= counter[i]; } } } return &result.front(); } void SalsaCallback::completion_check() { // No pending requests? ==> continue if (m_pending.empty()) { return; } // Check for completed messages int completed; int count = m_pending.size(); m_indices.resize(count); m_statuses.resize(count); MPI_Testsome(count, &m_requests[0], &completed, &m_indices[0], &m_statuses[0]); // Update array of pending messages for (int i = 0; i < completed; ++i) { int index = m_indices[i]; delete m_pending[index]; m_pending[index] = NULL; } m_pending.erase(std::remove(m_pending.begin(), m_pending.end(), static_cast< MpiMessage* >(NULL)), m_pending.end()); m_requests.erase(std::remove(m_requests.begin(), m_requests.end(), static_cast< MPI_Request >(MPI_REQUEST_NULL)), m_requests.end()); }
[ "c.bradley@auckland.ac.nz" ]
c.bradley@auckland.ac.nz
18f245e594a84c29c8036c80d24b7f34399d5380
95edf9e7bc17ed081d75bdd135c3adc4c3506bd0
/first_term/lab4.cpp
c8eacff297312f891107801435dbc35a7f628e43
[]
no_license
t-weathers/introductory_computer_science
3097e59379b2f99d3b379da5e473e79a0411564f
7ee09a6136f893b65d61a8f20a70bcb26380fe3c
refs/heads/master
2020-04-25T08:51:26.725647
2019-02-26T19:18:30
2019-02-26T19:18:30
172,660,062
0
0
null
null
null
null
UTF-8
C++
false
false
797
cpp
#include <iostream> using namespace std; /********************************************************************* ** Function: a_to_i ** Description: turns a character into a decimal value ** Parameters: char character ** Pre-Conditions: the input is a character ** Post-Conditions: returned the decimal value of the character *********************************************************************/ int atoi(char character){ int output = (int)(character); return output; } char itoa(int integer){ char output = (char)(integer); return output; } int main(){ char char1; int int1; cout <<"(atoi) give a char: "; cin >> char1; cout <<atoi(char1)<< endl; cout <<"(itoa) give a decimal value: "; cin >> int1; cout << itoa(int1) << endl; return 0; }
[ "noreply@github.com" ]
t-weathers.noreply@github.com
8ae06c01c03edf840435b4e3a7dd8550e0dc499c
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/test/magma-1.3.0/testing/testing_cpotrf_gpu.cpp
3c4a9f5dfab445fde4a624548d39eca5fd33deca
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,269
cpp
/* * -- MAGMA (version 1.3.0) -- * Univ. of Tennessee, Knoxville * Univ. of California, Berkeley * Univ. of Colorado, Denver * November 2012 * * @generated c Wed Nov 14 22:54:13 2012 * **/ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cuda_runtime_api.h> #include <cublas.h> // includes, project #include "flops.h" #include "magma.h" #include "magma_lapack.h" #include "testings.h" /* //////////////////////////////////////////////////////////////////////////// -- Testing cpotrf */ int main( int argc, char** argv) { TESTING_CUDA_INIT(); real_Double_t gflops, gpu_perf, gpu_time, cpu_perf, cpu_time; cuFloatComplex *h_A, *h_R; cuFloatComplex *d_A; /* Matrix size */ magma_int_t N = 0, n2, lda, ldda; const int MAXTESTS = 10; magma_int_t size[MAXTESTS] = { 1024, 2048, 3072, 4032, 5184, 6016, 7040, 8064, 9088, 10112 }; magma_int_t i, info; const char *uplo = MagmaLowerStr; cuFloatComplex c_neg_one = MAGMA_C_NEG_ONE; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; float work[1], error; magma_int_t checkres; checkres = getenv("MAGMA_TESTINGS_CHECK") != NULL; // process command line arguments printf( "\nUsage: %s -N <n> [-L|-U] -c\n", argv[0] ); printf( " -N can be repeated up to %d times.\n", MAXTESTS ); printf( " -c or setting $MAGMA_TESTINGS_CHECK runs LAPACK and checks result.\n\n" ); int ntest = 0; for( int i = 1; i < argc; ++i ) { if ( strcmp("-N", argv[i]) == 0 && i+1 < argc ) { magma_assert( ntest < MAXTESTS, "error: -N repeated more than maximum %d tests\n", MAXTESTS ); size[ ntest ] = atoi( argv[++i] ); magma_assert( size[ ntest ] > 0, "error: -N %s is invalid; must be > 0.\n", argv[i] ); N = max( N, size[ ntest ] ); ntest++; } else if ( strcmp("-L", argv[i]) == 0 ) { uplo = MagmaLowerStr; } else if ( strcmp("-U", argv[i]) == 0 ) { uplo = MagmaUpperStr; } else if ( strcmp("-c", argv[i]) == 0 ) { checkres = true; } else { printf( "invalid argument: %s\n", argv[i] ); exit(1); } } if ( ntest == 0 ) { ntest = MAXTESTS; N = size[ntest-1]; } /* Allocate memory for the matrix */ n2 = N*N; ldda = ((N+31)/32) * 32; TESTING_MALLOC( h_A, cuFloatComplex, n2); TESTING_HOSTALLOC( h_R, cuFloatComplex, n2); TESTING_DEVALLOC( d_A, cuFloatComplex, ldda*N ); printf(" N CPU GFlop/s (sec) GPU GFlop/s (sec) ||R_magma - R_lapack||_F / ||R_lapack||_F\n"); printf("========================================================\n"); for( i = 0; i < ntest; ++i ) { N = size[i]; lda = N; n2 = lda*N; ldda = ((N+31)/32)*32; gflops = FLOPS_CPOTRF( N ) / 1e9; /* Initialize the matrix */ lapackf77_clarnv( &ione, ISEED, &n2, h_A ); magma_chpd( N, h_A, lda ); lapackf77_clacpy( MagmaUpperLowerStr, &N, &N, h_A, &lda, h_R, &lda ); magma_csetmatrix( N, N, h_A, lda, d_A, ldda ); /* ==================================================================== Performs operation using MAGMA =================================================================== */ gpu_time = magma_wtime(); magma_cpotrf_gpu(uplo[0], N, d_A, ldda, &info); gpu_time = magma_wtime() - gpu_time; gpu_perf = gflops / gpu_time; if (info != 0) printf("magma_cpotrf_gpu returned error %d.\n", (int) info); if ( checkres ) { /* ===================================================================== Performs operation using LAPACK =================================================================== */ cpu_time = magma_wtime(); lapackf77_cpotrf(uplo, &N, h_A, &lda, &info); cpu_time = magma_wtime() - cpu_time; cpu_perf = gflops / cpu_time; if (info != 0) printf("lapackf77_cpotrf returned error %d.\n", (int) info); /* ===================================================================== Check the result compared to LAPACK =================================================================== */ magma_cgetmatrix( N, N, d_A, ldda, h_R, lda ); error = lapackf77_clange("f", &N, &N, h_A, &lda, work); blasf77_caxpy(&n2, &c_neg_one, h_A, &ione, h_R, &ione); error = lapackf77_clange("f", &N, &N, h_R, &lda, work) / error; printf("%5d %7.2f (%7.2f) %7.2f (%7.2f) %8.2e\n", (int) N, cpu_perf, cpu_time, gpu_perf, gpu_time, error ); } else { printf("%5d --- ( --- ) %7.2f (%7.2f) --- \n", (int) N, gpu_perf, gpu_time ); } } /* Memory clean up */ TESTING_FREE( h_A ); TESTING_HOSTFREE( h_R ); TESTING_DEVFREE( d_A ); TESTING_CUDA_FINALIZE(); return 0; }
[ "cjy7117@gmail.com" ]
cjy7117@gmail.com
5aa4710c55a7dab9c236a4e3068d2d76e890d145
61b8989672f152c45882719ed57dc62abfffed6e
/examples/Cassie/cassie_rbt_state_estimator.h
bcf8b992595aa05049643714b574287a8a9161ff
[ "BSD-3-Clause" ]
permissive
mposa/dairlib-1
ede175189c1b08aceaf19d3af77064d38c6aeb76
ff537de4e4e3b35f9abecf675f9a55e71ef35a7f
refs/heads/master
2020-04-27T23:31:47.922918
2019-03-22T19:30:37
2019-03-22T19:30:37
174,779,442
0
0
NOASSERTION
2019-03-27T20:21:02
2019-03-10T04:54:23
C++
UTF-8
C++
false
false
994
h
#pragma once #include <string> #include <map> #include <vector> #include "drake/systems/framework/leaf_system.h" #include "attic/multibody/rigidbody_utils.h" #include "systems/framework/output_vector.h" #include "systems/framework/timestamped_vector.h" #include "examples/Cassie/datatypes/cassie_out_t.h" namespace dairlib { namespace systems { /// Translates from a TimestamedVector of cassie torque commands into /// a cassie_user_in_t struct for transmission to the real robot. class CassieRbtStateEstimator : public drake::systems::LeafSystem<double> { public: explicit CassieRbtStateEstimator( const RigidBodyTree<double>&); private: void Output(const drake::systems::Context<double>& context, OutputVector<double>* output) const; const RigidBodyTree<double>& tree_; std::map<std::string, int> positionIndexMap_; std::map<std::string, int> velocityIndexMap_; std::map<std::string, int> actuatorIndexMap_; }; } // namespace systems } // namespace dairlib
[ "noreply@github.com" ]
mposa.noreply@github.com
24455d1ed2b942acb4bb4fe25f7791299eb55d60
2fa8a154212ed4d4cd1bf5807d6b198f929f186e
/client/decide.h
e08e8a8ef0a40a426d6e3098802e332dc4ddad2c
[]
no_license
razeghi71/planet
d58c00b3f1ca201dd9f47021c230c81c97d613d8
2a8bda0cb4ad855c182830630e5fc8960087b149
refs/heads/master
2020-04-27T17:56:37.492350
2013-11-30T13:04:35
2013-11-30T13:04:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
331
h
#ifndef DECIDE_H #define DECIDE_H #include "world.h" #include "agent.h" #include "planet.h" class Decide { public: Decide(World &_w); std::string decide(); std::string RageBot(); std::string RandomBot(); std::string ProspectorBot(); // std::string DualBot(); private: World &w; }; #endif // DECIDE_H
[ "razeghi71@gmail.com" ]
razeghi71@gmail.com
86d38d3f11a537922ffd0ad436e9ac7b6ab3286a
76e5b15b72380c82913bee721dfc75599d2040b2
/src/math/simplex/model_based_opt.cpp
8b8f82a315739cce2412211a902a25441f428e71
[ "MIT" ]
permissive
wintersteiger/z3
8397716b90be4c0ab3e2eeaf0ae558249fa8d57d
a3161bdc155f66a619ae740887cb267e57dd0e97
refs/heads/master
2023-02-06T04:26:19.993361
2022-08-03T16:40:01
2022-08-04T04:54:42
32,945,653
1
0
NOASSERTION
2023-01-30T21:06:33
2015-03-26T18:45:29
C++
UTF-8
C++
false
false
43,912
cpp
/*++ Copyright (c) 2016 Microsoft Corporation Module Name: model_based_opt.cpp Abstract: Model-based optimization and projection for linear real, integer arithmetic. Author: Nikolaj Bjorner (nbjorner) 2016-27-4 Revision History: --*/ #include "math/simplex/model_based_opt.h" #include "util/uint_set.h" #include "util/z3_exception.h" std::ostream& operator<<(std::ostream& out, opt::ineq_type ie) { switch (ie) { case opt::t_eq: return out << " = "; case opt::t_lt: return out << " < "; case opt::t_le: return out << " <= "; case opt::t_mod: return out << " mod "; } return out; } namespace opt { /** * Convert a row ax + coeffs + coeff = value into a definition for x * x = (value - coeffs - coeff)/a * as backdrop we have existing assignments to x and other variables that * satisfy the equality with value, and such that value satisfies * the row constraint ( = , <= , < , mod) */ model_based_opt::def::def(row const& r, unsigned x) { for (var const & v : r.m_vars) { if (v.m_id != x) { m_vars.push_back(v); } else { m_div = -v.m_coeff; } } m_coeff = r.m_coeff; switch (r.m_type) { case opt::t_lt: m_coeff += m_div; break; case opt::t_le: // for: ax >= t, then x := (t + a - 1) div a if (m_div.is_pos()) { m_coeff += m_div; m_coeff -= rational::one(); } break; default: break; } normalize(); SASSERT(m_div.is_pos()); } model_based_opt::def model_based_opt::def::operator+(def const& other) const { def result; vector<var> const& vs1 = m_vars; vector<var> const& vs2 = other.m_vars; vector<var> & vs = result.m_vars; rational c1(1), c2(1); if (m_div != other.m_div) { c1 = other.m_div; c2 = m_div; } unsigned i = 0, j = 0; while (i < vs1.size() || j < vs2.size()) { unsigned v1 = UINT_MAX, v2 = UINT_MAX; if (i < vs1.size()) v1 = vs1[i].m_id; if (j < vs2.size()) v2 = vs2[j].m_id; if (v1 == v2) { vs.push_back(vs1[i]); vs.back().m_coeff *= c1; vs.back().m_coeff += c2 * vs2[j].m_coeff; ++i; ++j; if (vs.back().m_coeff.is_zero()) { vs.pop_back(); } } else if (v1 < v2) { vs.push_back(vs1[i]); vs.back().m_coeff *= c1; } else { vs.push_back(vs2[j]); vs.back().m_coeff *= c2; } } result.m_div = c1*m_div; result.m_coeff = (m_coeff*c1) + (other.m_coeff*c2); result.normalize(); return result; } model_based_opt::def model_based_opt::def::operator/(rational const& r) const { def result(*this); result.m_div *= r; result.normalize(); return result; } model_based_opt::def model_based_opt::def::operator*(rational const& n) const { def result(*this); for (var& v : result.m_vars) { v.m_coeff *= n; } result.m_coeff *= n; result.normalize(); return result; } model_based_opt::def model_based_opt::def::operator+(rational const& n) const { def result(*this); result.m_coeff += n * result.m_div; result.normalize(); return result; } void model_based_opt::def::normalize() { if (!m_div.is_int()) { rational den = denominator(m_div); SASSERT(den > 1); for (var& v : m_vars) v.m_coeff *= den; m_coeff *= den; m_div *= den; } if (m_div.is_neg()) { for (var& v : m_vars) v.m_coeff.neg(); m_coeff.neg(); m_div.neg(); } if (m_div.is_one()) return; rational g(m_div); if (!m_coeff.is_int()) return; g = gcd(g, m_coeff); for (var const& v : m_vars) { if (!v.m_coeff.is_int()) return; g = gcd(g, abs(v.m_coeff)); if (g.is_one()) break; } if (!g.is_one()) { for (var& v : m_vars) v.m_coeff /= g; m_coeff /= g; m_div /= g; } } model_based_opt::model_based_opt() { m_rows.push_back(row()); } bool model_based_opt::invariant() { for (unsigned i = 0; i < m_rows.size(); ++i) { if (!invariant(i, m_rows[i])) { return false; } } return true; } #define PASSERT(_e_) { CTRACE("qe", !(_e_), display(tout, r); display(tout);); SASSERT(_e_); } bool model_based_opt::invariant(unsigned index, row const& r) { vector<var> const& vars = r.m_vars; for (unsigned i = 0; i < vars.size(); ++i) { // variables in each row are sorted and have non-zero coefficients PASSERT(i + 1 == vars.size() || vars[i].m_id < vars[i+1].m_id); PASSERT(!vars[i].m_coeff.is_zero()); PASSERT(index == 0 || m_var2row_ids[vars[i].m_id].contains(index)); } PASSERT(r.m_value == eval(r)); PASSERT(r.m_type != t_eq || r.m_value.is_zero()); // values satisfy constraints PASSERT(index == 0 || r.m_type != t_lt || r.m_value.is_neg()); PASSERT(index == 0 || r.m_type != t_le || !r.m_value.is_pos()); PASSERT(index == 0 || r.m_type != t_mod || (mod(r.m_value, r.m_mod).is_zero())); return true; } // a1*x + obj // a2*x + t2 <= 0 // a3*x + t3 <= 0 // a4*x + t4 <= 0 // a1 > 0, a2 > 0, a3 > 0, a4 < 0 // x <= -t2/a2 // x <= -t2/a3 // determine lub among these. // then resolve lub with others // e.g., -t2/a2 <= -t3/a3, then // replace inequality a3*x + t3 <= 0 by -t2/a2 + t3/a3 <= 0 // mark a4 as invalid. // // a1 < 0, a2 < 0, a3 < 0, a4 > 0 // x >= t2/a2 // x >= t3/a3 // determine glb among these // the resolve glb with others. // e.g. t2/a2 >= t3/a3 // then replace a3*x + t3 by t3/a3 - t2/a2 <= 0 // inf_eps model_based_opt::maximize() { SASSERT(invariant()); unsigned_vector bound_trail, bound_vars; TRACE("opt", display(tout << "tableau\n");); while (!objective().m_vars.empty()) { var v = objective().m_vars.back(); unsigned x = v.m_id; rational const& coeff = v.m_coeff; unsigned bound_row_index; rational bound_coeff; if (find_bound(x, bound_row_index, bound_coeff, coeff.is_pos())) { SASSERT(!bound_coeff.is_zero()); TRACE("opt", display(tout << "update: " << v << " ", objective()); for (unsigned above : m_above) { display(tout << "resolve: ", m_rows[above]); }); for (unsigned above : m_above) { resolve(bound_row_index, bound_coeff, above, x); } for (unsigned below : m_below) { resolve(bound_row_index, bound_coeff, below, x); } // coeff*x + objective <= ub // a2*x + t2 <= 0 // => coeff*x <= -t2*coeff/a2 // objective + t2*coeff/a2 <= ub mul_add(false, m_objective_id, - coeff/bound_coeff, bound_row_index); retire_row(bound_row_index); bound_trail.push_back(bound_row_index); bound_vars.push_back(x); } else { TRACE("opt", display(tout << "unbound: " << v << " ", objective());); update_values(bound_vars, bound_trail); return inf_eps::infinity(); } } // // update the evaluation of variables to satisfy the bound. // update_values(bound_vars, bound_trail); rational value = objective().m_value; if (objective().m_type == t_lt) { return inf_eps(inf_rational(value, rational(-1))); } else { return inf_eps(inf_rational(value)); } } void model_based_opt::update_value(unsigned x, rational const& val) { rational old_val = m_var2value[x]; m_var2value[x] = val; SASSERT(val.is_int() || !is_int(x)); unsigned_vector const& row_ids = m_var2row_ids[x]; for (unsigned row_id : row_ids) { rational coeff = get_coefficient(row_id, x); if (coeff.is_zero()) { continue; } row & r = m_rows[row_id]; rational delta = coeff * (val - old_val); r.m_value += delta; SASSERT(invariant(row_id, r)); } } void model_based_opt::update_values(unsigned_vector const& bound_vars, unsigned_vector const& bound_trail) { for (unsigned i = bound_trail.size(); i-- > 0; ) { unsigned x = bound_vars[i]; row& r = m_rows[bound_trail[i]]; rational val = r.m_coeff; rational old_x_val = m_var2value[x]; rational new_x_val; rational x_coeff, eps(0); vector<var> const& vars = r.m_vars; for (var const& v : vars) { if (x == v.m_id) { x_coeff = v.m_coeff; } else { val += m_var2value[v.m_id]*v.m_coeff; } } SASSERT(!x_coeff.is_zero()); new_x_val = -val/x_coeff; if (r.m_type == t_lt) { eps = abs(old_x_val - new_x_val)/rational(2); eps = std::min(rational::one(), eps); SASSERT(!eps.is_zero()); // // ax + t < 0 // <=> x < -t/a // <=> x := -t/a - epsilon // if (x_coeff.is_pos()) { new_x_val -= eps; } // // -ax + t < 0 // <=> -ax < -t // <=> -x < -t/a // <=> x > t/a // <=> x := t/a + epsilon // else { new_x_val += eps; } } TRACE("opt", display(tout << "v" << x << " coeff_x: " << x_coeff << " old_x_val: " << old_x_val << " new_x_val: " << new_x_val << " eps: " << eps << " ", r); ); m_var2value[x] = new_x_val; r.m_value = eval(r); SASSERT(invariant(bound_trail[i], r)); } // update and check bounds for all other affected rows. for (unsigned i = bound_trail.size(); i-- > 0; ) { unsigned x = bound_vars[i]; unsigned_vector const& row_ids = m_var2row_ids[x]; for (unsigned row_id : row_ids) { row & r = m_rows[row_id]; r.m_value = eval(r); SASSERT(invariant(row_id, r)); } } SASSERT(invariant()); } bool model_based_opt::find_bound(unsigned x, unsigned& bound_row_index, rational& bound_coeff, bool is_pos) { bound_row_index = UINT_MAX; rational lub_val; rational const& x_val = m_var2value[x]; unsigned_vector const& row_ids = m_var2row_ids[x]; uint_set visited; m_above.reset(); m_below.reset(); for (unsigned row_id : row_ids) { SASSERT(row_id != m_objective_id); if (visited.contains(row_id)) { continue; } visited.insert(row_id); row& r = m_rows[row_id]; if (r.m_alive) { rational a = get_coefficient(row_id, x); if (a.is_zero()) { // skip } else if (a.is_pos() == is_pos || r.m_type == t_eq) { rational value = x_val - (r.m_value/a); if (bound_row_index == UINT_MAX) { lub_val = value; bound_row_index = row_id; bound_coeff = a; } else if ((value == lub_val && r.m_type == opt::t_lt) || (is_pos && value < lub_val) || (!is_pos && value > lub_val)) { m_above.push_back(bound_row_index); lub_val = value; bound_row_index = row_id; bound_coeff = a; } else { m_above.push_back(row_id); } } else { m_below.push_back(row_id); } } } return bound_row_index != UINT_MAX; } void model_based_opt::retire_row(unsigned row_id) { m_rows[row_id].m_alive = false; m_retired_rows.push_back(row_id); } rational model_based_opt::eval(unsigned x) const { return m_var2value[x]; } rational model_based_opt::eval(def const& d) const { vector<var> const& vars = d.m_vars; rational val = d.m_coeff; for (var const& v : vars) { val += v.m_coeff * eval(v.m_id); } val /= d.m_div; return val; } rational model_based_opt::eval(row const& r) const { vector<var> const& vars = r.m_vars; rational val = r.m_coeff; for (var const& v : vars) { val += v.m_coeff * eval(v.m_id); } return val; } rational model_based_opt::eval(vector<var> const& coeffs) const { rational val(0); for (var const& v : coeffs) val += v.m_coeff * eval(v.m_id); return val; } rational model_based_opt::get_coefficient(unsigned row_id, unsigned var_id) const { return m_rows[row_id].get_coefficient(var_id); } rational model_based_opt::row::get_coefficient(unsigned var_id) const { if (m_vars.empty()) { return rational::zero(); } unsigned lo = 0, hi = m_vars.size(); while (lo < hi) { unsigned mid = lo + (hi - lo)/2; SASSERT(mid < hi); unsigned id = m_vars[mid].m_id; if (id == var_id) { lo = mid; break; } if (id < var_id) { lo = mid + 1; } else { hi = mid; } } if (lo == m_vars.size()) { return rational::zero(); } unsigned id = m_vars[lo].m_id; if (id == var_id) { return m_vars[lo].m_coeff; } else { return rational::zero(); } } model_based_opt::row& model_based_opt::row::normalize() { #if 0 if (m_type == t_mod) return *this; rational D(denominator(abs(m_coeff))); if (D == 0) D = 1; for (auto const& [id, coeff] : m_vars) if (coeff != 0) D = lcm(D, denominator(abs(coeff))); if (D == 1) return *this; SASSERT(D > 0); for (auto & [id, coeff] : m_vars) coeff *= D; m_coeff *= D; #endif return *this; } // // Let // row1: t1 + a1*x <= 0 // row2: t2 + a2*x <= 0 // // assume a1, a2 have the same signs: // (t2 + a2*x) <= (t1 + a1*x)*a2/a1 // <=> t2*a1/a2 - t1 <= 0 // <=> t2 - t1*a2/a1 <= 0 // // assume a1 > 0, -a2 < 0: // t1 + a1*x <= 0, t2 - a2*x <= 0 // t2/a2 <= -t1/a1 // t2 + t1*a2/a1 <= 0 // assume -a1 < 0, a2 > 0: // t1 - a1*x <= 0, t2 + a2*x <= 0 // t1/a1 <= -t2/a2 // t2 + t1*a2/a1 <= 0 // // the resolvent is the same in all cases (simpler proof should exist) // void model_based_opt::resolve(unsigned row_src, rational const& a1, unsigned row_dst, unsigned x) { SASSERT(a1 == get_coefficient(row_src, x)); SASSERT(!a1.is_zero()); SASSERT(row_src != row_dst); if (m_rows[row_dst].m_alive) { rational a2 = get_coefficient(row_dst, x); if (is_int(x)) { TRACE("opt", tout << a1 << " " << a2 << ": "; display(tout, m_rows[row_dst]); display(tout, m_rows[row_src]);); if (a1.is_pos() != a2.is_pos() || m_rows[row_src].m_type == opt::t_eq) { mul_add(x, a1, row_src, a2, row_dst); } else { mul(row_dst, abs(a1)); mul_add(false, row_dst, -abs(a2), row_src); } TRACE("opt", display(tout, m_rows[row_dst]);); normalize(row_dst); } else { mul_add(row_dst != m_objective_id && a1.is_pos() == a2.is_pos(), row_dst, -a2/a1, row_src); } } } /** * a1 > 0 * a1*x + r1 = value * a2*x + r2 <= 0 * ------------------ * a1*r2 - a2*r1 <= value */ void model_based_opt::solve(unsigned row_src, rational const& a1, unsigned row_dst, unsigned x) { SASSERT(a1 == get_coefficient(row_src, x)); SASSERT(a1.is_pos()); SASSERT(row_src != row_dst); if (!m_rows[row_dst].m_alive) return; rational a2 = get_coefficient(row_dst, x); mul(row_dst, a1); mul_add(false, row_dst, -a2, row_src); SASSERT(get_coefficient(row_dst, x).is_zero()); } // resolution for integer rows. void model_based_opt::mul_add( unsigned x, rational const& src_c, unsigned row_src, rational const& dst_c, unsigned row_dst) { row& dst = m_rows[row_dst]; row const& src = m_rows[row_src]; SASSERT(is_int(x)); SASSERT(t_le == dst.m_type && t_le == src.m_type); SASSERT(src_c.is_int()); SASSERT(dst_c.is_int()); SASSERT(m_var2value[x].is_int()); rational abs_src_c = abs(src_c); rational abs_dst_c = abs(dst_c); rational x_val = m_var2value[x]; rational slack = (abs_src_c - rational::one()) * (abs_dst_c - rational::one()); rational dst_val = dst.m_value - x_val*dst_c; rational src_val = src.m_value - x_val*src_c; rational distance = abs_src_c * dst_val + abs_dst_c * src_val + slack; bool use_case1 = distance.is_nonpos() || abs_src_c.is_one() || abs_dst_c.is_one(); #if 0 if (distance.is_nonpos() && !abs_src_c.is_one() && !abs_dst_c.is_one()) { unsigned r = copy_row(row_src); mul_add(false, r, rational::one(), row_dst); del_var(r, x); add(r, slack); TRACE("qe", tout << m_rows[r];); SASSERT(!m_rows[r].m_value.is_pos()); } #endif if (use_case1) { TRACE("opt", tout << "slack: " << slack << " " << src_c << " " << dst_val << " " << dst_c << " " << src_val << "\n";); // dst <- abs_src_c*dst + abs_dst_c*src + slack mul(row_dst, abs_src_c); add(row_dst, slack); mul_add(false, row_dst, abs_dst_c, row_src); return; } // // create finite disjunction for |b|. // exists x, z in [0 .. |b|-2] . b*x + s + z = 0 && ax + t <= 0 && bx + s <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && ax + t <= 0 && bx + s <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && a|b|x + |b|t <= 0 && bx + s <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && a|b|x + |b|t <= 0 && -z - s + s <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && a|b|x + |b|t <= 0 && -z <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && a|b|x + |b|t <= 0 // <=> // exists x, z in [0 .. |b|-2] . b*x = -z - s && a*n_sign(b)(s + z) + |b|t <= 0 // <=> // exists z in [0 .. |b|-2] . |b| | (z + s) && a*n_sign(b)(s + z) + |b|t <= 0 // TRACE("qe", tout << "finite disjunction " << distance << " " << src_c << " " << dst_c << "\n";); vector<var> coeffs; if (abs_dst_c <= abs_src_c) { rational z = mod(dst_val, abs_dst_c); if (!z.is_zero()) z = abs_dst_c - z; mk_coeffs_without(coeffs, dst.m_vars, x); add_divides(coeffs, dst.m_coeff + z, abs_dst_c); add(row_dst, z); mul(row_dst, src_c * n_sign(dst_c)); mul_add(false, row_dst, abs_dst_c, row_src); } else { // z := b - (s + bx) mod b // := b - s mod b // b | s + z <=> b | s + b - s mod b <=> b | s - s mod b rational z = mod(src_val, abs_src_c); if (!z.is_zero()) z = abs_src_c - z; mk_coeffs_without(coeffs, src.m_vars, x); add_divides(coeffs, src.m_coeff + z, abs_src_c); mul(row_dst, abs_src_c); add(row_dst, z * dst_c * n_sign(src_c)); mul_add(false, row_dst, dst_c * n_sign(src_c), row_src); } } void model_based_opt::mk_coeffs_without(vector<var>& dst, vector<var> const& src, unsigned x) { for (var const & v : src) { if (v.m_id != x) dst.push_back(v); } } rational model_based_opt::n_sign(rational const& b) const { return rational(b.is_pos()?-1:1); } void model_based_opt::mul(unsigned dst, rational const& c) { if (c.is_one()) return; row& r = m_rows[dst]; for (auto & v : r.m_vars) { v.m_coeff *= c; } r.m_coeff *= c; r.m_value *= c; } void model_based_opt::add(unsigned dst, rational const& c) { row& r = m_rows[dst]; r.m_coeff += c; r.m_value += c; } void model_based_opt::sub(unsigned dst, rational const& c) { row& r = m_rows[dst]; r.m_coeff -= c; r.m_value -= c; } void model_based_opt::del_var(unsigned dst, unsigned x) { row& r = m_rows[dst]; unsigned j = 0; for (var & v : r.m_vars) { if (v.m_id == x) { r.m_value -= eval(x)*r.m_coeff; } else { r.m_vars[j++] = v; } } r.m_vars.shrink(j); } void model_based_opt::normalize(unsigned row_id) { row& r = m_rows[row_id]; if (r.m_vars.empty()) { retire_row(row_id); return; } if (r.m_type == t_mod) return; rational g(abs(r.m_vars[0].m_coeff)); bool all_int = g.is_int(); for (unsigned i = 1; all_int && !g.is_one() && i < r.m_vars.size(); ++i) { rational const& coeff = r.m_vars[i].m_coeff; if (coeff.is_int()) { g = gcd(g, abs(coeff)); } else { all_int = false; } } if (all_int && !r.m_coeff.is_zero()) { if (r.m_coeff.is_int()) { g = gcd(g, abs(r.m_coeff)); } else { all_int = false; } } if (all_int && !g.is_one()) { SASSERT(!g.is_zero()); mul(row_id, rational::one()/g); } } // // set row1 <- row1 + c*row2 // void model_based_opt::mul_add(bool same_sign, unsigned row_id1, rational const& c, unsigned row_id2) { if (c.is_zero()) { return; } m_new_vars.reset(); row& r1 = m_rows[row_id1]; row const& r2 = m_rows[row_id2]; unsigned i = 0, j = 0; while (i < r1.m_vars.size() || j < r2.m_vars.size()) { if (j == r2.m_vars.size()) { m_new_vars.append(r1.m_vars.size() - i, r1.m_vars.data() + i); break; } if (i == r1.m_vars.size()) { for (; j < r2.m_vars.size(); ++j) { m_new_vars.push_back(r2.m_vars[j]); m_new_vars.back().m_coeff *= c; if (row_id1 != m_objective_id) { m_var2row_ids[r2.m_vars[j].m_id].push_back(row_id1); } } break; } unsigned v1 = r1.m_vars[i].m_id; unsigned v2 = r2.m_vars[j].m_id; if (v1 == v2) { m_new_vars.push_back(r1.m_vars[i]); m_new_vars.back().m_coeff += c*r2.m_vars[j].m_coeff; ++i; ++j; if (m_new_vars.back().m_coeff.is_zero()) { m_new_vars.pop_back(); } } else if (v1 < v2) { m_new_vars.push_back(r1.m_vars[i]); ++i; } else { m_new_vars.push_back(r2.m_vars[j]); m_new_vars.back().m_coeff *= c; if (row_id1 != m_objective_id) { m_var2row_ids[r2.m_vars[j].m_id].push_back(row_id1); } ++j; } } r1.m_coeff += c*r2.m_coeff; r1.m_vars.swap(m_new_vars); r1.m_value += c*r2.m_value; if (!same_sign && r2.m_type == t_lt) { r1.m_type = t_lt; } else if (same_sign && r1.m_type == t_lt && r2.m_type == t_lt) { r1.m_type = t_le; } SASSERT(invariant(row_id1, r1)); } void model_based_opt::display(std::ostream& out) const { for (auto const& r : m_rows) { display(out, r); } for (unsigned i = 0; i < m_var2row_ids.size(); ++i) { unsigned_vector const& rows = m_var2row_ids[i]; out << i << ": "; for (auto const& r : rows) { out << r << " "; } out << "\n"; } } void model_based_opt::display(std::ostream& out, vector<var> const& vars, rational const& coeff) { unsigned i = 0; for (var const& v : vars) { if (i > 0 && v.m_coeff.is_pos()) { out << "+ "; } ++i; if (v.m_coeff.is_one()) { out << "v" << v.m_id << " "; } else { out << v.m_coeff << "*v" << v.m_id << " "; } } if (coeff.is_pos()) { out << " + " << coeff << " "; } else if (coeff.is_neg()) { out << coeff << " "; } } std::ostream& model_based_opt::display(std::ostream& out, row const& r) { out << (r.m_alive?"a":"d") << " "; display(out, r.m_vars, r.m_coeff); if (r.m_type == opt::t_mod) { out << r.m_type << " " << r.m_mod << " = 0; value: " << r.m_value << "\n"; } else { out << r.m_type << " 0; value: " << r.m_value << "\n"; } return out; } std::ostream& model_based_opt::display(std::ostream& out, def const& r) { display(out, r.m_vars, r.m_coeff); if (!r.m_div.is_one()) { out << " / " << r.m_div; } return out; } unsigned model_based_opt::add_var(rational const& value, bool is_int) { unsigned v = m_var2value.size(); m_var2value.push_back(value); m_var2is_int.push_back(is_int); SASSERT(value.is_int() || !is_int); m_var2row_ids.push_back(unsigned_vector()); return v; } rational model_based_opt::get_value(unsigned var) { return m_var2value[var]; } void model_based_opt::set_row(unsigned row_id, vector<var> const& coeffs, rational const& c, rational const& m, ineq_type rel) { row& r = m_rows[row_id]; rational val(c); SASSERT(r.m_vars.empty()); r.m_vars.append(coeffs.size(), coeffs.data()); bool is_int_row = !coeffs.empty(); std::sort(r.m_vars.begin(), r.m_vars.end(), var::compare()); for (auto const& c : coeffs) { val += m_var2value[c.m_id] * c.m_coeff; SASSERT(!is_int(c.m_id) || c.m_coeff.is_int()); is_int_row &= is_int(c.m_id); } r.m_alive = true; r.m_coeff = c; r.m_value = val; r.m_type = rel; r.m_mod = m; if (is_int_row && rel == t_lt) { r.m_type = t_le; r.m_coeff += rational::one(); r.m_value += rational::one(); } } unsigned model_based_opt::new_row() { unsigned row_id = 0; if (m_retired_rows.empty()) { row_id = m_rows.size(); m_rows.push_back(row()); } else { row_id = m_retired_rows.back(); m_retired_rows.pop_back(); m_rows[row_id].reset(); m_rows[row_id].m_alive = true; } return row_id; } unsigned model_based_opt::copy_row(unsigned src) { unsigned dst = new_row(); row const& r = m_rows[src]; set_row(dst, r.m_vars, r.m_coeff, r.m_mod, r.m_type); for (auto const& v : r.m_vars) { m_var2row_ids[v.m_id].push_back(dst); } SASSERT(invariant(dst, m_rows[dst])); return dst; } void model_based_opt::add_constraint(vector<var> const& coeffs, rational const& c, ineq_type rel) { add_constraint(coeffs, c, rational::zero(), rel); } void model_based_opt::add_divides(vector<var> const& coeffs, rational const& c, rational const& m) { add_constraint(coeffs, c, m, t_mod); } void model_based_opt::add_constraint(vector<var> const& coeffs, rational const& c, rational const& m, ineq_type rel) { unsigned row_id = new_row(); set_row(row_id, coeffs, c, m, rel); for (var const& coeff : coeffs) { m_var2row_ids[coeff.m_id].push_back(row_id); } SASSERT(invariant(row_id, m_rows[row_id])); } void model_based_opt::set_objective(vector<var> const& coeffs, rational const& c) { set_row(m_objective_id, coeffs, c, rational::zero(), t_le); } void model_based_opt::get_live_rows(vector<row>& rows) { for (row & r : m_rows) { if (r.m_alive) { rows.push_back(r.normalize()); } } } // // pick glb and lub representative. // The representative is picked such that it // represents the fewest inequalities. // The constraints that enforce a glb or lub are not forced. // The constraints that separate the glb from ub or the lub from lb // are not forced. // In other words, suppose there are // . N inequalities of the form t <= x // . M inequalities of the form s >= x // . t0 is glb among N under valuation. // . s0 is lub among M under valuation. // If N < M // create the inequalities: // t <= t0 for each t other than t0 (N-1 inequalities). // t0 <= s for each s (M inequalities). // If N >= M the construction is symmetric. // model_based_opt::def model_based_opt::project(unsigned x, bool compute_def) { unsigned_vector& lub_rows = m_lub; unsigned_vector& glb_rows = m_glb; unsigned_vector& mod_rows = m_mod; unsigned lub_index = UINT_MAX, glb_index = UINT_MAX; bool lub_strict = false, glb_strict = false; rational lub_val, glb_val; rational const& x_val = m_var2value[x]; unsigned_vector const& row_ids = m_var2row_ids[x]; uint_set visited; lub_rows.reset(); glb_rows.reset(); mod_rows.reset(); bool lub_is_unit = false, glb_is_unit = false; unsigned eq_row = UINT_MAX; // select the lub and glb. for (unsigned row_id : row_ids) { if (visited.contains(row_id)) { continue; } visited.insert(row_id); row& r = m_rows[row_id]; if (!r.m_alive) { continue; } rational a = get_coefficient(row_id, x); if (a.is_zero()) { continue; } if (r.m_type == t_eq) { eq_row = row_id; continue; } if (r.m_type == t_mod) { mod_rows.push_back(row_id); } else if (a.is_pos()) { rational lub_value = x_val - (r.m_value/a); if (lub_rows.empty() || lub_value < lub_val || (lub_value == lub_val && r.m_type == t_lt && !lub_strict)) { lub_val = lub_value; lub_index = row_id; lub_strict = r.m_type == t_lt; } lub_rows.push_back(row_id); lub_is_unit &= a.is_one(); } else { SASSERT(a.is_neg()); rational glb_value = x_val - (r.m_value/a); if (glb_rows.empty() || glb_value > glb_val || (glb_value == glb_val && r.m_type == t_lt && !glb_strict)) { glb_val = glb_value; glb_index = row_id; glb_strict = r.m_type == t_lt; } glb_rows.push_back(row_id); glb_is_unit &= a.is_minus_one(); } } if (!mod_rows.empty()) { return solve_mod(x, mod_rows, compute_def); } if (eq_row != UINT_MAX) { return solve_for(eq_row, x, compute_def); } def result; unsigned lub_size = lub_rows.size(); unsigned glb_size = glb_rows.size(); unsigned row_index = (lub_size <= glb_size) ? lub_index : glb_index; // There are only upper or only lower bounds. if (row_index == UINT_MAX) { if (compute_def) { if (lub_index != UINT_MAX) { result = solve_for(lub_index, x, true); } else if (glb_index != UINT_MAX) { result = solve_for(glb_index, x, true); } else { result = def() + m_var2value[x]; } SASSERT(eval(result) == eval(x)); } else { for (unsigned row_id : lub_rows) retire_row(row_id); for (unsigned row_id : glb_rows) retire_row(row_id); } return result; } SASSERT(lub_index != UINT_MAX); SASSERT(glb_index != UINT_MAX); if (compute_def) { if (lub_size <= glb_size) { result = def(m_rows[lub_index], x); } else { result = def(m_rows[glb_index], x); } } // The number of matching lower and upper bounds is small. if ((lub_size <= 2 || glb_size <= 2) && (lub_size <= 3 && glb_size <= 3) && (!is_int(x) || lub_is_unit || glb_is_unit)) { for (unsigned i = 0; i < lub_size; ++i) { unsigned row_id1 = lub_rows[i]; bool last = i + 1 == lub_size; rational coeff = get_coefficient(row_id1, x); for (unsigned row_id2 : glb_rows) { if (last) { resolve(row_id1, coeff, row_id2, x); } else { unsigned row_id3 = copy_row(row_id2); resolve(row_id1, coeff, row_id3, x); } } } for (unsigned row_id : lub_rows) retire_row(row_id); return result; } // General case. rational coeff = get_coefficient(row_index, x); for (unsigned row_id : lub_rows) { if (row_id != row_index) { resolve(row_index, coeff, row_id, x); } } for (unsigned row_id : glb_rows) { if (row_id != row_index) { resolve(row_index, coeff, row_id, x); } } retire_row(row_index); return result; } // // compute D and u. // // D = lcm(d1, d2) // u = eval(x) mod D // // d1 | (a1x + t1) & d2 | (a2x + t2) // = // d1 | (a1(D*x' + u) + t1) & d2 | (a2(D*x' + u) + t2) // = // d1 | (a1*u + t1) & d2 | (a2*u + t2) // // x := D*x' + u // model_based_opt::def model_based_opt::solve_mod(unsigned x, unsigned_vector const& mod_rows, bool compute_def) { SASSERT(!mod_rows.empty()); rational D(1); for (unsigned idx : mod_rows) { D = lcm(D, m_rows[idx].m_mod); } if (D.is_zero()) { throw default_exception("modulo 0 is not defined"); } if (D.is_neg()) D = abs(D); TRACE("opt1", display(tout << "lcm: " << D << " x: v" << x << " tableau\n");); rational val_x = m_var2value[x]; rational u = mod(val_x, D); SASSERT(u.is_nonneg() && u < D); for (unsigned idx : mod_rows) { replace_var(idx, x, u); SASSERT(invariant(idx, m_rows[idx])); normalize(idx); } TRACE("opt1", display(tout << "tableau after replace x under mod\n");); // // update inequalities such that u is added to t and // D is multiplied to coefficient of x. // the interpretation of the new version of x is (x-u)/D // // a*x + t <= 0 // a*(D*x' + u) + t <= 0 // a*D*x' + a*u + t <= 0 // rational new_val = (val_x - u) / D; SASSERT(new_val.is_int()); unsigned y = add_var(new_val, true); unsigned_vector const& row_ids = m_var2row_ids[x]; uint_set visited; for (unsigned row_id : row_ids) { if (!visited.contains(row_id)) { // x |-> D*y + u replace_var(row_id, x, D, y, u); visited.insert(row_id); normalize(row_id); } } TRACE("opt1", display(tout << "tableau after replace x by y := v" << y << "\n");); def result = project(y, compute_def); if (compute_def) { result = (result * D) + u; m_var2value[x] = eval(result); } TRACE("opt1", display(tout << "tableau after project y" << y << "\n");); return result; } // update row with: x |-> C void model_based_opt::replace_var(unsigned row_id, unsigned x, rational const& C) { row& r = m_rows[row_id]; SASSERT(!get_coefficient(row_id, x).is_zero()); unsigned sz = r.m_vars.size(); unsigned i = 0, j = 0; rational coeff(0); for (; i < sz; ++i) { if (r.m_vars[i].m_id == x) { coeff = r.m_vars[i].m_coeff; } else { if (i != j) { r.m_vars[j] = r.m_vars[i]; } ++j; } } if (j != sz) { r.m_vars.shrink(j); } r.m_coeff += coeff*C; r.m_value += coeff*(C - m_var2value[x]); } // update row with: x |-> A*y + B void model_based_opt::replace_var(unsigned row_id, unsigned x, rational const& A, unsigned y, rational const& B) { row& r = m_rows[row_id]; rational coeff = get_coefficient(row_id, x); if (coeff.is_zero()) return; if (!r.m_alive) return; replace_var(row_id, x, B); r.m_vars.push_back(var(y, coeff*A)); r.m_value += coeff*A*m_var2value[y]; if (!r.m_vars.empty() && r.m_vars.back().m_id > y) { std::sort(r.m_vars.begin(), r.m_vars.end(), var::compare()); } m_var2row_ids[y].push_back(row_id); SASSERT(invariant(row_id, r)); } // 3x + t = 0 & 7 | (c*x + s) & ax <= u // 3 | -t & 21 | (-ct + 3s) & a-t <= 3u model_based_opt::def model_based_opt::solve_for(unsigned row_id1, unsigned x, bool compute_def) { TRACE("opt", tout << "v" << x << " := " << eval(x) << "\n" << m_rows[row_id1] << "\n";); rational a = get_coefficient(row_id1, x), b; row& r1 = m_rows[row_id1]; ineq_type ty = r1.m_type; SASSERT(!a.is_zero()); SASSERT(r1.m_alive); if (a.is_neg()) { a.neg(); r1.neg(); } SASSERT(a.is_pos()); if (ty == t_lt) { SASSERT(compute_def); r1.m_coeff -= r1.m_value; r1.m_type = t_le; r1.m_value = 0; } if (m_var2is_int[x] && !a.is_one()) { r1.m_coeff -= r1.m_value; r1.m_value = 0; vector<var> coeffs; mk_coeffs_without(coeffs, r1.m_vars, x); rational c = mod(-eval(coeffs), a); add_divides(coeffs, c, a); } unsigned_vector const& row_ids = m_var2row_ids[x]; uint_set visited; visited.insert(row_id1); for (unsigned row_id2 : row_ids) { if (!visited.contains(row_id2)) { visited.insert(row_id2); b = get_coefficient(row_id2, x); if (b.is_zero()) continue; row& dst = m_rows[row_id2]; switch (dst.m_type) { case t_eq: case t_lt: case t_le: solve(row_id1, a, row_id2, x); break; case t_mod: // mod reduction already done. UNREACHABLE(); break; } } } def result; if (compute_def) { result = def(m_rows[row_id1], x); m_var2value[x] = eval(result); TRACE("opt1", tout << "updated eval " << x << " := " << eval(x) << "\n";); } retire_row(row_id1); return result; } vector<model_based_opt::def> model_based_opt::project(unsigned num_vars, unsigned const* vars, bool compute_def) { vector<def> result; for (unsigned i = 0; i < num_vars; ++i) { result.push_back(project(vars[i], compute_def)); TRACE("opt", display(tout << "After projecting: v" << vars[i] << "\n");); } return result; } }
[ "noreply@github.com" ]
wintersteiger.noreply@github.com
2bf5bd6704e5c268e59ecebc63aff30b1ef7b9a9
852df37a4b702bdda62bd1c70d5837dec20307fc
/test/project-pkg/pkg-placeholder/src/show.cpp
5853ff54eb2166e4bc7cf4835a4c4e370857ddcb
[ "MIT" ]
permissive
uwstudent123/wio
ad09e9b6c13761abec9d60561e05cf38f95a9fea
765470ed560b323b425d2a0b50a63385a31fcb55
refs/heads/master
2022-02-15T05:23:39.253639
2019-02-22T16:43:47
2019-02-22T16:43:47
218,198,271
1
0
null
null
null
null
UTF-8
C++
false
false
556
cpp
#include "show.hh" #include <ingest.hh> #include <iostream> void show() { std::cout << "User Name: " << STRINGIFYMACRO(USER_NAME) << std::endl; std::cout << "User City: " << STRINGIFYMACRO(USER_CITY) << std::endl; #ifdef USER_AGE std::cout << "User Age: " << STRINGIFYMACRO(USER_AGE) << std::endl; #endif #ifdef LIVES_IN_CANADA std::cout << "User lives in Canada" << std::endl; #else std::cout << "User does not live in Canada" << std::endl; #endif std::cout << "\nDisplay from Ingest package: " << std::endl; display(); }
[ "noreply@github.com" ]
uwstudent123.noreply@github.com
3b8de8e99844be95db63c3aba6cf1497a9512fa8
26e42384993c2fdeba2bd1e02732ae3bda5a4419
/Graphs/BellmanFord.cpp
ced0bcf59e8a4cc7c9d425f081acca0399393510
[]
no_license
har200105/striverSDESheet
936b0e0bb922fd1cbffa3bc2c8cf0de23fd149a8
5176662a6c1529176508c86e5a064182cb71da76
refs/heads/master
2023-08-25T13:20:53.978758
2021-10-30T04:27:18
2021-10-30T04:27:18
408,673,436
95
21
null
2021-10-30T04:27:18
2021-09-21T03:17:28
C++
UTF-8
C++
false
false
1,027
cpp
#include<bits/stdc++.h> using namespace std; struct node { int u; int v; int wt; node(int first, int second, int weight) { u = first; v = second; wt = weight; } }; int main(){ int N,m; cin >> N >> m; vector<node> edges; for(int i = 0;i<m;i++) { int u, v, wt; cin >> u >> v >> wt; edges.push_back(node(u, v, wt)); } int src; cin >> src; int inf = 10000000; vector<int> dist(N, inf); dist[src] = 0; for(int i = 1;i<=N-1;i++) { for(auto it: edges) { if(dist[it.u] + it.wt < dist[it.v]) { dist[it.v] = dist[it.u] + it.wt; } } } int fl = 0; for(auto it: edges) { if(dist[it.u] + it.wt < dist[it.v]) { cout << "Negative Cycle"; fl = 1; break; } } if(!fl) { for(int i = 0;i<N;i++) { cout << i << " " << dist[i] << endl; } } return 0; }
[ "harshitr2001@gmail.com" ]
harshitr2001@gmail.com
b3bdc9c17dce16cd4018fc668d4f039007a15e0f
8cfbe9b1edec9badae5ca09b54f5714194b8df79
/src/ofxBitmapString.h
f807b56a819a6cffdb9463493217860171dad6ff
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
jg33/ofxAppUtils
3be35b044b95494a1298055927a18db4691c747f
993add0e9574da5fa7a181f37dc8e7d6041ea7d1
refs/heads/master
2020-12-25T23:25:57.401254
2014-11-06T04:25:40
2014-11-06T04:25:40
25,136,963
1
0
null
null
null
null
UTF-8
C++
false
false
2,061
h
/* * Copyright (c) 2011-2012 Dan Wilcox <danomatika@gmail.com> * * BSD Simplified License. * For information on usage and redistribution, and for a DISCLAIMER OF ALL * WARRANTIES, see the file, "LICENSE.txt," in this distribution. * * See https://github.com/danomatika/ofxAppUtils for documentation * */ #pragma once #include "ofGraphics.h" #include "ofVectorMath.h" //------------------------------------------------------------------------------ /// \class ofxBitmapStream /// \brief a stream interface to ofDrawBitmapStream /// /// ofxBitmapStream accepts variables via the ostream operator <<, builds a string, /// and logs it when the stream is finished (via the destructor). All the stream /// controls work (endl, flush, hex, etc). /// /// Usage: ofxBitmapString(10, 10) << "a string" << 100 << 20.234f; /// /// class idea from: /// http://www.gamedev.net/community/forums/topic.asp?topic_id=525405&whichpage=1&#3406418 /// how to catch std::endl (which is actually a func pointer): /// http://yvan.seth.id.au/Entries/Technology/Code/std__endl.html /// class ofxBitmapString { public: ofxBitmapString(const ofPoint & p) { pos = p; } ofxBitmapString(float x, float y, float z=0.0f) { pos.set(x, y, z); } /// does the actual printing on when the ostream is done ~ofxBitmapString() { ofDrawBitmapString(message.str(), pos.x, pos.y, pos.z); } /// catch the << ostream with a template class to read any type of data template <class T> ofxBitmapString& operator<<(const T& value) { message << value; return *this; } /// catch the << ostream function pointers such as std::endl and std::hex ofxBitmapString& operator<<(std::ostream& (*func)(std::ostream&)) { func(message); return *this; } private: ofPoint pos; ///< temp position std::ostringstream message; ///< temp buffer ofxBitmapString(ofxBitmapString const&) {} // not defined, not copyable ofxBitmapString& operator=(ofxBitmapString& from) {return *this;} // not defined, not assignable };
[ "danomatika@gmail.com" ]
danomatika@gmail.com
f8deea8eb35baf18373830389cc2422d8a74f968
925121d201ea444c94a8790f9726d8fdcafb719e
/Phase1/PASS1/include/Entry.h
453d1bd6ef1f5226ca5d035d04c1b300dd9ab9af
[]
no_license
AhmedMedhat7897/SIC-XE-assembler
2d4f8ce85f88796c1f2f475acae603fc24694c7e
455a2655f6406f146462b9aed97dbb26b8e5b5dc
refs/heads/master
2020-05-18T14:01:54.060066
2015-02-02T23:15:03
2015-02-02T23:15:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
354
h
#ifndef ENTRY_H #define ENTRY_H #include <string> #include<cstring> using namespace std; class Entry { public: int loc ; string label , op_code , operand ,comment,error; Entry(); Entry(int x , string a , string b , string c , string d,string e); virtual ~Entry(); protected: private: }; #endif // ENTRY_H
[ "amr.f.eldfrawy@gmail.com" ]
amr.f.eldfrawy@gmail.com
f1b362af2a2a26950c2822278526df43e4258516
9197b343ee61576246e5b1921c1d4ecb1ece271e
/callhandler.cpp
853ae0ad7d56819a5f379cc2f3f59e121412e5f5
[]
no_license
yfyf510/SuperSip
5b307e719ac3ebe0e7967deb9fbadd85401ecf5d
4728f1ca44629e42484b18ffd8540c9ca2b53c0f
refs/heads/master
2020-08-31T21:33:39.756596
2015-06-21T21:11:24
2015-06-21T21:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,815
cpp
#include <QtDebug> #include <QDateTime> #include <QCryptographicHash> #include "callhandler.h" #include "sipmessage.h" #include "sipparser.h" #include "sipdefinitions.h" #include "appsettings.h" CallHandler::CallHandler(QObject *parent) : QObject(parent) { // Create private key qsrand(QTime::currentTime().msec()); privateKey = ""; for (int i = 0; i < 100; i++) { char c = rand() % 256; privateKey.append(c); } } void CallHandler::processCallData(QByteArray callData, QHostAddress sender) { qDebug() << callData; SipMessage* sipmessage = new SipMessage(this); if (SipParser::parse(callData, sipmessage) == 0) { //qDebug() << callData; if (sipmessage->getIsRequest()) { switch(SipDefinitions::sipMethods.indexOf(sipmessage->getSipMethod())) { case 0: // INVITE { break; } case 1: // REGISTER { // check domain SipURI* sipuri = sipmessage->getSipUri(); if (!sipuri) { // TODO return; } QString domain = sipuri->getUriHost().toLower(); if (domain != QString(AppSettings::sipSettings->value("sipdomain").toByteArray()).toLower()) { // TODO qDebug() << domain <<" Domain NOK " << QString(AppSettings::sipSettings->value("sipdomain").toByteArray()).toLower(); return; } qDebug() << "Domain OK"; // TODO check required extensions 8.2.2 // Authentication // if (message contains auth) // { // // Check the response // } // else // { // // Send challenge // SipMessage responseMessage(401, sender, sipmessage); responseMessage.copyFromRequest(sipmessage); qint64 timestamp = QDateTime::currentMSecsSinceEpoch(); QByteArray ts = QByteArray::number(timestamp); QByteArray tohash = ts.append(":").append(privateKey); QByteArray hash = QCryptographicHash::hash(tohash, QCryptographicHash::Md5); QByteArray nonce = ts.append(":").append(hash).toBase64(); // generate opaque field opaque = ""; for (int i = 0; i < 20; i++) { char c = rand() % 256; opaque.append(c); } responseMessage.setWWW_AuthenticateNonce(nonce); responseMessage.setWWW_AuthenticateRealm(domain); responseMessage.setWWW_Authenticate(opaque.toBase64()); emit sendResponse(responseMessage.toBytes()); // } qDebug() << "rge"; break; } } } else { } } }
[ "aisebouma@gmail.com" ]
aisebouma@gmail.com
341ca542d9afd9e1fcff17c168bdf13d851cf23f
b8b9b95dafed18094649e61aac6bd629d46ef3d5
/graph/L3/tests/jaccardSimilaritySSDense/test_jaccardSimilaritySSDense.cpp
94da8133891b86e80c8d8b95434271feae5aad49
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
inaccel/Vitis_Libraries
87e64572b644c1b4a0d5789e5890832c47d4c077
876e262201069f46a78050e23a13db20dd73ad8b
refs/heads/master
2021-06-20T09:29:27.384124
2021-06-11T09:31:59
2021-06-11T09:31:59
343,359,839
0
0
Apache-2.0
2021-03-01T09:31:33
2021-03-01T09:31:32
null
UTF-8
C++
false
false
7,290
cpp
/* * Copyright 2020 Xilinx, 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. */ #include "utils.hpp" #include "xf_graph_L3.hpp" #define DT float int main(int argc, const char* argv[]) { //--------------- cmd parser ------------------------------- // cmd parser ArgParser parser(argc, argv); std::string filenameWeight; std::string goldenFile; std::string tmpStr; const int splitNm = 4; // kernel has 4 PUs, the input data should be splitted into 4 parts unsigned int numVertices = 16; // total number of vertex read from file unsigned int numEdges = 5; // total number of edge read from file uint32_t* numVerticesPU = new uint32_t[splitNm]; // vertex numbers in each PU uint32_t* numEdgesPU = new uint32_t[splitNm]; // edge numbers in each PU uint32_t topK; std::cout << "INFO: use dense graph" << std::endl; if (!parser.getCmdOption("-weight", tmpStr)) { // weight filenameWeight = "./data/jaccard_dense_weight.csr"; std::cout << "INFO: indices file path is not set, use default " << filenameWeight << "\n"; } else { filenameWeight = tmpStr; std::cout << "INFO: indices file path is " << filenameWeight << std::endl; } if (!parser.getCmdOption("-golden", tmpStr)) { // golden goldenFile = "./data/jaccard_dense.mtx"; std::cout << "INFO: golden file path is not set!\n"; } else { goldenFile = tmpStr; std::cout << "INFO: golden file path is " << goldenFile << std::endl; } if (!parser.getCmdOption("-topK", tmpStr)) { // topK topK = 32; std::cout << "INFO: topK is not set, use 32 by default" << std::endl; } else { topK = std::stoi(tmpStr); } //---------------- setup number of vertices in each PU --------- for (int i = 0; i < splitNm; ++i) { numVerticesPU[i] = 1; } int dataType = 1; // int32:0 float:1 int sourceID = 3; // source ID uint32_t* numElementsPU; numElementsPU = new uint32_t[splitNm]; for (int i = 0; i < splitNm; i++) { numEdgesPU[i] = numEdges; numElementsPU[i] = numEdges * numVerticesPU[i]; } xf::graph::Graph<uint32_t, DT> g("Dense", 4 * splitNm, numElementsPU); g.numEdgesPU = new uint32_t[splitNm]; g.numVerticesPU = new uint32_t[splitNm]; g.edgeNum = numEdges; g.nodeNum = numVertices; g.splitNum = splitNm; for (int i = 0; i < splitNm; ++i) { g.numVerticesPU[i] = numVerticesPU[i]; g.numEdgesPU[i] = numEdgesPU[i]; } std::fstream weightfstream(filenameWeight.c_str(), std::ios::in); if (!weightfstream) { std::cout << "Error: " << filenameWeight << "weight file doesn't exist !" << std::endl; exit(1); } unsigned int sumVertex = 0; for (int i = 0; i < splitNm; i++) { // offset32 buffers allocation sumVertex += 4 * numVerticesPU[i]; } if (sumVertex != numVertices) { // vertex numbers between file input and numVerticesPU should match std::cout << "Error : sum of PU vertex numbers doesn't match file input vertex number!" << std::endl; std::cout << "sumVertex =" << sumVertex << " numVertices=" << numVertices << std::endl; exit(1); } readInWeight<splitNm>(weightfstream, dataType, numElementsPU, g.weightsDense); std::cout << "INFO: numVertice=" << numVertices << std::endl; std::cout << "INFO: numEdges=" << numEdges << std::endl; //---------------- Generate Source Indice and Weight Array ------- unsigned int sourceNUM; // sourceIndice array length uint32_t* sourceWeight; // weights of source vertex's out members generateSourceParams<splitNm>(numVerticesPU, numEdges, dataType, sourceID, g.weightsDense, sourceNUM, &sourceWeight); //----------------- Text Parser ---------------------------------- std::string opName; std::string kernelName; int requestLoad; std::string xclbinPath; int deviceNeeded; std::fstream userInput("./config.json", std::ios::in); if (!userInput) { std::cout << "Error : file doesn't exist !" << std::endl; exit(1); } char line[1024] = {0}; char* token; while (userInput.getline(line, sizeof(line))) { token = strtok(line, "\"\t ,}:{\n"); while (token != NULL) { if (!std::strcmp(token, "operationName")) { token = strtok(NULL, "\"\t ,}:{\n"); opName = token; } else if (!std::strcmp(token, "kernelName")) { token = strtok(NULL, "\"\t ,}:{\n"); kernelName = token; } else if (!std::strcmp(token, "requestLoad")) { token = strtok(NULL, "\"\t ,}:{\n"); requestLoad = std::atoi(token); } else if (!std::strcmp(token, "xclbinPath")) { token = strtok(NULL, "\"\t ,}:{\n"); xclbinPath = token; } else if (!std::strcmp(token, "deviceNeeded")) { token = strtok(NULL, "\"\t ,}:{\n"); deviceNeeded = std::atoi(token); } token = strtok(NULL, "\"\t ,}:{\n"); } } userInput.close(); //----------------- Setup similarity thread --------- xf::graph::L3::Handle::singleOP op0; op0.operationName = (char*)opName.c_str(); op0.setKernelName((char*)kernelName.c_str()); op0.requestLoad = requestLoad; op0.xclbinFile = (char*)xclbinPath.c_str(); op0.deviceNeeded = deviceNeeded; xf::graph::L3::Handle handle0; handle0.addOp(op0); handle0.setUp(); //---------------- Load Graph ----------------------------------- (handle0.opsimdense)->loadGraph(g); float* similarity = xf::graph::L3::aligned_alloc<float>(topK); uint32_t* resultID = xf::graph::L3::aligned_alloc<uint32_t>(topK); memset(resultID, 0, topK * sizeof(uint32_t)); memset(similarity, 0, topK * sizeof(float)); //---------------- Run L3 API ----------------------------------- auto ev = xf::graph::L3::jaccardSimilaritySSDense(handle0, sourceNUM, sourceWeight, topK, g, resultID, similarity); int ret = ev.wait(); (handle0.opsimdense)->join(); handle0.free(); g.freeBuffers(); //---------------- Check Result --------------------------------- int err = checkData<splitNm>(goldenFile, resultID, similarity); delete[] numElementsPU; delete[] numVerticesPU; delete[] numEdgesPU; free(g.numEdgesPU); free(g.numVerticesPU); if (err == 0) { std::cout << "INFO: Results are correct" << std::endl; return 0; } else { std::cout << "Error: Results are false" << std::endl; return 1; } }
[ "sdausr@xilinx.com" ]
sdausr@xilinx.com
160f6d7630cfefe909c966d9b9b4ea5e545cd657
cf21471b4076cb1695cf054d17d33aa927c298f6
/Blink_AnalogRead/Blink_AnalogRead.ino
ac52474874e44d82db87aaaa2dfa9011ea86f37b
[]
no_license
oscarbego/ArduinoFreeRTOS_Colas_Estructura
987a9c6a7e255d1c0dddba32199b36091699bfac
326c9797dfce05bbebda01b37297d3245055cff6
refs/heads/main
2023-01-05T09:53:17.736795
2020-11-07T00:59:36
2020-11-07T00:59:36
310,731,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,802
ino
#include <Arduino_FreeRTOS.h> // Include queue support #include <queue.h> // Define a struct struct boton { int id; }; // define two tasks for Blink & AnalogRead void TaskBlink( void *pvParameters ); void TaskRead( void *pvParameters ); void setup() { Serial.begin(9600); while (!Serial) { } xTaskCreate( TaskBlink , "Blink" // A name just for humans , 128 // This stack size can be checked & adjusted by reading the Stack Highwater , NULL , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. , NULL ); xTaskCreate( TaskRead , "AnalogRead" , 128 // Stack size , NULL , 1 // Priority , NULL ); } void loop() { // Empty. Things are done in Tasks. } /*--------------------------------------------------*/ /*---------------------- Tasks ---------------------*/ /*--------------------------------------------------*/ void TaskBlink(void *pvParameters) // This is a task. { (void) pvParameters; // initialize digital LED_BUILTIN on pin 13 as an output. pinMode(LED_BUILTIN, OUTPUT); for (;;) // A Task shall never return or exit. { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second } } void TaskRead(void *pvParameters) // This is a task. { (void) pvParameters; for (;;) { if (Serial.available()) { Serial.print(Serial.readString()); } //Serial.println(sensorValue); vTaskDelay(1); // one tick delay (15ms) in between reads for stability } }
[ "oscar.bego@gmail.com" ]
oscar.bego@gmail.com
e0e01ef299e8d37da7bceb0ed6d08e5b4516e033
ba5b9f328442262a95219933a217cb5bfc982c86
/Classes/HelpScene.h
ce1bdb9aa6df8bdd724e91f53a91f58175882aa2
[]
no_license
Latoris/Cross-Me
5845bd4a112784ff84b616fe36c1abd880ef0c02
e4b9b1da09323832a9440dfef6eea6bd37cd939a
refs/heads/master
2016-09-05T17:44:30.829513
2015-07-01T13:08:09
2015-07-01T13:08:09
37,413,794
0
0
null
null
null
null
UTF-8
C++
false
false
271
h
#ifndef _HELPSCENE_H_ #define _HELPSCENE_H_ #include <cocos2d.h> #include <iostream> USING_NS_CC; class HelpScene: public Layer{ public: virtual bool init(); static Scene* createScene(); bool onTouchbegan(Touch *t, Event *e); CREATE_FUNC(HelpScene); }; #endif
[ "renjietang009649@gmail.com" ]
renjietang009649@gmail.com
1f3c357773c6579f592bd5e0ca7c88e56166c5e8
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp
882209b76267db402e857cf92893f90a16ddf0c8
[ "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
8,466
cpp
/* * Copyright (c) 2006,2007,2008, Google 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 the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/graphics/skia/SkiaUtils.h" #include "SkColorPriv.h" #include "SkRegion.h" #include "platform/graphics/GraphicsContext.h" #include "platform/graphics/ImageBuffer.h" namespace WebCore { static const struct CompositOpToXfermodeMode { uint8_t mCompositOp; uint8_t m_xfermodeMode; } gMapCompositOpsToXfermodeModes[] = { { CompositeClear, SkXfermode::kClear_Mode }, { CompositeCopy, SkXfermode::kSrc_Mode }, { CompositeSourceOver, SkXfermode::kSrcOver_Mode }, { CompositeSourceIn, SkXfermode::kSrcIn_Mode }, { CompositeSourceOut, SkXfermode::kSrcOut_Mode }, { CompositeSourceAtop, SkXfermode::kSrcATop_Mode }, { CompositeDestinationOver, SkXfermode::kDstOver_Mode }, { CompositeDestinationIn, SkXfermode::kDstIn_Mode }, { CompositeDestinationOut, SkXfermode::kDstOut_Mode }, { CompositeDestinationAtop, SkXfermode::kDstATop_Mode }, { CompositeXOR, SkXfermode::kXor_Mode }, { CompositePlusDarker, SkXfermode::kDarken_Mode }, { CompositePlusLighter, SkXfermode::kPlus_Mode } }; // keep this array in sync with blink::WebBlendMode enum in public/platform/WebBlendMode.h static const uint8_t gMapBlendOpsToXfermodeModes[] = { SkXfermode::kClear_Mode, // blink::WebBlendModeNormal SkXfermode::kMultiply_Mode, // blink::WebBlendModeMultiply SkXfermode::kScreen_Mode, // blink::WebBlendModeScreen SkXfermode::kOverlay_Mode, // blink::WebBlendModeOverlay SkXfermode::kDarken_Mode, // blink::WebBlendModeDarken SkXfermode::kLighten_Mode, // blink::WebBlendModeLighten SkXfermode::kColorDodge_Mode, // blink::WebBlendModeColorDodge SkXfermode::kColorBurn_Mode, // blink::WebBlendModeColorBurn SkXfermode::kHardLight_Mode, // blink::WebBlendModeHardLight SkXfermode::kSoftLight_Mode, // blink::WebBlendModeSoftLight SkXfermode::kDifference_Mode, // blink::WebBlendModeDifference SkXfermode::kExclusion_Mode, // blink::WebBlendModeExclusion SkXfermode::kHue_Mode, // blink::WebBlendModeHue SkXfermode::kSaturation_Mode, // blink::WebBlendModeSaturation SkXfermode::kColor_Mode, // blink::WebBlendModeColor SkXfermode::kLuminosity_Mode // blink::WebBlendModeLuminosity }; PassRefPtr<SkXfermode> WebCoreCompositeToSkiaComposite(CompositeOperator op, blink::WebBlendMode blendMode) { if (blendMode != blink::WebBlendModeNormal) { if ((uint8_t)blendMode >= SK_ARRAY_COUNT(gMapBlendOpsToXfermodeModes)) { SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown blink::WebBlendMode %d\n", blendMode)); return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode)); } SkXfermode::Mode mode = (SkXfermode::Mode)gMapBlendOpsToXfermodeModes[(uint8_t)blendMode]; return adoptRef(SkXfermode::Create(mode)); } const CompositOpToXfermodeMode* table = gMapCompositOpsToXfermodeModes; for (unsigned i = 0; i < SK_ARRAY_COUNT(gMapCompositOpsToXfermodeModes); i++) { if (table[i].mCompositOp == op) return adoptRef(SkXfermode::Create((SkXfermode::Mode)table[i].m_xfermodeMode)); } SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown CompositeOperator %d\n", op)); return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode)); // fall-back } static U8CPU InvScaleByte(U8CPU component, uint32_t scale) { SkASSERT(component == (uint8_t)component); return (component * scale + 0x8000) >> 16; } SkColor SkPMColorToColor(SkPMColor pm) { if (!pm) return 0; unsigned a = SkGetPackedA32(pm); if (!a) { // A zero alpha value when there are non-zero R, G, or B channels is an // invalid premultiplied color (since all channels should have been // multiplied by 0 if a=0). SkASSERT(false); // In production, return 0 to protect against division by zero. return 0; } uint32_t scale = (255 << 16) / a; return SkColorSetARGB(a, InvScaleByte(SkGetPackedR32(pm), scale), InvScaleByte(SkGetPackedG32(pm), scale), InvScaleByte(SkGetPackedB32(pm), scale)); } void ClipRectToCanvas(const GraphicsContext* context, const SkRect& srcRect, SkRect* destRect) { if (!context->getClipBounds(destRect) || !destRect->intersect(srcRect)) destRect->setEmpty(); } bool SkPathContainsPoint(const SkPath& originalPath, const FloatPoint& point, SkPath::FillType ft) { SkRect bounds = originalPath.getBounds(); // We can immediately return false if the point is outside the bounding // rect. We don't use bounds.contains() here, since it would exclude // points on the right and bottom edges of the bounding rect, and we want // to include them. SkScalar fX = SkFloatToScalar(point.x()); SkScalar fY = SkFloatToScalar(point.y()); if (fX < bounds.fLeft || fX > bounds.fRight || fY < bounds.fTop || fY > bounds.fBottom) return false; // Scale the path to a large size before hit testing for two reasons: // 1) Skia has trouble with coordinates close to the max signed 16-bit values, so we scale larger paths down. // TODO: when Skia is patched to work properly with large values, this will not be necessary. // 2) Skia does not support analytic hit testing, so we scale paths up to do raster hit testing with subpixel accuracy. SkScalar biggestCoord = std::max(std::max(std::max(bounds.fRight, bounds.fBottom), -bounds.fLeft), -bounds.fTop); if (SkScalarNearlyZero(biggestCoord)) return false; biggestCoord = std::max(std::max(biggestCoord, fX + 1), fY + 1); const SkScalar kMaxCoordinate = SkIntToScalar(1 << 15); SkScalar scale = SkScalarDiv(kMaxCoordinate, biggestCoord); SkRegion rgn; SkRegion clip; SkMatrix m; SkPath scaledPath(originalPath); scaledPath.setFillType(ft); m.setScale(scale, scale); scaledPath.transform(m, 0); int x = static_cast<int>(floorf(0.5f + point.x() * scale)); int y = static_cast<int>(floorf(0.5f + point.y() * scale)); clip.setRect(x - 1, y - 1, x + 1, y + 1); return rgn.setPath(scaledPath, clip); } SkMatrix affineTransformToSkMatrix(const AffineTransform& source) { SkMatrix result; result.setScaleX(WebCoreDoubleToSkScalar(source.a())); result.setSkewX(WebCoreDoubleToSkScalar(source.c())); result.setTranslateX(WebCoreDoubleToSkScalar(source.e())); result.setScaleY(WebCoreDoubleToSkScalar(source.d())); result.setSkewY(WebCoreDoubleToSkScalar(source.b())); result.setTranslateY(WebCoreDoubleToSkScalar(source.f())); // FIXME: Set perspective properly. result.setPerspX(0); result.setPerspY(0); result.set(SkMatrix::kMPersp2, SK_Scalar1); return result; } } // namespace WebCore
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
291dbaf23159e8f5d1d55e6b3a41180dc2293c73
f4865775b92eef264e2f274672bd61c0564fd21d
/Monopoly/MonopolyFinal/Space.h
07206830ff75647600f2958c8ab35750d3bee398
[]
no_license
turtle328/monopoly-game
750b5f539531e9666fce2b35b1d2c409708fa5b3
6a50ce3569f56558a51d7648a66b9535f39cc7e4
refs/heads/master
2020-04-20T17:32:54.087294
2019-02-03T20:56:52
2019-02-03T20:56:52
168,991,434
0
0
null
null
null
null
UTF-8
C++
false
false
219
h
#pragma once #include <string> #include <vector> class Player; class Space { public: virtual void run(Player&) = 0; virtual std::string getName() const = 0; virtual std::vector<std::string> boardOut() const = 0; };
[ "ajr6974@g.rit.edu" ]
ajr6974@g.rit.edu
842d77ed36dd1e1273c4ee9bcc04da838b5bb886
b8194fee4ddf498b2c1bd302ec4ba9466746250d
/build/Android/Debug/app/src/main/include/Fuse.Android.GLUtils.h
b155012a68bbd9a4958aceaf9911e5fcb49e9cf4
[]
no_license
color0e/Fabric_Fuse_Project
e49e7371c9579d80c9ec96c1f2d3a90de7b52149
9b20a0347e5249315cf7af587e04234ec611c6be
refs/heads/master
2020-03-30T16:49:34.363764
2018-10-03T16:26:28
2018-10-03T16:26:28
151,428,896
0
1
null
null
null
null
UTF-8
C++
false
false
1,029
h
// This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Android.TextRenderer/1.9.0/Internal/GLUtils.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Android{struct Bitmap;}}} namespace g{namespace Fuse{namespace Android{struct GLUtils;}}} namespace g{namespace Java{struct Object;}} namespace g{ namespace Fuse{ namespace Android{ // internal sealed extern class GLUtils :12 // { uType* GLUtils_typeof(); void GLUtils__TexImage2D_fn(int32_t* target, int32_t* level, ::g::Java::Object* bitmap, int32_t* border); void GLUtils__TexImage2D1_fn(int32_t* target, int32_t* level, ::g::Fuse::Android::Bitmap* bitmap, int32_t* border); struct GLUtils : uObject { static void TexImage2D(int32_t target, int32_t level, ::g::Java::Object* bitmap, int32_t border); static void TexImage2D1(int32_t target, int32_t level, ::g::Fuse::Android::Bitmap* bitmap, int32_t border); }; // } }}} // ::g::Fuse::Android
[ "limjangsoon@naver.com" ]
limjangsoon@naver.com
32f784377fdf89fdb8908e48e323d49e18e494e1
f581543fb8e1ddb83453dd09f861657d4b535b8f
/src/client/networkHandler.cpp
d24d632a21ea257aa404c2d1107b8a1e0aa3fa92
[]
no_license
Paul92/Quizzzer
878ab960674a6e99c475b82ad258163208712a93
1e2597dd584351e43b8f386d248a4c0aafe3aac0
refs/heads/master
2020-12-11T07:25:47.840562
2016-02-10T22:24:30
2016-02-10T22:24:30
46,889,596
0
0
null
null
null
null
UTF-8
C++
false
false
5,344
cpp
#include "networkHandler.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "error.h" #include <QtDebug> #include <QMessageBox> #include <QApplication> #include <QSocketNotifier> NetworkHandler::NetworkHandler(QObject *parent, QString host, int port) : QObject(parent), host(host), port(port) { struct sockaddr_in serv_addr; struct hostent *server; this->sockfd = socket(AF_INET, SOCK_STREAM, 0); if (this->sockfd < 0) { QMessageBox::critical(0, tr("Eroare"), tr("Conectarea la server nu a reusit (socket)")); exit(0); } server = gethostbyname(this->host.toLatin1().data()); if (server == NULL) { QMessageBox::critical(0, tr("Eroare"), tr("Conectarea la server nu a reusit (DNS)")); exit(0); } bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(port); if (::connect(this->sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) { QMessageBox::critical(0, tr("Eroare"), tr("Conectarea la server nu a reusit (connect)")); exit(0); } this->notifier = new QSocketNotifier(this->sockfd, QSocketNotifier::Read); this->notifier->setEnabled(false); } void NetworkHandler::loginSlot(const QString &username, const QString &password) { QString loginString = "login " + username + " " + password + "\n"; const char *loginCommand = loginString.toLatin1().data(); write(this->sockfd, loginCommand, strlen(loginCommand)); char buffer[64]; read(this->sockfd, buffer, 64); if (strcmp(buffer, "OK\n") != 0) emit loginFailed(); else emit loginSucessfull(); } void NetworkHandler::registerSlot(const QString &username, const QString &password) { QString loginString = "newuser " + username + " " + password + "\n"; const char *registerCommand = loginString.toLatin1().data(); write(this->sockfd, registerCommand, strlen(registerCommand)); char buffer[64]; read(this->sockfd, buffer, 64); if (strcmp(buffer, "OK\n") != 0) emit registerFailed(); else emit loginSucessfull(); } NetworkHandler::~NetworkHandler() { char quitString[] = "quit\n"; write(this->sockfd, quitString, strlen(quitString)); delete this->notifier; close(this->sockfd); } void NetworkHandler::waitForGameStart() { connect(this->notifier, SIGNAL(activated(int)), this, SLOT(gameStartSlot(int))); this->notifier->setEnabled(true); qDebug("GameStart Activated\n"); } void NetworkHandler::waitForQuestionUpdate() { connect(this->notifier, SIGNAL(activated(int)), this, SLOT(newQuestionSlot(int))); this->notifier->setEnabled(true); qDebug("QuestionUpdate Activated\n"); } void NetworkHandler::gameStartSlot(int sockfd) { qDebug("Game start slot called\n"); char buffer[256]; read(this->sockfd, buffer, 256); qDebug() << "Received status " << buffer; if (strncmp(buffer, "game_started\n", 12) == 0) { qDebug("Signal Emitted\n"); this->notifier->setEnabled(false); disconnect(this->notifier, 0, this, 0); emit gameStartSignal(); } } void NetworkHandler::handleQuestion(QString buffer) { qDebug("Raising question signal"); QStringList params = buffer.split("|"); params.removeFirst(); QuestionData question(params); emit newQuestionSignal(question); } void NetworkHandler::handleScoreboard(QString buffer) { qDebug("Raising scoreboard signal"); QStringList params = buffer.split("|"); params.removeFirst(); ScoreTable table(params); emit newScoreboardSignal(table); } void NetworkHandler::handleEndgame(QString buffer) { qDebug("Raising endgame signal"); this->notifier->setEnabled(false); disconnect(this->notifier, 0, this, 0); emit gameEndSignal(); } void NetworkHandler::newQuestionSlot(int sockfd) { char buffer[1024]; memset(buffer, 0, 1024 * sizeof(char)); read(this->sockfd, buffer, 1024); qDebug() << "New command: " << buffer; if (strncmp(buffer, "question", 8) == 0) handleQuestion(buffer); else if (strncmp(buffer, "scoreboard", 10) == 0) handleScoreboard(buffer); else if (strncmp(buffer, "game_end", 8) == 0) handleEndgame(buffer); else qCritical() << "Unexpected command in newQuestionSlot: " << buffer; } void NetworkHandler::sendAnswer(int answer) { QString command = "answer " + QString::number(answer) + "\n"; const char *answerCommand = command.toLatin1().data(); write(this->sockfd, answerCommand, strlen(answerCommand)); qDebug("Answer command sent"); } ScoreTable NetworkHandler::getScoreTable() { char buffer[1024]; memset(buffer, 0, 1024 * sizeof(char)); read(this->sockfd, buffer, 1024); QString string(buffer); QStringList params = string.split("|"); params.removeFirst(); qDebug("Final score table received"); return ScoreTable(params); } void NetworkHandler::logout() { char logoutString[] = "logout\n"; write(this->sockfd, logoutString, strlen(logoutString)); qDebug("Logout command sent"); }
[ "paul.gafton@gmail.com" ]
paul.gafton@gmail.com
e5db5dae90e192270a7f78894a35a0244fae68d0
a672d3a9d99cd1306b7e216a83ac5bdadd4eb56c
/.svn/pristine/e5/e5db5dae90e192270a7f78894a35a0244fae68d0.svn-base
c10e933c234f93de3348ff9dbdbeef9be0caeebc
[ "Zlib" ]
permissive
LiveMirror/freedownload
a5a6ccf936aab411403f69f2a5438fcf966e05d3
43bcee2fda538b817890f4021e48af5da1098874
refs/heads/master
2020-06-05T02:24:55.481333
2019-06-17T05:40:36
2019-06-17T05:40:36
192,281,362
1
1
null
null
null
null
UTF-8
C++
false
false
1,233
/* Free Download Manager Copyright (c) 2003-2016 FreeDownloadManager.ORG */ #if !defined(AFX_DLGVIDSEEK_H__909ED8B4_A02B_4EFE_9297_AA426833BB15__INCLUDED_) #define AFX_DLGVIDSEEK_H__909ED8B4_A02B_4EFE_9297_AA426833BB15__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif class CDlgVidSeek : public CDialog { public: HWND m_hWndDuration; CString GetDuration(); void Set_MediaSeeking (IMediaSeeking* seek); CDlgVidSeek(CWnd* pParent = NULL); //{{AFX_DATA(CDlgVidSeek) enum { IDD = IDD_VIDSEEK }; CSliderCtrl m_wndSeek; //}}AFX_DATA //{{AFX_VIRTUAL(CDlgVidSeek) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL protected: CBrush m_brClrWindow; CString DurationToString (LONGLONG llDur, BOOL* pbNeedHours = NULL); LONGLONG m_llDuration; IMediaSeeking* m_seek; //{{AFX_MSG(CDlgVidSeek) afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg void OnSize(UINT nType, int cx, int cy); virtual BOOL OnInitDialog(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} #endif
[ "638781@qq.com" ]
638781@qq.com
c27c63ba34dbd4ca634c834e33cad7a216eb40d3
18e75b4f3e46673ca79990cd1cb2bd8637c87466
/HelloWorld2/main/greet.h
9f2a849c7325567203d3f02932974e274ccd50fc
[]
no_license
hika019/bazel_test
edf007a85abc37c1cd59e44429460ada92ac80e1
74cd167db81d4f0d8ce39c3fca5601bc6bd4c698
refs/heads/master
2023-08-20T05:13:21.633874
2021-10-30T03:29:37
2021-10-30T03:29:37
422,772,416
0
0
null
null
null
null
UTF-8
C++
false
false
80
h
#pragma once #include <string> std::string get_greet(const std::string &thing);
[ "ikazuti2001@gmail.com" ]
ikazuti2001@gmail.com
34d69ac909f06dc595db8293de1f933759b20ce4
0a139335433bc38750f7b6e51414d93573f7f449
/manyAmeba/src/ofApp.h
cda19f062e37d9db05e89729ec3bdcf8b2cdda7f
[]
no_license
kotaonaga/ofPrototyping
e8b23839a95a68cd372846718d4e409077c3d186
796edb917f06a62e6544c5b166ce10d75d0a633f
refs/heads/master
2021-05-24T08:11:32.780363
2020-07-06T13:45:42
2020-07-06T13:45:42
253,464,461
1
0
null
null
null
null
UTF-8
C++
false
false
833
h
#pragma once #include "ofMain.h" #include "ofxGui.h" #include "Ameba.hpp" #define amebaNum 15 class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofxPanel gui; ofxFloatSlider noiseScale; ofxFloatSlider noiseScale2; Ameba amebas[amebaNum]; ofFbo fbo; };
[ "kohtaonaga@gmail.com" ]
kohtaonaga@gmail.com
2ccb89e3749fae25e728fae36207ede17d578fa0
c7036309916267fff8b90950b859f5dfa57c72aa
/05.cpp
c55def06ab45bf83fdf800b2a672f751abb8b4b9
[]
no_license
shraddha5595/RepositoryDEMO
012f9971ad5e4afbe9217f97bd20c09dbc8719c9
f0a9fa8ee505f57b0dc7e52536ad1901e7b9320f
refs/heads/master
2020-09-23T16:24:47.438219
2019-12-03T05:39:22
2019-12-03T05:39:22
225,540,266
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
#include<iostream> #include<cmath> using namespace std; class complex { int real; int img; public: complex(); complex(int, int); void accept(); void display(); complex operator + (complex&x); complex operator - (complex&x); complex operator ++(); complex operator ++(int); }; complex::complex() { real = 0; img = 0; } complex::complex(int r, int i) { real = r; img = i; } void complex::accept() { cin>>real; cin>>img; } void complex::display() { char ch; ch=(img>0)?'+':'-'; cout<<real<<ch<<abs(img)<<"i"<<endl; } complex complex::operator +(complex&c) { complex temp; temp.real=this->real+c.real; temp.img= this->img+c.img; return temp; } complex complex::operator -(complex&c) { complex temp; temp.real=this->real-c.real; temp.img=this->img-c.img; return temp; } complex complex::operator ++() { complex temp; temp.real = ++real; temp.img = ++img; return temp; } complex complex::operator ++(int) { complex temp; temp.real = real++; temp.img = img++; return temp; } int main() { complex c1(10,20); complex c2(11,22); complex c3,c6; c3=c1+c2; c6=c1-c2; complex c4,c5; c4=++c1; c5=c1++; c3.display(); c6.display(); c4.display(); c5.display(); return 0; }
[ "shraddha5595@gmail.com" ]
shraddha5595@gmail.com
a48c69ed1b474cd81a3735a64f771844f41e71ef
cefd6c17774b5c94240d57adccef57d9bba4a2e9
/WebKit/Source/WebCore/html/canvas/OESStandardDerivatives.h
a21dfd89c1b6089d086f71af9944431910907755
[ "BSL-1.0", "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only" ]
permissive
adzhou/oragle
9c054c25b24ff0a65cb9639bafd02aac2bcdce8b
5442d418b87d0da161429ffa5cb83777e9b38e4d
refs/heads/master
2022-11-01T05:04:59.368831
2014-03-12T15:50:08
2014-03-12T15:50:08
17,238,063
0
1
BSL-1.0
2022-10-18T04:23:53
2014-02-27T05:39:44
C++
UTF-8
C++
false
false
1,849
h
/* * Copyright (C) 2011 Google 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: * * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef OESStandardDerivatives_h #define OESStandardDerivatives_h #include "WebGLExtension.h" #include <wtf/PassOwnPtr.h> namespace WebCore { class OESStandardDerivatives : public WebGLExtension { public: static OwnPtr<OESStandardDerivatives> create(WebGLRenderingContext*); virtual ~OESStandardDerivatives(); virtual ExtensionName getName() const override; private: OESStandardDerivatives(WebGLRenderingContext*); }; } // namespace WebCore #endif // OESStandardDerivatives_h
[ "adzhou@hp.com" ]
adzhou@hp.com
c281ee1187a66305080e447b172efe1949b92b95
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/preloading/chrome_preloading.h
0c35f7acc7ccf8b1fdff08de9f5b919766f643bc
[ "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
7,659
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PRELOADING_CHROME_PRELOADING_H_ #define CHROME_BROWSER_PRELOADING_CHROME_PRELOADING_H_ #include <string> #include "content/public/browser/browser_context.h" #include "content/public/browser/preloading.h" #include "url/gurl.h" class TemplateURLService; // If you change any of the following enums or static variables, please follow // the process in go/preloading-dashboard-updates to update the mapping // reflected in dashboard, or if you are not a Googler, please file an FYI bug // on https://crbug.new with component Internals>Preload. // Defines various embedder triggering mechanisms which triggers different // preloading operations mentioned in //content/public/browser/preloading.h. // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. // // Advance numbering by +1 when adding a new element. // // Please make sure Chrome `PreloadingPredictor` are defined after 100 // (inclusive) as 99 and below are reserved for content-public and // content-internal definitions. Both the value and the name should be unique // across all the namespaces. namespace chrome_preloading_predictor { // When the preloading URL is predicted from the Omnibox Direct URL Input // (DUI). This is used to perform various preloading operations like prefetch // and prerender to load Omnibox predicted URLs faster. static constexpr content::PreloadingPredictor kOmniboxDirectURLInput( 100, "OmniboxDirectURLInput"); // When a pointerdown (e.g. mousedown or touchstart) event happens on an // anchor element with an href value pointing to an HTTP(S) origin, we may // attempt to preload the link. static constexpr content::PreloadingPredictor kPointerDownOnAnchor( 101, "PointerDownOnAnchor"); // When the preloading URL is predicted from the default search suggest // service for faster search page loads. static constexpr content::PreloadingPredictor kDefaultSearchEngine( 102, "DefaultSearchEngine"); // When the preloading URL is predicted from the default search suggest due to // change in Omnibox selection. static constexpr content::PreloadingPredictor kOmniboxSearchPredictor( 103, "OmniboxSearchPredictor"); // When the preloading URL is predicted from the default search suggest due to // mouse being pressed down on a Omnibox Search suggestion. static constexpr content::PreloadingPredictor kOmniboxMousePredictor( 104, "OmniboxMousePredictor"); // When the default match in omnibox has the search prefetch or prerender // hint. static constexpr content::PreloadingPredictor kOmniboxSearchSuggestDefaultMatch( 105, "OmniboxSearchSuggestDefaultMatch"); // When the user hovers their mouse over the back button. static constexpr content::PreloadingPredictor kBackButtonHover( 106, "BackButtonHover"); // When a pointerdown (e.g. mousedown or touchstart) event happens on an // bookmark bar link to an HTTPS origin, we may attempt to preload the link. static constexpr content::PreloadingPredictor kPointerDownOnBookmarkBar( 107, "PointerDownOnBookmarkBar"); // When a mousehover event happens on a bookmark bar link to an HTTPS origin, // we may attempt to preload the link. static constexpr content::PreloadingPredictor kMouseHoverOnBookmarkBar( 108, "MouseHoverOnBookmarkBar"); // When a pointerdown (e.g. mousedown or touchstart) event happens on a // new tab page link to an HTTPS origin, we may attempt to preload the link. static constexpr content::PreloadingPredictor kPointerDownOnNewTabPage( 109, "PointerDownOnNewTabPage"); // When a mousehover event happens on a new tab page link to an HTTPS origin, // we may attempt to preload the link. static constexpr content::PreloadingPredictor kMouseHoverOnNewTabPage( 110, "MouseHoverOnNewTabPage"); // When the preloading URL is predicted from the default search suggest due to // the user touching down on a Omnibox Search suggestion. static constexpr content::PreloadingPredictor kOmniboxTouchDownPredictor( 111, "OmniboxTouchDownPredirector"); // TODO(crbug.com/1309934): Integrate more Preloading predictors with // Preloading logging APIs. } // namespace chrome_preloading_predictor // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class ChromePreloadingEligibility { // Numbering starts from `kPreloadingEligibilityContentEnd` defined in // //content/public/preloading.h . Advance numbering by +1 when adding a new // element. // Chrome was unable to get a LoadingPredictor object for the user profile. kUnableToGetLoadingPredictor = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd), // Preloading was ineligible because Prefetch was not started and Prerender // can't be triggered. kPrefetchNotStarted = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 1, // Preloading was ineligible because Prefetch failed and Prerender can't be // triggered. kPrefetchFailed = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 2, // Preloading was ineligible because Prerender was already consumed and can't // be triggered again. kPrerenderConsumed = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 3, // Preloading was ineligible because the default search engine was not set. kSearchEngineNotValid = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 4, // Preloading can't be started because there are no search terms present. kNoSearchTerms = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 5, // Preloading was ineligible due to error in the network request. kPreloadingErrorBackOff = static_cast<int>( content::PreloadingEligibility::kPreloadingEligibilityContentEnd) + 6, kMaxValue = kPreloadingErrorBackOff, }; // Helper method to convert ChromePreloadingEligibility to // content::PreloadingEligibility to avoid casting. content::PreloadingEligibility ToPreloadingEligibility( ChromePreloadingEligibility eligibility); // Helpers methods to extract search terms from a given URL. TemplateURLService* GetTemplateURLServiceFromBrowserContext( content::BrowserContext* browser_context); std::u16string ExtractSearchTermsFromURL( const TemplateURLService* const template_url_service, const GURL& url); std::u16string ExtractSearchTermsFromURL( content::BrowserContext* browser_context, const GURL& url); // Returns true if a canonical URL representation of a |preloading_url| can be // generated. |canonical_url| is set to the canonical URL representation when // this method returns |true|. bool HasCanoncialPreloadingOmniboxSearchURL( const GURL& preloading_url, content::BrowserContext* browser_context, GURL* canonical_url); // Returns true when |navigation_url| is considered as navigating to the same // omnibox search results page as |canonical_preloading_search_url|. bool IsSearchDestinationMatch(const GURL& canonical_preloading_search_url, content::BrowserContext* browser_context, const GURL& navigation_url); #endif // CHROME_BROWSER_PRELOADING_CHROME_PRELOADING_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
48716202947a59d0e96f6c4cf2a588c3bc7524cb
d1898867627b877d93afa1473534307f154c6afa
/cpp/two_sum.cpp
edd2de351da5f51809c6590ed897d46ba5255c25
[]
no_license
muraig/learning_list
c1c4b1a7c9100a06153e66a81d2b00c04575ac53
d60ffefb9dc2c0a16e36b69f9bc36e29ca583144
refs/heads/master
2023-01-21T06:10:45.590314
2020-12-06T16:30:11
2020-12-06T16:30:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
#include <iostream> #include <vector> #include <unordered_map> using namespace std; vector<int> two_sum(const vector<int> &nums, int target) { unordered_map<int, int> seen; for (int i = 0; i < nums.size(); i++) { int cur_num = nums[i]; if (seen.count(cur_num)) return vector<int>{seen[cur_num], i}; else seen[target - cur_num] = i; } return vector<int>{}; } int main(int argc, char const *argv[]) { vector<int> nums{1, 2, 3, 4, 5, 6, 20, 30}; int target = 31; cout << "sum is " << target << ": " << endl; for (auto i : two_sum(nums, target)) cout << i << endl; return 0; }
[ "1107432420@qq.com" ]
1107432420@qq.com
973c3f37782b5335f61395ce3f304a956f39f31d
f08eec0f98931afd9fe43bc1a1fbc8d76f46994d
/Source/Asteroid.cpp
5f908d7bc8f359e44a46f27ef0fb5d982167ec7a
[]
no_license
sevenred1995/Shoot-The-Chicken-3D
c70d1d030eac907f1fe0c0ffb42fd036a1d37001
f1e1d04e32d6fe3cf8396a390cfb88a360ca58ad
refs/heads/master
2021-05-31T03:28:59.373527
2016-05-15T10:37:56
2016-05-15T10:37:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,090
cpp
#include "Game.h" using namespace GamePlay; static std::default_random_engine rndEngine; static std::uniform_real_distribution<float> posDist(-c_halfMovementRestrictBoxWidth/2.0f, c_halfMovementRestrictBoxWidth/2.0f); static std::uniform_real_distribution<float> speedDist(-0.2f, 0.2f); static std::uniform_real_distribution<float> rotSpeedDist(-0.001f, 0.001f); void IAsteroid::Init(UINT asteroidType) { //floating rocks(asteroids), random engine is used to generator random coordinate switch(UINT(asteroidType)) { case AsteroidType_Rock1: mMesh.LoadFile_OBJ("Media/rock1.obj"); break; case AsteroidType_Rock2: mMesh.LoadFile_OBJ("Media/rock2.obj"); break; case AsteroidType_Rock3: mMesh.LoadFile_OBJ("Media/rock3.obj"); break; case AsteroidType_Box: default: float width = rand() % 50 + 50; mMesh.CreateBox(width, width, width, 3, 3, 3); break; } //texture mTexture.LoadPPM("Media/rock.ppm"); //mMesh.SetTexture(&mTexture); Material mat; mat.ambient = { 0.3f,0.3f,0.3f }; mat.diffuse = { 0.7f,0.7f,0.7f }; mMesh.SetMaterial(mat); //movement param init mMesh.SetPosition(posDist(rndEngine), posDist(rndEngine), posDist(rndEngine)); mRotateSpeed = { rotSpeedDist(rndEngine),rotSpeedDist(rndEngine), rotSpeedDist(rndEngine)}; mMoveSpeed = { speedDist(rndEngine),speedDist(rndEngine), speedDist(rndEngine) }; } void IAsteroid::Update() { //move VECTOR3 pos = mMesh.GetPosition(); pos += mMoveSpeed; //if rock go out of the restricted boundary,re-init pos if (abs(pos.x) > c_halfMovementRestrictBoxWidth || abs(pos.y) > c_halfMovementRestrictBoxWidth || abs(pos.z) > c_halfMovementRestrictBoxWidth) { pos = { posDist(rndEngine), posDist(rndEngine), posDist(rndEngine) }; } mMesh.SetPosition(pos); //rotate mMesh.RotateX_Pitch(mRotateSpeed.x*gTimeElapsed); mMesh.RotateY_Yaw(mRotateSpeed.y*gTimeElapsed); mMesh.RotateZ_Roll(mRotateSpeed.z*gTimeElapsed); } void IAsteroid::Render() { gRenderer.RenderMesh(mMesh); } void IAsteroid::GetBoundingBox(BOUNDINGBOX & outBox) { mMesh.ComputeBoundingBox(outBox); }
[ "836613859@qq.com" ]
836613859@qq.com
e33de6f221bff0d4aaeb928ca50d0f44e256f12e
75502a1cc7eeebbe47c9e7c06f23f0d16b477fe7
/ngx_pose_proto/ngx_http_pose_module.cpp
b5de9c2eaf8a0feb5082161ad6b9307ab055e15b
[]
no_license
pengjiawei/ngx_protobuf_addon
d52a8e13400631096b3ecbe4380e655505d1fd7f
9491a032535a60908ae4870fd5465b51aabe44aa
refs/heads/master
2020-03-14T03:32:45.797979
2018-06-23T05:52:55
2018-06-23T05:52:55
131,422,253
1
0
null
null
null
null
UTF-8
C++
false
false
7,499
cpp
#include <SeNaviCommon/Service/Client.h> #include <type/pose2d.h> extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include "ngx_pose_proto.h" #include <stdio.h> #include <stdlib.h> static char * ngx_http_pose(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static ngx_int_t ngx_http_pose_handler(ngx_http_request_t *r); } using namespace std; static ngx_command_t ngx_http_pose_commands[] = { { ngx_string("pose"), NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_HTTP_LMT_CONF | NGX_CONF_NOARGS, ngx_http_pose, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_pose_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_pose_module = { NGX_MODULE_V1, &ngx_http_pose_module_ctx, /* module context */ ngx_http_pose_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static char * ngx_http_pose(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_core_loc_conf_t *clcf; //首先找到mytest配置项所属的配置块,clcf貌似是location块内的数据 //结构,其实不然,它可以是main、srv或者loc级别配置项,也就是说在每个 //http{}和server{}内也都有一个ngx_http_core_loc_conf_t结构体 clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); //http框架在处理用户请求进行到NGX_HTTP_CONTENT_PHASE阶段时,如果 //请求的主机域名、URI与mytest配置项所在的配置块相匹配,就将调用我们 //实现的ngx_http_mytest_handler方法处理这个请求 clcf->handler = ngx_http_pose_handler; return NGX_CONF_OK; } ngx_pose_t *unpack_pose(ngx_str_t *val, ngx_pool_t *pool) { ngx_protobuf_context_t ctx; ngx_pose_t *pose; pose = ngx_pose__alloc(pool); if (pose == NULL) { return NULL; } ctx.pool = pool; ctx.buffer.start = val->data; ctx.buffer.pos = ctx.buffer.start; ctx.buffer.last = val->data + val->len; ctx.reuse_strings = 1; if (ngx_pose__unpack(pose, &ctx) != NGX_OK) { return NULL; } return pose; } ngx_int_t pack_pose(ngx_pose_t *pose, ngx_str_t *output, ngx_pool_t *pool, FILE *file) { FILE *fout; fout = fopen("/tmp/nginx_pack_log", "a+tc"); fprintf(fout, "in pack pose!\n"); fflush(fout); ngx_protobuf_context_t ctx; size_t size; ngx_int_t rc; fprintf(fout, "pose x = %d\n", pose->x); fflush(fout); size = ngx_pose__size(pose); if (size == 0) { return NGX_DECLINED; } fprintf(fout, "pose size = %d\n", size); fflush(fout); output->data = ngx_palloc(pool, size); if (output->data == NULL) { fprintf(fout, "output->data is null\n"); fflush(fout); return NGX_ERROR; } ctx.pool = pool; ctx.buffer.start = output->data; ctx.buffer.pos = ctx.buffer.start; ctx.buffer.last = ctx.buffer.start + size; rc = ngx_pose__pack(pose, &ctx); output->len = ctx.buffer.pos - ctx.buffer.start; u_char cc = *(output->data + output->len); fprintf(fout, "pack rc = %d,output->len = %d output->data = %c\n", rc, output->len, cc); fflush(fout); return rc; } static ngx_int_t ngx_http_pose_handler(ngx_http_request_t *r) { //必须是GET或者HEAD方法,否则返回405 Not Allowed if (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD))) { return NGX_HTTP_NOT_ALLOWED; } //丢弃请求中的包体 ngx_int_t rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } FILE *fout; fout = fopen("/tmp/nginx_pose_log", "a+tc"); fprintf(fout, "m->start process!\n"); fflush(fout); ngx_pose_t *pose = ngx_pose__alloc(r->pool); NS_Service::Client<sgbot::Pose2D>* pose_cli = new NS_Service::Client<sgbot::Pose2D>("DISPLAY_POSE"); sgbot::Pose2D display_pose; if(pose_cli->call(display_pose)){ fprintf(fout, "construct_pose x = %.4f,y = %.4f\n",display_pose.x(),display_pose.y()); ngx_pose__set_x(pose, display_pose.x()); ngx_pose__set_y(pose, display_pose.y()); }else{ fprintf(fout, "call pose failed\n"); fflush(fout); return -1; } delete pose_cli; fprintf(fout, "pose has x = %d,has y =%d,size = %d\n", pose->__has_x, pose->__has_y, ngx_pose__size(pose)); ngx_str_t str = ngx_null_string; ngx_str_t *output = &str; fprintf(fout, "pack pose\n"); fflush(fout); pack_pose(pose, output, r->pool, fout); ngx_str_t test_t = ngx_string("hello, this is nginx"); // output = &test_t; fprintf(fout, "output len = %d data = %c\n", output->len, *(output->data + output->len)); //设置返回的Content-Type。注意,ngx_str_t有一个很方便的初始化宏 //ngx_string,它可以把ngx_str_t的data和len成员都设置好 ngx_str_t type = ngx_string("text/plain"); //设置Content-Type r->headers_out.content_type = type; //set length of msg r->headers_out.content_length_n = output->len; //设置返回状态码 r->headers_out.status = NGX_HTTP_OK; rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { fprintf(fout, "send header error\n"); return rc; } ngx_buf_t *b; b = ngx_create_temp_buf(r->pool, output->len); if (b == NULL) { fprintf(fout, "ngx_buf_t is null\n"); fflush(fout); return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_memcpy(b->pos, output->data, output->len); b->last = b->pos + output->len; b->last_buf = 1; //构造发送时的ngx_chain_t结构体 ngx_chain_t out; //赋值ngx_buf_t out.buf = b; //设置next为NULL out.next = NULL; //最后一步发送包体,http框架会调用ngx_http_finalize_request方法 //结束请求 fprintf(fout, "m->end process!\n"); fflush(fout); fclose(fout); return ngx_http_output_filter(r, &out); }
[ "917527280@qq.com" ]
917527280@qq.com
fa10412606fc2668e050b88e3922c3455e482f47
01898637df8f69931d40d99f1c25606b8830a92d
/CodeFourses/A. Omkar and Password.cpp
9ee43cad72838a344083832dbf9c82501175df80
[ "Apache-2.0" ]
permissive
Rafat97/RafatProgtammingContest
5126a8f3f6845af8032015d5bd406fefa86db2ce
f39ef6a71511abb91d42c6af469e4b24959be226
refs/heads/master
2021-12-21T15:57:13.127188
2021-12-07T14:18:53
2021-12-07T14:18:53
170,029,411
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
#include<bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> #define ll long long #define fastoi ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define printNPrecision(afterDigit,value) cout << fixed << setprecision(12) << value <<endl; #define llu unsigned long long #define lld long long #define U unsigned int #define LSOne(S) (S & (-S)) #define isBitSet(S, i) ((S >> i) & 1) const int MOD = 1000000007; const int MAX = 1000005; void solve(){ int n, val; vector<int> data; cin >>n; for(int i = 0 ; i < n ; i++ ){ cin>>val; data.push_back(val); } sort(data.begin() , data.end()); if(data[0] == data[n-1]) cout<<n<<endl; else cout<<1<<endl; } int main() { fastoi ; int t; cin>>t; while(t--) solve(); return 0; }
[ "rafathaque1997@gmail.com" ]
rafathaque1997@gmail.com
0e2fb71464e141305abb2930fe1df608376395d2
b6607ecc11e389cc56ee4966293de9e2e0aca491
/NSUTS/2015/I/Main.cpp
5453853fe39c949e2ece18853a6f167b341d0213
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
2,014
cpp
/**************************************** ** Solution by NU #2 ** ****************************************/ #include <bits/stdc++.h> using namespace std; #define F first #define S second #define MP make_pair #define all(x) (x).begin(), (x).end() typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef unsigned int uint32; const double EPS = 1e-9; const double PI = acos(-1.0); const int MOD = 1000 * 1000 * 1000 + 7; const int INF = 2000 * 1000 * 1000; template <typename T> inline T sqr(T n) { return n * n; } int Q; uint32 a; uint32 rev_add(uint32 h, int shift) { uint32 result = 0; uint32 mask = (1 << shift) - 1; uint32 cur = 0; while (mask > 0) { cur = h & mask; result |= cur; h -= cur; mask <<= shift; cur <<= shift; h -= cur; } return result; } uint32 rev_xor(uint32 h, int shift) { uint32 result = 0; uint32 mask = ((1 << shift) - 1) << (32 - shift); uint32 cur = 0; while (mask > 0) { cur = h & mask; result |= cur; h ^= cur; mask >>= shift; cur >>= shift; h ^= cur; } return result; } uint32 reverse(uint32 a) { a = rev_add(a, 16); a = rev_xor(a, 11); a = rev_add(a, 3); a = rev_xor(a, 6); a = rev_add(a, 10); return a; } uint32 gen() { uint32 result = rand(); result <<= 16; result |= rand(); return result; } void test() { while (true) { uint32 a = gen(); int s = gen() % 31 + 1; uint32 aa1 = a + (a << s); uint32 aa2 = a ^ (a >> s); assert(rev_add(aa1, s) == a); assert(rev_xor(aa2, s) == a); } } int main() { srand(time(NULL)); freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); //test(); scanf("%d", &Q); while (Q--) { scanf("%u", &a); printf("%u\n", reverse(a)); } return 0; }
[ "bekzhan.kassenov@nu.edu.kz" ]
bekzhan.kassenov@nu.edu.kz
0a6f6f3cedbc56030d698593430b9cc0973575c9
8ffe3ce13e05aae7467d79d8cc4ac006dbe003d7
/HW5-TemplatedQueue/HW5-TemplatedQueue/HW5-TemplatedQueue.cpp
00585fe29fb629d23fb986ec40238f1cb3bc898b
[]
no_license
ccc9775/IGME209-02
38392e2808973d8bd787badefd5b46d4991270e6
23b1ab83d543fba6b9fbda28e7cb11d3c40c5ade
refs/heads/main
2023-08-01T07:59:51.641388
2021-09-21T15:54:38
2021-09-21T15:54:38
332,861,503
0
0
null
null
null
null
UTF-8
C++
false
false
1,769
cpp
// HW5-TemplatedQueue.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <string> #include "queue.h" using namespace std; struct Player { string name; int health; }one, two, three; int main() { Queue<int> intTest; Queue<string> stringTest; Queue<Player> playerTest; //test for integers in the queue cout << "Integers" << endl; cout << intTest.IsEmpty() << endl; intTest.Push(27); cout << "first int test (should print 27):" << endl; intTest.Print(); intTest.Push(13); intTest.Push(1000); intTest.PushFirst(1234); cout << "second int test (should print 1234, 27, 13, 1000):" << endl; intTest.Print(); intTest.Pop(); cout << "third int test (should print 13, 1000):" << endl; intTest.Print(); cout << intTest.IsEmpty() << endl; cout << "Strings" << endl; stringTest.IsEmpty(); cout << "first string test (should print an error message):" << endl; stringTest.Print(); stringTest.Push("cat"); stringTest.Push("hat"); stringTest.Push("bat"); stringTest.Push("rat"); cout << "second string test (should print cat, hat, bat, rat):" << endl; stringTest.Print(); stringTest.Pop(); stringTest.PopLast(); cout << "third string test (should print hat, bat):" << endl; stringTest.Print(); //test with a custom player struct (was told not to worry about printing for this one) one.health = 30; one.name = "Jedd"; two.health = 100; two.name = "Viktor"; three.health = 60; three.name = "Salazar"; cout << "Players" << endl; playerTest.Push(one); playerTest.Push(two); playerTest.Pop(); playerTest.Push(three); }
[ "ccc9775@rit.edu" ]
ccc9775@rit.edu
d1bddec1e62e0670283141d29fa5cb41bae3954a
4ea885e9f170e45cc6f60a0c17ed2b5f7e6e33c9
/lab5.5_10.cpp
2e4116eeac96c4c3883636da92ec44216a92ea76
[]
no_license
AdyaAnwesa/lab5.5
c7158f0987d723fcf0f90c283223cf7070c7016e
9803371b5c53df31b3d98c762dfee6921b4dd43a
refs/heads/master
2020-03-28T04:07:01.193712
2018-09-07T14:47:08
2018-09-07T14:47:08
147,694,697
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
#include<iostream> using namespace std; int main() { //Print Mirror Right Triangle Star Pattern //Ask user for Required size Triangle int n,j; cout << "What is size of the Mirror Right Triangle star pattern that you want?"<<endl; cin >> n; //Printing Rows for(int i=1; i<=n; i++){ //Printing Columns //Print Spaces for(j=i; j<n; j++){ cout<<" "; } //Print Stars for(j=1; j<=i; j++){ cout<<"*"; } cout<<endl; } return 10; }
[ "noreply@github.com" ]
AdyaAnwesa.noreply@github.com
ce0c34704422255360abd9d559c3d9bf6614d584
2fbc36bdeafcb900f2d1981743b8a3cdcb532fb1
/src/kernel/math/math.h
895e1ef87dda247de9b965d60a5bfc8e564c555e
[]
no_license
mrFlatiron/learnopengl
67734a67113ae66a472b292fa8319440f5fc2f43
3618c137eefb63455fe643ed6b796beb9fef9bec
refs/heads/master
2020-03-30T21:38:52.379743
2018-10-11T17:27:21
2018-10-11T17:27:21
151,636,243
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
#ifndef MATH_H #define MATH_H #include <glm/glm.hpp> namespace math { namespace constants { constexpr float cmp_eps = 2 * std::numeric_limits<float>::epsilon (); } //namespace math::constants inline bool fuzzy_eq (float a, float b, float eps = math::constants::cmp_eps) { return fabs (a - b) < eps; } inline bool fuzzy_eq (const glm::vec3 &a, const glm::vec3 &b, float eps = math::constants::cmp_eps) { for (int i = 0; i < 3; i++) if (!fuzzy_eq (a[i], b[i], eps)) return false; return true; } inline float length (const glm::vec3 &vec) { return sqrt (glm::dot (vec, vec)); } } //namespace math #endif // MATH_H
[ "mr.flatiron@mail.ru" ]
mr.flatiron@mail.ru
b8ce6a9753b3de90a39e226d1664b96c39cd5005
b3ccdce795076b48120063d3e4f99c7a781b8a15
/src/InsertionSort.cpp
dbda9d6c28f763b397eafb24e7093627b359ad82
[]
no_license
JackThorp/SortingAlgorithms
8773b3e9d7502e256130484d190dc97e1b11c330
8117b566ededd8be1414d21df147ea590ed9af07
refs/heads/master
2021-10-19T17:57:42.625297
2019-02-22T19:36:08
2019-02-22T19:36:08
112,600,199
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
cpp
// // InsertionSort.cpp // SortingAlgorithms // // Created by Jack Thorp on 08/01/2018. // Copyright © 2018 Jack Thorp. All rights reserved. // #include "InsertionSort.hpp" using namespace std; // Insertion sort. // 1. Put smallest element at list beginning // 2. Iterate through list until end is reached holding on to current element // 3. Whilst current element is smaller than it's left hand neighbour shift neighbour right // 4. Insert current element where left neighour is no longer smaller void InsertionSort::sort(vector<int>& list) { // Move smallest element to front. // 5, 4, 3, 2, 1, (0) for (int i = int(list.size()) - 1; i > 0; --i) { if (list[i] < list[i-1]) { int temp = list[i-1]; list[i-1] = list[i]; list[i] = temp; } } int count = 2; for (int i = count; i < list.size(); ++i) { int v = list[i]; int j = i; while(v < list[j-1]) { list[j] = list[j-1]; j--; } list[j] = v; } return; }
[ "jackthorp13@gmail.com" ]
jackthorp13@gmail.com
5817874dab033cb6e5494c5ae3d6b67bfa24cb95
5286798f369775a6607636a7c97c87d2a4380967
/thirdparty/cgal/CGAL-5.1/include/CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h
f89d8fa204f3a963647bf103153d05460f6eef19
[ "GPL-3.0-only", "LGPL-2.1-or-later", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "MIT-0", "LGPL-3.0-only", "LGPL-3.0-or-later" ]
permissive
MelvinG24/dust3d
d03e9091c1368985302bd69e00f59fa031297037
c4936fd900a9a48220ebb811dfeaea0effbae3ee
refs/heads/master
2023-08-24T20:33:06.967388
2021-08-10T10:44:24
2021-08-10T10:44:24
293,045,595
0
0
MIT
2020-09-05T09:38:30
2020-09-05T09:38:29
null
UTF-8
C++
false
false
11,721
h
// Copyright (c) 2009-2013 GeometryFactory (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL: https://github.com/CGAL/cgal/blob/v5.1/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h $ // $Id: polygon_soup_to_polygon_mesh.h 2780fa0 2020-08-05T10:49:14+02:00 Mael Rouxel-Labbé // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : Laurent Rineau and Ilker O. Yaz #ifndef CGAL_POLYGON_MESH_PROCESSING_POLYGON_SOUP_TO_POLYGON_MESH_H #define CGAL_POLYGON_MESH_PROCESSING_POLYGON_SOUP_TO_POLYGON_MESH_H #include <CGAL/license/Polygon_mesh_processing/repair.h> #include <CGAL/Polygon_mesh_processing/orient_polygon_soup.h> #include <CGAL/algorithm.h> #include <CGAL/boost/graph/Euler_operations.h> #include <CGAL/boost/graph/iterator.h> #include <CGAL/boost/graph/named_params_helper.h> #include <CGAL/Dynamic_property_map.h> #include <CGAL/property_map.h> #include <boost/dynamic_bitset.hpp> #include <boost/range/size.hpp> #include <boost/range/value_type.hpp> #include <boost/range/reference.hpp> #include <array> #include <set> #include <type_traits> #include <vector> namespace CGAL { namespace Polygon_mesh_processing { namespace internal { template <typename PM_Point, typename PS_Point> PM_Point convert_to_pm_point(const PS_Point& p) { CGAL_static_assertion((std::is_convertible<PS_Point, PM_Point>::value)); return PM_Point(p); } // just for backward compatibility reasons template <typename PM_Point, typename PS_FT> PM_Point convert_to_pm_point(const std::array<PS_FT, 3>& p) { return PM_Point(p[0], p[1], p[2]); } template <typename PointRange, typename PolygonRange, typename PointMap = typename CGAL::GetPointMap<PointRange>::const_type> class PS_to_PM_converter { typedef typename boost::range_value<PolygonRange>::type Polygon; public: /** * The constructor for modifier object. * @param points points of the soup of polygons. * @param polygons each element in the range describes a polygon using the index of the points in the range. */ PS_to_PM_converter(const PointRange& points, const PolygonRange& polygons, const PointMap pm = PointMap()) : m_points(points), m_polygons(polygons), m_pm(pm) { } template <typename PolygonMesh, typename VertexPointMap> void operator()(PolygonMesh& pmesh, VertexPointMap vpm, const bool insert_isolated_vertices = true) { typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor; typedef typename boost::property_traits<VertexPointMap>::value_type PM_Point; reserve(pmesh, static_cast<typename boost::graph_traits<PolygonMesh>::vertices_size_type>(m_points.size()), static_cast<typename boost::graph_traits<PolygonMesh>::edges_size_type>(2*m_polygons.size()), static_cast<typename boost::graph_traits<PolygonMesh>::faces_size_type>(m_polygons.size())); boost::dynamic_bitset<> not_isolated; if(!insert_isolated_vertices) { not_isolated.resize(m_points.size()); for(std::size_t i = 0, end = m_polygons.size(); i < end; ++i) { const Polygon& polygon = m_polygons[i]; const std::size_t size = polygon.size(); for(std::size_t j = 0; j < size; ++j) not_isolated.set(polygon[j], true); } } std::vector<vertex_descriptor> vertices(m_points.size()); for(std::size_t i = 0, end = m_points.size(); i < end; ++i) { if(!insert_isolated_vertices && !not_isolated.test(i)) continue; vertices[i] = add_vertex(pmesh); PM_Point pi = convert_to_pm_point<PM_Point>(get(m_pm, m_points[i])); put(vpm, vertices[i], pi); } for(std::size_t i = 0, end = m_polygons.size(); i < end; ++i) { const Polygon& polygon = m_polygons[i]; const std::size_t size = polygon.size(); std::vector<vertex_descriptor> vr(size); //vertex range vr.resize(size); for(std::size_t j = 0; j < size; ++j) vr[j] = vertices[polygon[j] ]; CGAL_assertion_code(typename boost::graph_traits<PolygonMesh>::face_descriptor fd =) CGAL::Euler::add_face(vr, pmesh); CGAL_assertion(fd != boost::graph_traits<PolygonMesh>::null_face()); } } template <typename PolygonMesh> void operator()(PolygonMesh& pmesh, const bool insert_isolated_vertices = true) { return operator()(pmesh, get(CGAL::vertex_point, pmesh), insert_isolated_vertices); } private: const PointRange& m_points; const PolygonRange& m_polygons; const PointMap m_pm; }; } // namespace internal /** * \ingroup PMP_repairing_grp * * returns `true` if the soup of polygons defines a valid polygon * mesh that can be handled by * `CGAL::Polygon_mesh_processing::polygon_soup_to_polygon_mesh()`. * It checks that each edge has at most two incident faces and such an edge * is visited in opposite direction along the two face boundaries, * no polygon has twice the same vertex, * and the polygon soup describes a manifold surface. * This function does not require a range of points as an argument * since the check is purely topological. To each vertex of the mesh * is associated an index that is used in the description of the * boundaries of the polygons provided in `polygons`. * * @tparam PolygonRange a model of the concept `RandomAccessContainer` * whose value_type is a model of the concept `RandomAccessContainer` * whose value_type is `std::size_t`. * * @param polygons each element in the range describes a polygon * using the indices of the vertices. * * @sa `orient_polygon_soup()` */ template<typename PolygonRange> bool is_polygon_soup_a_polygon_mesh(const PolygonRange& polygons) { typedef typename boost::range_value<PolygonRange>::type Polygon; typedef typename boost::range_value<Polygon>::type V_ID; if(boost::begin(polygons) == boost::end(polygons)) return true; //check there is no duplicated ordered edge, and //check there is no polygon with twice the same vertex std::set<std::pair<V_ID, V_ID> > edge_set; V_ID max_id = 0; for(const Polygon& polygon : polygons) { std::size_t nb_edges = boost::size(polygon); if(nb_edges < 3) return false; std::set<V_ID> polygon_vertices; V_ID prev = *std::prev(boost::end(polygon)); for(V_ID id : polygon) { if(max_id<id) max_id = id; if(! edge_set.insert(std::pair<V_ID, V_ID>(prev,id)).second) return false; else prev = id; if(!polygon_vertices.insert(id).second) return false; // vertex met twice in the same polygon } } //check manifoldness typedef std::vector<V_ID> PointRange; typedef internal::Polygon_soup_orienter<PointRange, PolygonRange> Orienter; typename Orienter::Edge_map edges(max_id+1); typename Orienter::Marked_edges marked_edges; Orienter::fill_edge_map(edges, marked_edges, polygons); //returns false if duplication is necessary if(!marked_edges.empty()) return false; return Orienter::has_singular_vertices(static_cast<std::size_t>(max_id+1),polygons,edges,marked_edges); } /** * \ingroup PMP_repairing_grp * builds a polygon mesh from a soup of polygons. * * @pre the input polygon soup describes a consistently oriented * polygon mesh. This can be checked using the function * \link CGAL::Polygon_mesh_processing::is_polygon_soup_a_polygon_mesh() * `CGAL::Polygon_mesh_processing::is_polygon_soup_a_polygon_mesh(polygons)` \endlink. * * @tparam PolygonMesh a model of `MutableFaceGraph` * @tparam PointRange a model of the concept `RandomAccessContainer` * whose value type is the point type * @tparam PolygonRange a model of the concept `RandomAccessContainer` whose * value type is a model of the concept `RandomAccessContainer` whose value type is `std::size_t` * @tparam NamedParameters_PS a sequence of \ref bgl_namedparameters "Named Parameters" * @tparam NamedParameters_PM a sequence of \ref bgl_namedparameters "Named Parameters" * * @param points points of the soup of polygons * @param polygons each element in the vector describes a polygon using the indices of the points in `points` * @param out the polygon mesh to be built * @param np_ps an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin * \cgalParamNBegin{point_map} * \cgalParamDescription{a property map associating points to the elements of the range `points`} * \cgalParamType{a model of `ReadablePropertyMap` whose value type is a point type convertible to the point type * of the vertex point map associated to the polygon mesh} * \cgalParamDefault{`CGAL::Identity_property_map`} * \cgalParamNEnd * \cgalNamedParamsEnd * * @param np_pm an optional sequence of \ref bgl_namedparameters "Named Parameters" among the ones listed below * * \cgalNamedParamsBegin * \cgalParamNBegin{vertex_point_map} * \cgalParamDescription{a property map associating points to the vertices of `out`} * \cgalParamType{a class model of `ReadWritePropertyMap` with `boost::graph_traits<PolygonMesh>::%vertex_descriptor` * as key type and `%Point_3` as value type} * \cgalParamDefault{`boost::get(CGAL::vertex_point, out)`} * \cgalParamExtra{If this parameter is omitted, an internal property map for `CGAL::vertex_point_t` * must be available in `PolygonMesh`.} * \cgalParamNEnd * \cgalNamedParamsEnd * * \sa `CGAL::Polygon_mesh_processing::orient_polygon_soup()` * \sa `CGAL::Polygon_mesh_processing::is_polygon_soup_a_polygon_mesh()` * \sa `CGAL::Polygon_mesh_processing::polygon_mesh_to_polygon_soup()` */ template<typename PolygonMesh, typename PointRange, typename PolygonRange, typename NamedParameters_PS, typename NamedParameters_PM> void polygon_soup_to_polygon_mesh(const PointRange& points, const PolygonRange& polygons, PolygonMesh& out, const NamedParameters_PS& np_ps, const NamedParameters_PM& np_pm) { CGAL_precondition_msg(is_polygon_soup_a_polygon_mesh(polygons), "Input soup needs to define a valid polygon mesh! See is_polygon_soup_a_polygon_mesh() for further information."); using parameters::choose_parameter; using parameters::get_parameter; typedef typename CGAL::GetPointMap<PointRange, NamedParameters_PS>::const_type Point_map; Point_map pm = choose_parameter<Point_map>(get_parameter(np_ps, internal_np::point_map)); typedef typename CGAL::GetVertexPointMap<PolygonMesh, NamedParameters_PM>::type Vertex_point_map; Vertex_point_map vpm = choose_parameter(get_parameter(np_pm, internal_np::vertex_point), get_property_map(CGAL::vertex_point, out)); internal::PS_to_PM_converter<PointRange, PolygonRange, Point_map> converter(points, polygons, pm); converter(out, vpm); } template<typename PolygonMesh, typename PointRange, typename PolygonRange> void polygon_soup_to_polygon_mesh(const PointRange& points, const PolygonRange& polygons, PolygonMesh& out) { return polygon_soup_to_polygon_mesh(points, polygons, out, parameters::all_default(), parameters::all_default()); } } // namespace Polygon_mesh_processing } // namespace CGAL #endif // CGAL_POLYGON_MESH_PROCESSING_POLYGON_SOUP_TO_POLYGON_MESH_H
[ "huxingyi@msn.com" ]
huxingyi@msn.com
14a1f8389a1728c21abb96e8c519c44e6ea3ab89
998f0d972c05fb4e944a38db990dcd9f30cf8f26
/toolkit/Source/src/gs2d/src/Platform/FileLogger.cpp
c2b182667c0e3fb5a7309ded5bf8dce67343914e
[ "MIT" ]
permissive
Teanan/ethanon
d7e37eafd4a38688499b6106d66f03186381bae3
967188ebb90c9080170f612a0c265a8c6d03a0b6
refs/heads/master
2020-12-24T13:17:27.136834
2013-03-25T14:53:26
2013-03-25T14:53:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,619
cpp
/*-------------------------------------------------------------------------------------- Ethanon Engine (C) Copyright 2008-2013 Andre Santee http://ethanonengine.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. --------------------------------------------------------------------------------------*/ #include "FileLogger.h" #include "Platform.h" #include <fstream> #include <iostream> #ifdef ANDROID #include "android/AndroidLog.h" #endif namespace Platform { bool AppendToFile(const gs2d::str_type::string& fileName, const gs2d::str_type::string& str) { gs2d::str_type::ofstream ofs(fileName.c_str(), std::ios::out | std::ios::app); if (ofs.is_open()) { ofs << str << std::endl; ofs.close(); return true; } else { return false; } } FileLogger::FileLogger(const gs2d::str_type::string& fileName) : m_fileName(fileName) { gs2d::str_type::ofstream ofs(fileName.c_str()); if (ofs.is_open()) { ofs << GS_L("[") << fileName << GS_L("]") << std::endl; ofs.close(); } } void FileLogger::WriteToErrorLog(const gs2d::str_type::string& str) { static bool errorLogFileCreated = false; if (!errorLogFileCreated) { gs2d::str_type::ofstream ofs(GetErrorLogFileDirectory().c_str()); if (ofs.is_open()) { ofs << GS_L("[") << GetErrorLogFileDirectory() << GS_L("]") << std::endl; ofs.close(); } } AppendToFile(GetErrorLogFileDirectory(), str); errorLogFileCreated = true; } void FileLogger::WriteToWarningLog(const gs2d::str_type::string& str) { static bool warningLogFileCreated = false; if (!warningLogFileCreated) { gs2d::str_type::ofstream ofs(GetWarningLogFileDirectory().c_str()); if (ofs.is_open()) { ofs << GS_L("[") << GetWarningLogFileDirectory() << GS_L("]") << std::endl; ofs.close(); } } AppendToFile(GetWarningLogFileDirectory(), str); warningLogFileCreated = true; } bool FileLogger::Log(const gs2d::str_type::string& str, const TYPE& type) const { #if defined(WIN32) || defined(APPLE_IOS) || defined(MACOSX) GS2D_COUT << str << std::endl; if (type == ERROR) { GS2D_CERR << GS_L("\x07"); } #endif if (type == ERROR) WriteToErrorLog(str); else if (type == WARNING) WriteToWarningLog(str); #ifdef ANDROID switch (type) { case ERROR: case WARNING: LOGE(str.c_str()); break; default: LOGI(str.c_str()); } #endif return AppendToFile(m_fileName, str); } gs2d::str_type::string FileLogger::GetErrorLogFileDirectory() { return GetLogDirectory() + GS_L("_error.log.txt"); } gs2d::str_type::string FileLogger::GetWarningLogFileDirectory() { return GetLogDirectory() + GS_L("_warning.log.txt"); } } // namespace Platform
[ "andre.santee@gmail.com" ]
andre.santee@gmail.com
c9f95253dafc7cda07c1917395e78a64ea4bf200
9da03771c40f9861931f157752ca23085b498070
/onwindow.h
bf8e475ed2d54900c35b53090e13ca55d9b47a78
[]
no_license
jl2/ONView
ef4ad356bc3b2c6cfdb3125db349306bb16e7fce
59f7e39d257afce6bba42fb5e11a6f2117df371a
refs/heads/master
2020-12-25T18:20:43.916652
2011-07-01T23:38:32
2011-07-01T23:38:32
1,951,110
2
1
null
null
null
null
UTF-8
C++
false
false
1,691
h
/* onwindow.h Copyright (c) 2011, Jeremiah LaRocco jeremiah.larocco@gmail.com Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef ONWINDOW_H #define ONWINDOW_H #include <QMainWindow> #include <QDateTime> #include <ctime> #include "onwidget.h" class QAction; class QLabel; class QIcon; class QMenu; class QCloseEvent; class QSettings; class QTimer; class ONWindow : public QMainWindow { Q_OBJECT; public: ONWindow(); ~ONWindow(); private slots: void openFile(); void about(); void startTimer(); void update(); protected: // Initialization functions void createActions(); void createMenus(); void closeEvent(QCloseEvent *event); private: QAction *aboutAction; QAction *aboutQtAction; QAction *quitAction; QAction *openAction; QAction *timeAction; QMenu *fileMenu; QMenu *optionsMenu; QMenu *helpMenu; QSettings *qset; std::time_t start_time; QTimer *theTimer; ONWidget *onwid; }; #endif
[ "jeremiah.larocco@gmail.com" ]
jeremiah.larocco@gmail.com
ac46744312d9cea46cf58a187998ee7c29b4ea71
382a482a30d13668c909734e0082d4a3025aa6db
/Stepik/C++1/3.3.10/3.3.10.cpp
3560856f96b110fb23f1699d3aea51f7805451eb
[]
no_license
Decorus2009/Study
e7b04aed5e1953901584a20892d3fec0389227a5
685773f16737119a0f5cfc6a5a107335731cb310
refs/heads/master
2021-09-05T09:06:56.741786
2018-01-25T22:36:09
2018-01-25T22:36:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include <cstddef> // size_t #include <cstring> // strlen, strcpy struct String { String(const char *str = "") : size(strlen(str)), str(strcpy(new char[size + 1], str)) {} size_t size; char *str; };
[ "Decorus2009@mail.ru" ]
Decorus2009@mail.ru
a9ee4eefef33beb1ecea21c24fead8f1faed90e3
ae01bf4d128384d158f6c60f342a6a1b0a32fc29
/Q1009/1009.cpp
85cc4eb5c9c7bd0bde40e6f2f1be08c675e2252a
[]
no_license
AliTaheriNastooh/LightOJ_Problem
17809cecea225c1c75ba77e4037d1d43172f1d61
7f0e62c92a6040c985dcb2d0663e6abd0d3c8000
refs/heads/master
2021-04-29T12:07:56.615461
2018-02-16T07:15:49
2018-02-16T07:15:49
121,723,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
cpp
#include <iostream> #include <cstdio> #include <vector> using namespace std; vector <int> v[20001]; int y[2],p=0; void fun(int x) { int k,f=1; for(int i=0;i<v[x].size();i++) if(v[x][i]) { k=v[x][i]; v[x][i]=0; f=1; for(int j=0;j<v[k].size();j++) if(v[k][j]==0) {f=0;break;} for(int j=0;j<v[k].size();j++) if(v[k][j]==x) {v[k][j]=0;break;} if(f) y[p]++; p = (p==0) ? 1 : 0; fun(k); } p = (p==0) ? 1 : 0; v[x].clear(); } int main() { int t,n,m=0; cin>>t; for(int k=0;k<t;k++) { cin>>n; for(int i=0;i<n;i++) { int a,b; scanf("%d %d",&a,&b); v[a].push_back(b); v[b].push_back(a); } for(int i=1;i<20001;i++) { if(v[i].size()) { y[0]=1;y[1]=0;p=1; fun(i); m+=max(y[0],y[1]); } } cout<<"Case "<<k+1<<": "<<m<<endl; m=0; } return 0; }
[ "ali.taherinastooh@gmail.com" ]
ali.taherinastooh@gmail.com
c3c018c8d84d01489c379cfa5d265454af594a3d
776acfe7bc591edcb00a8357a4845f5cadfa6b86
/2017/exam_prep/pokerchips/pokerchips.cpp
d7406893b3a08aac37025a8b351d72b5603c459e
[]
no_license
ybieri/algolab
dcf0b74577b58b018e0d6f16b147260a793332cb
09eb70a6266995cdbb58b44f60239dcbc84f0c78
refs/heads/master
2020-03-06T20:00:57.294982
2018-03-27T21:19:26
2018-03-27T21:19:26
127,042,966
0
0
null
null
null
null
UTF-8
C++
false
false
2,209
cpp
#include <iostream> #include <vector> #include <queue> #include <tuple> #include <cmath> #include <climits> #include <algorithm> using namespace std; typedef vector<int> v1; typedef vector<v1> v2; typedef vector<v2> v3; typedef vector<v3> v4; typedef vector<v4> v5; int round(v2& stacks, v5& table, v1& top_element){ if(table[top_element[0]][top_element[1]][top_element[2]][top_element[3]][top_element[4]] == -1){ int maxval = -1; //form all sets 2^5 = 32 for(int i=0; i<32; ++i){ bool valid = true; int color = -1; int removed = 0; v1 new_top(5, 0); // go throug all stacks for(int j=0; j<5; ++j){ if(i>>j&1){ //current stack has a 1. we take an element from it if(top_element[j] == 0){ valid = false; break; } if(color == -1){ //cout <<"color -1" << endl; color = stacks[j][top_element[j]-1]; }else if(color != stacks[j][top_element[j]-1]){ //cout << "color neq" << endl; valid = false; break; } ++removed; new_top[j] = top_element[j] - 1; }else{ new_top[j] = top_element[j]; } } if(top_element == new_top){ }else{ int point = 0; if(removed > 1){ point = pow(2, removed-2); } int maxpts = point + round(stacks, table, new_top); maxval = std::max(maxval, maxpts); } } table[top_element[0]][top_element[1]][top_element[2]][top_element[3]][top_element[4]] = maxval; } return table[top_element[0]][top_element[1]][top_element[2]][top_element[3]][top_element[4]]; } void do_testcases(){ int n; cin >> n; // num stacks vector<int> stacksize(5, 0); vector<int> top_elem(5, 0); for(int i=0; i<n; ++i){ cin >> stacksize[i]; top_elem[i] = stacksize[i]; } v2 stacks; stacks.reserve(n); for(int i=0; i<n; ++i){ stacks.push_back(vector<int>(stacksize[i], -1)); for(int j=0; j<stacksize[i]; ++j){ cin >> stacks[i][j]; } } v5 table(stacksize[0]+1, v4(stacksize[1]+1, v3(stacksize[2]+1, v2(stacksize[3]+1, v1(stacksize[4]+1, -1))))); table[0][0][0][0][0] = 0; cout << round(stacks, table, top_elem) << endl ; } int main(){ ios_base::sync_with_stdio(false); int t; cin >> t; while(t--) do_testcases(); return 0; }
[ "bieriy@student.ethz.ch" ]
bieriy@student.ethz.ch
f1adc0a95bfe6f3c632733d7a182cc785d4e14a7
a09274b324f25cf167090f6b75b3f5eb56a6e1b5
/1/7hw/3/myString.cpp
9971f26843637e41a3a81a793095d988a6e22c8a
[]
no_license
shurik111333/homework
e409ddd5a0250c9544b2513ecf6c38a1ba98e65c
7a97089572f1c316fd2bae620bfba8ff796822f1
refs/heads/master
2020-05-21T12:33:33.080528
2017-06-03T09:44:52
2017-06-03T09:44:52
47,825,887
1
1
null
2017-06-03T09:44:53
2015-12-11T12:36:12
C++
UTF-8
C++
false
false
3,613
cpp
#include "myString.h" #include <cstring> int min(int a, int b); char *String::initValue(const char *string) { char *value = new char[length + 1]; for (int i = 0; i < length; i++) { value[i] = string[i]; } value[length] = '\0'; return value; } String::String(const String *string) :length(string->length), value(initValue(string->value)) {} String::String(const char *newString) :length(std::strlen(newString)), value(initValue(newString)) {} String::String (const char *newString, int length) :length(length), value(initValue(newString)) {} String::~String() { delete[] this->value; } void String::skipEqual(const String &str1, const String &str2, int &index) const { while (index < min(str1.length, str2.length) && str1.value[index] == str2.value[index]) { index++; } } bool String::operator ==(const String &string) const { int index = 0; skipEqual(*this, string, index); return (index == min(this->length, string.length) && this->length == string.length); } bool String::operator !=(const String &string) const { return !(*this == string); } bool String::operator <(const String &string) const { int index = 0; skipEqual(*this, string, index); return (index == min(this->length, string.length) && this->length < string.length) || (index < min(this->length, string.length) && this->value[index] < string.value[index]); } bool String::operator >(const String &string) const { return string < *this; } std::ostream &operator <<(std::ostream &out, const String &string) { if (!isEmpty(&string)) out << string.value; return out; } int length(char *string) { int result = 0; while (string[result] != '\0') { result++; } return result; } int length(const String *string) { return string == nullptr ? 0 : string->length; } const int p = 53; const int module = 1000000000 + 7; int getHash(const String *string) { long long result = (unsigned char)string->value[0]; for (int i = 1; i < length(string); i++) { result = (result * p + (unsigned char)string->value[i]) % module; } return result; } char getChar(String *string, int index) { return index < length(string) ? string->value[index] : '\0'; } String *clone(const String *string) { return new String(string); } String *concat(String *string, const String *stringToConcat) { int newLength = length(string) + length(stringToConcat); char *newString = new char[newLength + 1]; for (int i = 0; i < length(string); i++) { newString[i] = string->value[i]; } for (int i = 0; i < length(stringToConcat); i++) { newString[i + length(string)] = stringToConcat->value[i]; } newString[newLength] = '\0'; delete string; string = new String(newString, newLength); return string; } int min(int a, int b) { return a < b ? a : b; } bool isEmpty(const String *string) { return length(string) == 0; } String *substring(const String *string, int start, int length) { int newLength = min(length, string->length - start); char *substr = new char[newLength + 1]; for (int i = start; i < start + newLength; i++) { substr[i - start] = string->value[i]; } substr[newLength] = '\0'; return new String(substr, newLength); } char *stringToChar(const String *string) { char *result = new char[length(string) + 1]; for (int i = 0; i < length(string); i++) { result[i] = string->value[i]; } result[length(string)] = '\0'; return result; }
[ "chudov.aleksandr94@gmail.com" ]
chudov.aleksandr94@gmail.com
0fa6e75b1d91bd5737c0e96880042ceb8460252b
6e57bdc0a6cd18f9f546559875256c4570256c45
/external/tensorflow/tensorflow/contrib/lite/model.h
26ce192a1e3c445925fa7b9bda405c0944aa678f
[ "Apache-2.0" ]
permissive
dongdong331/test
969d6e945f7f21a5819cd1d5f536d12c552e825c
2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e
refs/heads/master
2023-03-07T06:56:55.210503
2020-12-07T04:15:33
2020-12-07T04:15:33
134,398,935
2
1
null
2022-11-21T07:53:41
2018-05-22T10:26:42
null
UTF-8
C++
false
false
7,906
h
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Deserialization infrastructure for tflite. Provides functionality // to go from a serialized tflite model in flatbuffer format to an // interpreter. // // using namespace tflite; // StderrReporter error_reporter; // auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite", // &error_reporter); // MyOpResolver resolver; // You need to subclass OpResolver to provide // // implementations. // InterpreterBuilder builder(*model, resolver); // std::unique_ptr<Interpreter> interpreter; // if(builder(&interpreter) == kTfLiteOk) { // .. run model inference with interpreter // } // // OpResolver must be defined to provide your kernel implementations to the // interpreter. This is environment specific and may consist of just the builtin // ops, or some custom operators you defined to extend tflite. #ifndef TENSORFLOW_CONTRIB_LITE_MODEL_H_ #define TENSORFLOW_CONTRIB_LITE_MODEL_H_ #include <memory> #include "tensorflow/contrib/lite/error_reporter.h" #include "tensorflow/contrib/lite/interpreter.h" #include "tensorflow/contrib/lite/schema/schema_generated.h" namespace tflite { // An RAII object that represents a read-only tflite model, copied from disk, // or mmapped. This uses flatbuffers as the serialization format. class FlatBufferModel { public: // Builds a model based on a file. Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> BuildFromFile( const char* filename, ErrorReporter* error_reporter = DefaultErrorReporter()); // Builds a model based on a pre-loaded flatbuffer. The caller retains // ownership of the buffer and should keep it alive until the returned object // is destroyed. Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> BuildFromBuffer( const char* buffer, size_t buffer_size, ErrorReporter* error_reporter = DefaultErrorReporter()); // Builds a model directly from a flatbuffer pointer. The caller retains // ownership of the buffer and should keep it alive until the returned object // is destroyed. Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> BuildFromModel( const tflite::Model* model_spec, ErrorReporter* error_reporter = DefaultErrorReporter()); // Releases memory or unmaps mmaped meory. ~FlatBufferModel(); // Copying or assignment is disallowed to simplify ownership semantics. FlatBufferModel(const FlatBufferModel&) = delete; FlatBufferModel& operator=(const FlatBufferModel&) = delete; bool initialized() const { return model_ != nullptr; } const tflite::Model* operator->() const { return model_; } const tflite::Model* GetModel() const { return model_; } ErrorReporter* error_reporter() const { return error_reporter_; } const Allocation* allocation() const { return allocation_; } // Returns true if the model identifier is correct (otherwise false and // reports an error). bool CheckModelIdentifier() const; private: // Loads a model from `filename`. If `mmap_file` is true then use mmap, // otherwise make a copy of the model in a buffer. // // Note, if `error_reporter` is null, then a DefaultErrorReporter() will be // used. explicit FlatBufferModel( const char* filename, bool mmap_file = true, ErrorReporter* error_reporter = DefaultErrorReporter(), bool use_nnapi = false); // Loads a model from `ptr` and `num_bytes` of the model file. The `ptr` has // to remain alive and unchanged until the end of this flatbuffermodel's // lifetime. // // Note, if `error_reporter` is null, then a DefaultErrorReporter() will be // used. FlatBufferModel(const char* ptr, size_t num_bytes, ErrorReporter* error_reporter = DefaultErrorReporter()); // Loads a model from Model flatbuffer. The `model` has to remain alive and // unchanged until the end of this flatbuffermodel's lifetime. FlatBufferModel(const Model* model, ErrorReporter* error_reporter); // Flatbuffer traverser pointer. (Model* is a pointer that is within the // allocated memory of the data allocated by allocation's internals. const tflite::Model* model_ = nullptr; ErrorReporter* error_reporter_; Allocation* allocation_ = nullptr; }; // Abstract interface that returns TfLiteRegistrations given op codes or custom // op names. This is the mechanism that ops being referenced in the flatbuffer // model are mapped to executable function pointers (TfLiteRegistrations). class OpResolver { public: // Finds the op registration for a builtin operator by enum code. virtual TfLiteRegistration* FindOp(tflite::BuiltinOperator op) const = 0; // Finds the op registration of a custom operator by op name. virtual TfLiteRegistration* FindOp(const char* op) const = 0; virtual ~OpResolver() {} }; // Build an interpreter capable of interpreting `model`. // // model: a scoped model whose lifetime must be at least as long as // the interpreter. In principle multiple interpreters can be made from // a single model. // op_resolver: An instance that implements the Resolver interface which maps // custom op names and builtin op codes to op registrations. // reportError: a functor that is called to report errors that handles // printf var arg semantics. The lifetime of the reportError object must // be greater than or equal to the Interpreter created by operator(). // // Returns a kTfLiteOk when successful and sets interpreter to a valid // Interpreter. Note: the user must ensure the model lifetime is at least as // long as interpreter's lifetime. class InterpreterBuilder { public: InterpreterBuilder(const FlatBufferModel& model, const OpResolver& op_resolver); // Builds an interpreter given only the raw flatbuffer Model object (instead // of a FlatBufferModel). Mostly used for testing. // If `error_reporter` is null, then DefaultErrorReporter() is used. InterpreterBuilder(const ::tflite::Model* model, const OpResolver& op_resolver, ErrorReporter* error_reporter = DefaultErrorReporter()); InterpreterBuilder(const InterpreterBuilder&) = delete; InterpreterBuilder& operator=(const InterpreterBuilder&) = delete; TfLiteStatus operator()(std::unique_ptr<Interpreter>* interpreter); TfLiteStatus operator()(std::unique_ptr<Interpreter>* interpreter, int num_threads); private: TfLiteStatus BuildLocalIndexToRegistrationMapping(); TfLiteStatus ParseNodes( const flatbuffers::Vector<flatbuffers::Offset<Operator>>* operators, Interpreter* interpreter); TfLiteStatus ParseTensors( const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers, const flatbuffers::Vector<flatbuffers::Offset<Tensor>>* tensors, Interpreter* interpreter); const ::tflite::Model* model_; const OpResolver& op_resolver_; ErrorReporter* error_reporter_; std::vector<TfLiteRegistration*> flatbuffer_op_index_to_registration_; std::vector<BuiltinOperator> flatbuffer_op_index_to_registration_types_; const Allocation* allocation_ = nullptr; }; } // namespace tflite #endif // TENSORFLOW_CONTRIB_LITE_MODEL_H_
[ "dongdong331@163.com" ]
dongdong331@163.com
9f18fed46e7a4a42dc390cd4aa10ab2fe6c6194c
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/Facepunch.Steamworks/SteamAppUninstalled_t.h
79eb5a027e68599c605c934ef0b7c64758d8dcdb
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
191
h
#pragma once namespace SteamNative { class SteamAppUninstalled_t : public ValueType // 0x0 { public: unsigned int AppID; // 0x10 (size: 0x4, flags: 0x6, type: 0x9) }; // size = 0x18 }
[ "info@cvm-solutions.co.uk" ]
info@cvm-solutions.co.uk
3d5dbf7d38f004b7a9aaa5967582a033ee76062a
aa9dd90ce0331880920dba05c4594051b928b897
/FramedTransform.h
4da2cd13c30cf9d781720fddc4f0a0ecf8daebe8
[]
no_license
Spoonman376/GraphOptimizerTest
971a3d9d1268af3b14369f467d42d3a7d6bdb400
6efed13b1ab7073fad740c95643528d288bf9ddf
refs/heads/master
2020-11-29T23:59:02.644397
2017-07-04T19:39:13
2017-07-04T19:39:13
96,248,165
0
0
null
null
null
null
UTF-8
C++
false
false
892
h
// // #ifndef FramedTransform_h #define FramedTransform_h #include <Eigen/Core> #include <Eigen/Dense> #include <stdio.h> #include <vector> struct FramedTransformation { public: int id1, id2, frame; Eigen::Matrix4d transformation; FramedTransformation(int i1, int i2, int f, Eigen::Matrix4d t); }; typedef Eigen::Matrix<double, 6, 6, Eigen::RowMajor> InformationMatrix; struct FramedInformation { public: int id1, id2, frame; InformationMatrix information; FramedInformation(int i1, int i2, int f, InformationMatrix t); }; struct RGBDTrajectory { std::vector<FramedTransformation> data; int index; void saveToFile(std::string filename); void loadFromFile(std::string filename); }; struct RGBDInformation { std::vector<FramedInformation> data; void loadFromFile(std::string filename); void saveToFile(std::string filename); }; #endif /* FramedTransform_h */
[ "erik@anarchy-2.local" ]
erik@anarchy-2.local
d9726c4b25bbaabc35064dd86a30f8e72431c59e
903379d1c3610c4d766499400c019e677893294c
/Sources/WebCrowler/Google_tests/lib/googletest/test/googletest-param-test-invalid-name1-test_.cc
7fc17654675a8f5047f46731f8b638ae8139aeef
[ "BSD-3-Clause" ]
permissive
EvilBorsch/FindFace
aa0a52d9c194d5e7d91fabd96a1e18c534a5168b
6001a90e24f45e9f2fa284c3e08655a4b68318fd
refs/heads/master
2022-12-05T07:43:00.588763
2020-04-17T13:07:20
2020-04-17T13:07:20
220,627,746
4
2
null
2022-11-22T05:00:55
2019-11-09T10:44:41
C++
UTF-8
C++
false
false
2,070
cc
// Copyright 2015, Google 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 the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "gtest/gtest.h" namespace { class DummyTest : public ::testing::TestWithParam<const char *> { }; TEST_P(DummyTest, Dummy ) { } INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest, ::testing::Values("InvalidWithQuotes"), ::testing::PrintToStringParamName() ); } // namespace int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "pingvin1959@yandex.ru" ]
pingvin1959@yandex.ru
5cd516f2cc3b295e2d9804161385cfc6c288556b
c32b9b623fc526c8394aa4316eaca719718142a7
/Break It/SPECK/CryptoProjSubmit/CryptoProjSubmit/speck.cpp
444e930e37b7b5dbb7b658257700088f1db7fe94
[ "MIT" ]
permissive
codycann/eecs475_dsa
358190ada878bf53b218b2c6fe0b3d66ce9b5243
b5c4b3d11a4e7af7a9404414c86d08bb24daac22
refs/heads/master
2020-05-18T21:00:20.682064
2014-04-25T09:04:02
2014-04-25T09:04:02
18,195,353
0
1
null
null
null
null
UTF-8
C++
false
false
676
cpp
// Team: 32 (The Muffin Men) // Name: Anthony Chiang, Eric Edmond, Steven Louie // Uniqname: aycc, eedmond, slouie #include "speck.hpp" #include "utility.hpp" int main(int argc, char *argv[]) { /* Run with one of the following options Note that all arguments should be in base-16 format ./speck_cipher keygen ./speck_cipher encrypt keyword1 keyword0 plaintext1 plaintext0 ./speck_cipher decrypt keyword1 keyword0 ciphertext1 ciphertext0 Output from each of the three options: keygen -> keyword1 keyword0 encrypt -> ciphertext1 ciphertext0 decrypt -> plaintext1 plaintext0 */ return run_speck(argc,argv); }
[ "kevin@krakauer.org" ]
kevin@krakauer.org
f7f08e94dcf87ade31c5e5f8a29f4051910387b9
19b1d6cd253aeb809349769b073f4504c16bbc86
/withoutMain.cpp
de9cd318be3715c529708b2fbb3d4fa28abfe730
[]
no_license
harshkasyap/LearnCPlusPlus
ef10338d3b298d19de6c06e68f60e39994898d7a
bfdadf87f9c54a9090452d364a319207842cab02
refs/heads/master
2020-07-25T21:53:55.921129
2019-09-14T12:14:02
2019-09-14T12:14:02
208,433,604
0
0
null
null
null
null
UTF-8
C++
false
false
134
cpp
#include <iostream> using namespace std; extern void _exit(register int); int _start() { cout << "Hello World"; _exit(0); }
[ "harshkasyap@gmail.com" ]
harshkasyap@gmail.com
b3b08b66757cb68ea6b0810c115692ea3d6eef19
ba98197d69bb4b9390a94750556d0bc07c163eae
/Source/Engine/Animators/Data/AnimationSubGeometry.h
f45ccf71697199778749be9a093550d599f19cb3
[ "MIT" ]
permissive
daiwei1999/AwayCPP
a229389369e01e1b80a27ff684723d234dbba030
095a994bdd85982ffffd99a9461cbefb57499ccb
refs/heads/master
2023-07-20T19:42:32.741480
2023-07-05T09:10:26
2023-07-05T09:10:26
36,792,672
12
6
null
null
null
null
UTF-8
C++
false
false
778
h
#pragma once #include "Common.h" AWAY_NAMESPACE_BEGIN class AnimationSubGeometry { public: AnimationSubGeometry(); float* getVertexData() { return m_vertexData; } int getVertexCount() { return m_numVertices; } int getTotalLenOfOneVertex() { return m_totalLenOfOneVertex; } void createVertexData(int numVertices, int totalLenOfOneVertex); void activateVertexBuffer(int index, int bufferOffset, IContext* context, VertexBufferFormat format); void invalidateBuffer(); public: float m_previousTime; int m_numProcessedVertices; std::vector<ParticleAnimationData*> m_animationParticles; private: float* m_vertexData; VertexBuffer* m_vertexBuffer; IContext* m_bufferContext; bool m_bufferDirty; int m_numVertices; int m_totalLenOfOneVertex; }; AWAY_NAMESPACE_END
[ "daiwei_1999_82@163.com" ]
daiwei_1999_82@163.com
8933e996d44158007e4b426982927c75a676b17d
27713285271ea578d5977c61ce2c8f1d7ae24452
/Robots/RobotManager.cpp
0292d3bcf669dd548f45c04f55554995ef5904b9
[]
no_license
hw233/xiangjingchuangshuo_server-c-
18d907db95042169c00e74c9f2fccf24134455e3
84cc615d9571a717b1b3ee6decd85101c712db83
refs/heads/master
2020-04-09T16:17:11.460132
2018-09-25T03:02:05
2018-09-25T03:02:05
160,449,545
0
1
null
null
null
null
UTF-8
C++
false
false
3,574
cpp
#include "RobotManager.h" #include "xNetProcessor.h" #include "Robot.h" #include "xLuaTable.h" RobotManager::RobotManager():m_oOneSecTimer(1), m_eFuncType(EFUNCTYPE_SKILL) { } RobotManager::~RobotManager() { } bool RobotManager::add(Robot *robot) { if (!robot) return false; return addEntry(robot); } bool RobotManager::del(Robot *robot) { if (!robot) return false; removeEntry(robot); SAFE_DELETE(robot); return true; } void RobotManager::timer() { DWORD cur = now(); if (m_oOneSecTimer.timeUp(cur)) { for (auto &it : xEntryID::ets_) { Robot *pRobot = (Robot *)it.second; if (pRobot) { pRobot->timer(cur); } } } } void RobotManager::process() { xNetProcessor *np; for (auto &it : xEntryID::ets_) { Robot *pRobot = (Robot *)it.second; if (pRobot) { np = pRobot->m_pTask; if (np) { CmdPair *pair = np->getCmd(); while (pair) { if (!pRobot->doServerCmd((xCommand *)(pair->second), pair->first)) { XDBG << "[Robot消息处理]" << pRobot->id << pRobot->name << "error," << ((xCommand *)(pair->second))->cmd << ((xCommand *)(pair->second))->param << XEND; // std::cout << pRobot->id << " 消息处理错误:" << (DWORD)((xCommand *)(pair->second))->cmd << "," << (DWORD)((xCommand *)(pair->second))->param << "," << pair->first << std::endl; } // std::cout << pRobot->id << " 消息处理:" << (DWORD)((xCommand *)(pair->second))->cmd << "," << (DWORD)((xCommand *)(pair->second))->param << "," << pair->first << std::endl; np->popCmd(); pair = np->getCmd(); } } } } } void RobotManager::onClose(xNetProcessor* np) { if (!np) return; for (auto &it : xEntryID::ets_) { Robot *pRobot = (Robot *)it.second; if (pRobot->m_pTask == np) { pRobot->m_pTask = nullptr; XLOG << "[连接]" << pRobot->id << pRobot->m_dwRegionID << "关闭游戏服连接" << XEND; return; } } } void RobotManager::init() { if (!loadConfig()) return; if (!loadData()) return; } bool RobotManager::loadConfig() { if (!xLuaTable::getMe().open("robot.lua")) { XERR<<"[RobotManager] load robot.lua failed!"<<XEND; return false; } xLuaData data; xLuaTable::getMe().getLuaData("ParamList", data); m_strProxyIp = data.getTableString("proxy_ip"); m_dwProxyPort = data.getTableInt("proxy_port"); m_dwZoneId = data.getTableInt("zone_id"); m_qwAccId = data.getTableInt("acc_id"); m_dwCount = data.getTableInt("count"); m_dwMapID = data.getTableInt("mapid"); m_dwRange = data.getTableInt("range"); m_eFuncType = static_cast<EFuncType>(data.getTableInt("func_type")); xLuaData& pos = data.getMutableData("pos"); m_posCenter.set_x(pos.getTableInt("1")); m_posCenter.set_y(pos.getTableInt("2")); m_posCenter.set_z(pos.getTableInt("3")); return true; } bool RobotManager::loadData() { if (m_strProxyIp.empty() || !m_dwProxyPort || !m_dwZoneId || !m_dwCount || !m_qwAccId) { XERR << "[RobotManager] loadData failed! robot.lua config error!" << XEND; return false; } for (DWORD index=0; index<m_dwCount; index++) { Robot *pRobot = new Robot(m_qwAccId+index, m_dwZoneId); add(pRobot); } return true; } void RobotManager::getScenePos(Cmd::ScenePos& pos) { pos.set_x(randBetween(m_posCenter.x() - m_dwRange, m_posCenter.x() + m_dwRange)); pos.set_z(randBetween(m_posCenter.z() - m_dwRange, m_posCenter.z() + m_dwRange)); pos.set_y(m_posCenter.y()); }
[ "changjiangk@126.com" ]
changjiangk@126.com
701b39c655a5f4431c89f8ae743f959c1b2a3e47
fb689146cc19e1113e095e6dfd12f8b73177b22f
/include/deal.II/lac/compressed_simple_sparsity_pattern.h
5f9f5055597d208c9316adb29db3b2cb8ab423cf
[]
no_license
qsnake/deal.II
0418a4c9371e2630a0fce65b8de3529fa168d675
79c0458c8cc3fa03e5d89357a53a4f9397ead5c3
refs/heads/master
2021-01-01T15:55:27.801304
2012-07-27T13:31:57
2012-07-27T14:16:10
5,205,180
3
1
null
null
null
null
UTF-8
C++
false
false
19,185
h
//--------------------------------------------------------------------------- // $Id: compressed_simple_sparsity_pattern.h 23944 2011-07-12 12:23:28Z bangerth $ // // Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #ifndef __deal2__compressed_simple_sparsity_pattern_h #define __deal2__compressed_simple_sparsity_pattern_h #include <deal.II/base/config.h> #include <deal.II/base/subscriptor.h> #include <deal.II/base/utilities.h> #include <deal.II/lac/exceptions.h> #include <deal.II/base/index_set.h> #include <vector> #include <algorithm> #include <iostream> DEAL_II_NAMESPACE_OPEN template <typename number> class SparseMatrix; /*! @addtogroup Sparsity *@{ */ /** * This class acts as an intermediate form of the * SparsityPattern class. From the interface it mostly * represents a SparsityPattern object that is kept compressed * at all times. However, since the final sparsity pattern is not * known while constructing it, keeping the pattern compressed at all * times can only be achieved at the expense of either increased * memory or run time consumption upon use. The main purpose of this * class is to avoid some memory bottlenecks, so we chose to implement * it memory conservative. The chosen data format is too unsuited * to be used for actual matrices, though. It is therefore necessary to first * copy the data of this object over to an object of type * SparsityPattern before using it in actual matrices. * * Another viewpoint is that this class does not need up front allocation of a * certain amount of memory, but grows as necessary. An extensive description * of sparsity patterns can be found in the documentation of the @ref Sparsity * module. * * This class is an example of the "dynamic" type of @ref Sparsity. * * <h3>Interface</h3> * * Since this class is intended as an intermediate replacement of the * SparsityPattern class, it has mostly the same interface, with * small changes where necessary. In particular, the add() * function, and the functions inquiring properties of the sparsity * pattern are the same. * * * <h3>Usage</h3> * * Use this class as follows: * @verbatim * CompressedSimpleSparsityPattern compressed_pattern (dof_handler.n_dofs()); * DoFTools::make_sparsity_pattern (dof_handler, * compressed_pattern); * constraints.condense (compressed_pattern); * * SparsityPattern sp; * sp.copy_from (compressed_pattern); * @endverbatim * * * <h3>Notes</h3> * * There are several, exchangeable variations of this class, see @ref Sparsity, * section '"Dynamic" or "compressed" sparsity patterns' for more information. * * @author Timo Heister, 2008 */ class CompressedSimpleSparsityPattern : public Subscriptor { public: /** * An iterator that can be used to * iterate over the elements of a single * row. The result of dereferencing such * an iterator is a column index. */ typedef std::vector<unsigned int>::const_iterator row_iterator; /** * Initialize the matrix empty, * that is with no memory * allocated. This is useful if * you want such objects as * member variables in other * classes. You can make the * structure usable by calling * the reinit() function. */ CompressedSimpleSparsityPattern (); /** * Copy constructor. This constructor is * only allowed to be called if the * matrix structure to be copied is * empty. This is so in order to prevent * involuntary copies of objects for * temporaries, which can use large * amounts of computing time. However, * copy constructors are needed if you * want to use the STL data types on * classes like this, e.g. to write such * statements like <tt>v.push_back * (CompressedSparsityPattern());</tt>, * with @p v a vector of @p * CompressedSparsityPattern objects. */ CompressedSimpleSparsityPattern (const CompressedSimpleSparsityPattern &); /** * Initialize a rectangular * matrix with @p m rows and * @p n columns. The @p rowset * restricts the storage to * elements in rows of this set. * Adding elements outside of * this set has no effect. The * default argument keeps all * entries. */ CompressedSimpleSparsityPattern (const unsigned int m, const unsigned int n, const IndexSet & rowset = IndexSet()); /** * Initialize a square matrix of * dimension @p n. */ CompressedSimpleSparsityPattern (const unsigned int n); /** * Copy operator. For this the * same holds as for the copy * constructor: it is declared, * defined and fine to be called, * but the latter only for empty * objects. */ CompressedSimpleSparsityPattern & operator = (const CompressedSimpleSparsityPattern &); /** * Reallocate memory and set up * data structures for a new * matrix with @p m rows and * @p n columns, with at most * max_entries_per_row() nonzero * entries per row. The @p rowset * restricts the storage to * elements in rows of this set. * Adding elements outside of * this set has no effect. The * default argument keeps all * entries. */ void reinit (const unsigned int m, const unsigned int n, const IndexSet & rowset = IndexSet()); /** * Since this object is kept * compressed at all times anway, * this function does nothing, * but is declared to make the * interface of this class as * much alike as that of the * SparsityPattern class. */ void compress (); /** * Return whether the object is * empty. It is empty if no * memory is allocated, which is * the same as that both * dimensions are zero. */ bool empty () const; /** * Return the maximum number of * entries per row. Note that * this number may change as * entries are added. */ unsigned int max_entries_per_row () const; /** * Add a nonzero entry to the * matrix. If the entry already * exists, nothing bad happens. */ void add (const unsigned int i, const unsigned int j); /** * Add several nonzero entries to the * specified row of the matrix. If the * entries already exist, nothing bad * happens. */ template <typename ForwardIterator> void add_entries (const unsigned int row, ForwardIterator begin, ForwardIterator end, const bool indices_are_unique_and_sorted = false); /** * Check if a value at a certain * position may be non-zero. */ bool exists (const unsigned int i, const unsigned int j) const; /** * Make the sparsity pattern * symmetric by adding the * sparsity pattern of the * transpose object. * * This function throws an * exception if the sparsity * pattern does not represent a * square matrix. */ void symmetrize (); /** * Print the sparsity of the * matrix. The output consists of * one line per row of the format * <tt>[i,j1,j2,j3,...]</tt>. <i>i</i> * is the row number and * <i>jn</i> are the allocated * columns in this row. */ void print (std::ostream &out) const; /** * Print the sparsity of the matrix in a * format that @p gnuplot understands and * which can be used to plot the sparsity * pattern in a graphical way. The format * consists of pairs <tt>i j</tt> of * nonzero elements, each representing * one entry of this matrix, one per line * of the output file. Indices are * counted from zero on, as usual. Since * sparsity patterns are printed in the * same way as matrices are displayed, we * print the negative of the column * index, which means that the * <tt>(0,0)</tt> element is in the top * left rather than in the bottom left * corner. * * Print the sparsity pattern in * gnuplot by setting the data style * to dots or points and use the * @p plot command. */ void print_gnuplot (std::ostream &out) const; /** * Return number of rows of this * matrix, which equals the dimension * of the image space. */ unsigned int n_rows () const; /** * Return number of columns of this * matrix, which equals the dimension * of the range space. */ unsigned int n_cols () const; /** * Number of entries in a * specific row. This function * can only be called if the * given row is a member of the * index set of rows that we want * to store. */ unsigned int row_length (const unsigned int row) const; /** * Access to column number field. * Return the column number of * the @p indexth entry in @p row. */ unsigned int column_number (const unsigned int row, const unsigned int index) const; /** * Return an iterator that can loop over * all entries in the given * row. Dereferencing the iterator yields * a column index. */ row_iterator row_begin (const unsigned int row) const; /** * Returns the end of the current row. */ row_iterator row_end (const unsigned int row) const; /** * Compute the bandwidth of the matrix * represented by this structure. The * bandwidth is the maximum of * $|i-j|$ for which the index pair * $(i,j)$ represents a nonzero entry * of the matrix. */ unsigned int bandwidth () const; /** * Return the number of nonzero elements * allocated through this sparsity pattern. */ unsigned int n_nonzero_elements () const; /** * Return the IndexSet that sets which * rows are active on the current * processor. It corresponds to the * IndexSet given to this class in the * constructor or in the reinit function. */ const IndexSet & row_index_set () const; /** * return whether this object stores only * those entries that have been added * explicitly, or if the sparsity pattern * contains elements that have been added * through other means (implicitly) while * building it. For the current class, * the result is always true. * * This function mainly serves the * purpose of describing the current * class in cases where several kinds of * sparsity patterns can be passed as * template arguments. */ static bool stores_only_added_elements (); /** * Determine an estimate for the * memory consumption (in bytes) * of this object. */ std::size_t memory_consumption () const; private: /** * Number of rows that this sparsity * structure shall represent. */ unsigned int rows; /** * Number of columns that this sparsity * structure shall represent. */ unsigned int cols; /** * A set that contains the valid rows. */ IndexSet rowset; /** * Store some data for each row * describing which entries of this row * are nonzero. Data is stored sorted in * the @p entries std::vector. * The vector per row is dynamically * growing upon insertion doubling its * memory each time. */ struct Line { public: /** * Storage for the column indices of * this row. This array is always * kept sorted. */ std::vector<unsigned int> entries; /** * Constructor. */ Line (); /** * Add the given column number to * this line. */ void add (const unsigned int col_num); /** * Add the columns specified by the * iterator range to this line. */ template <typename ForwardIterator> void add_entries (ForwardIterator begin, ForwardIterator end, const bool indices_are_sorted); /** * estimates memory consumption. */ std::size_t memory_consumption () const; }; /** * Actual data: store for each * row the set of nonzero * entries. */ std::vector<Line> lines; }; /*@}*/ /*---------------------- Inline functions -----------------------------------*/ inline void CompressedSimpleSparsityPattern::Line::add (const unsigned int j) { // first check the last element (or if line // is still empty) if ( (entries.size()==0) || ( entries.back() < j) ) { entries.push_back(j); return; } // do a binary search to find the place // where to insert: std::vector<unsigned int>::iterator it = Utilities::lower_bound(entries.begin(), entries.end(), j); // If this entry is a duplicate, exit // immediately if (*it == j) return; // Insert at the right place in the // vector. Vector grows automatically to // fit elements. Always doubles its size. entries.insert(it, j); } inline unsigned int CompressedSimpleSparsityPattern::n_rows () const { return rows; } inline unsigned int CompressedSimpleSparsityPattern::n_cols () const { return cols; } inline void CompressedSimpleSparsityPattern::add (const unsigned int i, const unsigned int j) { Assert (i<rows, ExcIndexRange(i, 0, rows)); Assert (j<cols, ExcIndexRange(j, 0, cols)); if (rowset.size() > 0 && !rowset.is_element(i)) return; const unsigned int rowindex = rowset.size()==0 ? i : rowset.index_within_set(i); lines[rowindex].add (j); } template <typename ForwardIterator> inline void CompressedSimpleSparsityPattern::add_entries (const unsigned int row, ForwardIterator begin, ForwardIterator end, const bool indices_are_sorted) { Assert (row < rows, ExcIndexRange (row, 0, rows)); if (rowset.size() > 0 && !rowset.is_element(row)) return; const unsigned int rowindex = rowset.size()==0 ? row : rowset.index_within_set(row); lines[rowindex].add_entries (begin, end, indices_are_sorted); } inline CompressedSimpleSparsityPattern::Line::Line () {} inline unsigned int CompressedSimpleSparsityPattern::row_length (const unsigned int row) const { Assert (row < n_rows(), ExcIndexRange (row, 0, n_rows())); if (rowset.size() > 0 && !rowset.is_element(row)) return 0; const unsigned int rowindex = rowset.size()==0 ? row : rowset.index_within_set(row); return lines[rowindex].entries.size(); } inline unsigned int CompressedSimpleSparsityPattern::column_number (const unsigned int row, const unsigned int index) const { Assert (row < n_rows(), ExcIndexRange (row, 0, n_rows())); Assert( rowset.size() == 0 || rowset.is_element(row), ExcInternalError()); const unsigned int local_row = rowset.size() ? rowset.index_within_set(row) : row; Assert (index < lines[local_row].entries.size(), ExcIndexRange (index, 0, lines[local_row].entries.size())); return lines[local_row].entries[index]; } inline CompressedSimpleSparsityPattern::row_iterator CompressedSimpleSparsityPattern::row_begin (const unsigned int row) const { Assert (row < n_rows(), ExcIndexRange (row, 0, n_rows())); const unsigned int local_row = rowset.size() ? rowset.index_within_set(row) : row; return lines[local_row].entries.begin(); } inline CompressedSimpleSparsityPattern::row_iterator CompressedSimpleSparsityPattern::row_end (const unsigned int row) const { Assert (row < n_rows(), ExcIndexRange (row, 0, n_rows())); const unsigned int local_row = rowset.size() ? rowset.index_within_set(row) : row; return lines[local_row].entries.end(); } inline const IndexSet & CompressedSimpleSparsityPattern::row_index_set () const { return rowset; } inline bool CompressedSimpleSparsityPattern::stores_only_added_elements () { return true; } DEAL_II_NAMESPACE_CLOSE #endif
[ "ondrej.certik@gmail.com" ]
ondrej.certik@gmail.com