blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
78657a2de8dc70b16c62e87f0bf06ea55cd41108
50466d79347d3ecef93ebf879a6c156142518dae
/src/util/principle_component_analysis.h
f76ba04a365675a978868a7af740435a2b5cd287
[ "MIT" ]
permissive
amadavan/OCR
6bb8a908452bc1e8fa89cf534dde3d668a00dead
05c323593302c9183005b067cdf1d48864727f29
refs/heads/master
2020-04-12T09:50:10.514272
2016-07-14T00:30:45
2016-07-14T00:30:45
60,293,536
0
0
null
null
null
null
UTF-8
C++
false
false
6,545
h
#ifndef OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_ #define OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_ #include <float.h> #include <cmath> #include <armadillo> #include "util/ocrtypes.h" namespace ocr { /** * A Principle Component Analysis (PCA) implementation. * * Defines an implementation of PCA with the ability to designate how the * projection is found and the reduced space. */ class PCA { public: /** * Default constructor for PCA uses automatic determination of dimensions * * Constructs the PCA object that will be used to determine the projections * of the original dataset to and from the reduced subspace. By default, it * determines the number of dimensions to retain based on analysis of the * amounnt of variability measured. */ PCA(); /** * Constructor for PCA providing a set number of reduced dimensions * * Constructs the PCA object with the number of dimensions to be included in * the reduced subspace. * * @param[in] num_reduced_dimensions number of dimensions to include in * reduced subspace */ PCA(int num_reduced_dimensions); /** * Consutuctor for PCA providing percent variability * * Constructs the PCA object while specifying the total percentage of * variability contained in the reduced subspace. * * @param[in] percent_variability percentage of original space's variability * contained in reduced subspace */ PCA(double percent_variability); ~PCA() {} /** * Trains the classifier given a dataset and known labels for the set * * Uses the known dataset and labels to generate the algorithm that will * later be used to predict the values of unknown data. This method should * be run prior to any testing methods (including test, test_batch...) * * @param[in] data_set nxm matrix with each entry in a column * @param[in] label_set mx1 vector of data_set labels */ void solve( const arma::mat &dataset ); /** * Determine the error rate for a given test set * * Computes the labels for a given dataset and compares to given known * labels. The resulting comparison is used to determine the overall * error rate of the algorithm for that dataset. This method assumes that * the training method has already been completed. * * @param[in] test_mat nxm matrix with each entry in a column * @param[in] true_labels mx1 column vector of true labels * @param[out] predicted_labels mx1 column vector of predicted labels * * @return fractional error rate */ arma::mat project( const arma::mat &mat, bool reverse = false ); /** * Set the PCA to solve for a specified percent variability * * Specifies a floating point value of variability that will be included in * the projection. This value represents a minimum bound and ensures that * at least this much variability is included in the projection. * * @param[in] variability Minimum percent variability in projection */ void set_percent_variability(double variability); /** * Returns the percent variability of the PCA solution or set-point * * Depending on the current state of the PCA solver, this can return two * different values. The first is if the PCA has not yet been solved. If * that is the case, this value will be the percent variability specified by * the user if they wish to use the variability dimension select mode, or * the default value of 0. Alternatively, if the algorithm has been run, * this will return the percent variability included in the data regardless * of algorithm used. * * @param[out] variability percentage variability included in PCA solution */ double get_percent_variability(); /** * Set the PCA to solve for a specified number of dimensions * * Defines a set number of dimensions to be included in the projection space * and to be solved for in the PCA. In other words, the top dimensions * eigenvectors will be included in the projection. * * @param[in] dimensions Number of dimensions to include in PCA projection */ void set_dimensions(uint32_t dimensions); /** * Returns number of dimensions in PCA * * Depending on whether or not the solve function has been run, this can * return two things. If solve was called and set_dimensions has not been * called since, this will return the number of dimensions that the solve * function reduced the dataset to. If set_dimensions has been called or * solve has not been called, this will return the value specified in the * constructor or set_dimensions. If no value was set, it defaults to 0. * * @param[out] n_dimensions Number of dimensions in PCA */ uint32_t get_dimensions(); /** * Use Minka's MLE to determine number of dimensions * * When performing a solve, the algorithm will determine the appropriate * number of dimensions by performing Minka's MLE that can be found here <a * href="https://uwaterloo.ca/data-science/sites/ca.data-science/files/ * uploads/files/automatic-dimensionality-selection-from-scree-plot-use-of- * profile-likelihood.pdf">here</a>. */ void set_auto_dimension(); private: /** * Enumeration of different ways of determining PCA dimensions * * Enumerated type that acts as a switch between different ways of * calculating the number of dimensions to be included in the PCA. These * include AUTO which uses Minka's MLE method, NUM_DIMENSIONS which sets a * number of dimensions, and PERCENT_VARIABILITY which defines a minimum * variability bound to be included in the projection. */ enum Mode { AUTO, NUM_DIMENSIONS, PERCENT_VARIABILITY }; arma::mat projection_matrix_; /// Matrix containing left-multiply projection uint32_t num_reduced_dimensions_; /// Number of dimensions double percent_variability_; // Percent variability Mode dimension_select_mode_; // Method of selecting number of dimensions /** * Return number of dimensions using Minka's MLE * * Performs Minka's MLE estimation that can be found here <a href="https://uwaterloo.ca/data-science/sites/ca.data-science/files/uploads/files/automatic-dimensionality-selection-from-scree-plot-use-of-profile-likelihood.pdf">here</a>. * Returns the Maximum Likelihood number of dimensions. * * @param[in] eigenvalues A list of eigenvalues in descending order * @param[in] n_samples Number of samples in dataset * @param[out] dimensions Maximum likelihood number of dimensions. */ size_t determine_dimensions(const arma::vec &eigenvalues, const size_t n_samples); }; } #endif // OCR_UTIL_PRINCIPLE_COMPONENT_ANALYSIS_H_
[ "avinash.madavan@gmail.com" ]
avinash.madavan@gmail.com
7308e633ac8e7b975aafc84e4cedcc06f85e4129
311bca02634b791b17a1cd6e2258d858c5ee8b70
/src/qt/coincontroldialog.cpp
0fa4a05cd9befc472e439984ff87caefea5daec5
[ "MIT" ]
permissive
ed-ro0t/C-Bit
65359b8eb1efbf3762d9c0375acd971e2352b38f
73bc5652564d344af6847eefde6d386225d4ad02
refs/heads/master
2020-03-09T06:57:08.468887
2017-09-04T00:40:41
2017-09-04T00:40:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,639
cpp
// Copyright (c) 2011-2015 The C-Bit Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "coincontrol.h" #include "init.h" #include "main.h" // For minRelayTxFee #include "wallet/wallet.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> QList<CAmount> CoinControlDialog::payAmounts; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); bool CoinControlDialog::fSubtractFeeFromAmount = false; bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const { int column = treeWidget()->sortColumn(); if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS) return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong(); return QTreeWidgetItem::operator<(other); } CoinControlDialog::CoinControlDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0), platformStyle(platformStyle) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290); ui->treeWidget->setColumnWidth(COLUMN_DATE, 110); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } void CoinControlDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(model, this); } } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, "")); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder); } else { if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else coinControl->Select(outpt); // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } // TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used. // Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473 #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority) { double dPriorityMedium = mempoolEstimatePriority; if (dPriorityMedium <= 0) dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded if (dPriority / 1000000 > dPriorityMedium) return tr("highest"); else if (dPriority / 100000 > dPriorityMedium) return tr("higher"); else if (dPriority / 10000 > dPriorityMedium) return tr("high"); else if (dPriority / 1000 > dPriorityMedium) return tr("medium-high"); else if (dPriority > dPriorityMedium) return tr("medium"); else if (dPriority * 10 > dPriorityMedium) return tr("low-medium"); else if (dPriority * 100 > dPriorityMedium) return tr("low"); else if (dPriority * 1000 > dPriorityMedium) return tr("lower"); else return tr("lowest"); } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { std::vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(::minRelayTxFee)) fDust = true; } } QString sPriorityLabel = tr("none"); CAmount nAmount = 0; CAmount nPayFee = 0; CAmount nAfterFee = 0; CAmount nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; bool fAllowFree = false; bool fWitness = false; std::vector<COutPoint> vCoinControl; std::vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput& out, vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if (model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); // Bytes CTxDestination address; int witnessversion = 0; std::vector<unsigned char> witnessprogram; if (out.tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4); fWitness = true; } else if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); if (keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here if (fWitness) { // there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact. // usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee. // also, the witness stack size value value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit. nBytes += 2; // account for the serialized marker and flag bytes nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input. } // Priority double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority); // in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate if (CoinControlDialog::fSubtractFeeFromAmount) if (nAmount - nPayAmount == 0) nBytes -= 34; // Fee nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); if (nPayFee > 0 && coinControl->nMinimumTotalFee > nPayFee) nPayFee = coinControl->nMinimumTotalFee; // Allow free? (require at least hard-coded threshold and default to that if no estimate) double dPriorityNeeded = std::max(mempoolEstimatePriority, AllowFreeThreshold()); fAllowFree = (dPriority >= dPriorityNeeded); if (fSendFreeTransactions) if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) nPayFee = 0; if (nPayAmount > 0) { nChange = nAmount - nPayAmount; if (!CoinControlDialog::fSubtractFeeFromAmount) nChange -= nPayFee; // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < MIN_CHANGE) { CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0)); if (txout.IsDust(::minRelayTxFee)) { if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust nChange = txout.GetDustThreshold(::minRelayTxFee); else { nPayFee += nChange; nChange = 0; } } } if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount) nBytes -= 34; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } // actually update labels int nDisplayUnit = BitcoinUnits::XCT; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText(fDust ? tr("yes") : tr("no")); // Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change if (nPayFee > 0 && (coinControl->nMinimumTotalFee < nPayFee)) { l3->setText(ASYMP_UTF8 + l3->text()); l4->setText(ASYMP_UTF8 + l4->text()); if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount) l8->setText(ASYMP_UTF8 + l8->text()); } // turn labels "red" l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : "");// Bytes >= 1000 l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes" // tool tips QString toolTip1 = tr("This label turns red if the transaction size is greater than 1000 bytes.") + "<br /><br />"; toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))) + "<br /><br />"; toolTip1 += tr("Can vary +/- 1 byte per input."); QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />"; toolTip2 += tr("This label turns red if the priority is smaller than \"medium\".") + "<br /><br />"; toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))); QString toolTip3 = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold."); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary; if (payTxFee.GetFeePerK() > 0) dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000; else { dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), mempool.estimateSmartFee(nTxConfirmTarget).GetFeePerK()) / 1000; } QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l5->setToolTip(toolTip1); l6->setToolTip(toolTip2); l7->setToolTip(toolTip3); l8->setToolTip(toolTip4); dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip()); dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip()); dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } CAmount nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; CCoinControlWidgetItem *itemOutput; if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress); else itemOutput = new CCoinControlWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); // if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes) } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->vout[out.i].nValue)); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime())); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth)); itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth)); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority)); itemOutput->setData(COLUMN_PRIORITY, Qt::UserRole, QVariant((qlonglong)dPriority)); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed")); } // set checkbox if (coinControl->IsSelected(COutPoint(txhash, out.i))) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum)); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority)); itemWalletAddress->setData(COLUMN_PRIORITY, Qt::UserRole, QVariant((qlonglong)dPrioritySum)); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); }
[ "crzybluebilly@mailinator.com" ]
crzybluebilly@mailinator.com
f1b1aba887bd9cb76922546fb171939381a2626e
2367a63e0e079a520ed998df0ba3de125b6b3460
/Translator_file/deal.II/matrix_free/matrix_free.h
7aa096fd8372640685b40473b3eb4a75964e9f40
[ "MIT" ]
permissive
jiaqiwang969/deal.ii-course-practice
e005804c506bc764b9e8a25a32b35d28b3fec203
0da5ad1537d8152549d8a0e4de5872efe7619c8a
refs/heads/master
2023-06-03T16:35:07.191106
2021-06-19T04:13:02
2021-06-19T04:13:02
369,974,242
0
0
MIT
2021-06-15T09:04:32
2021-05-23T06:05:42
C++
UTF-8
C++
false
false
191,413
h
//include/deal.II-translator/matrix_free/matrix_free_0.txt // --------------------------------------------------------------------- // // Copyright (C) 2011 - 2021 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.md at // the top level directory of deal.II. // // --------------------------------------------------------------------- #ifndef dealii_matrix_free_h #define dealii_matrix_free_h #include <deal.II/base/config.h> #include <deal.II/base/aligned_vector.h> #include <deal.II/base/exceptions.h> #include <deal.II/base/quadrature.h> #include <deal.II/base/template_constraints.h> #include <deal.II/base/thread_local_storage.h> #include <deal.II/base/vectorization.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/mapping.h> #include <deal.II/fe/mapping_q1.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/hp/mapping_collection.h> #include <deal.II/hp/q_collection.h> #include <deal.II/lac/affine_constraints.h> #include <deal.II/lac/block_vector_base.h> #include <deal.II/lac/la_parallel_vector.h> #include <deal.II/lac/vector_operation.h> #include <deal.II/matrix_free/dof_info.h> #include <deal.II/matrix_free/mapping_info.h> #include <deal.II/matrix_free/shape_info.h> #include <deal.II/matrix_free/task_info.h> #include <deal.II/matrix_free/type_traits.h> #include <cstdlib> #include <limits> #include <list> #include <memory> DEAL_II_NAMESPACE_OPEN /** * 这个类收集了所有为矩阵自由实现而存储的数据。这个存储方案是针对用相同数据进行的几个循环而定制的,也就是说,通常在同一个网格上做许多矩阵-向量乘积或残差计算。该类在 * step-37 和 step-48 中使用。 * 该类不实现任何涉及有限元基函数的操作,即关于对单元的操作。对于这些操作,FEEvaluation类被设计为使用该类中收集的数据。 * 存储的数据可以细分为三个主要部分。 * * * * - DoFInfo:它存储了局部自由度与全局自由度的关系。它包括对约束条件的描述,这些约束条件被评估为穿过一个单元上的所有局部自由度。 * * * * - MappingInfo:它存储了从实数到单位单元的转换,这些转换对于建立有限元函数的导数和找到物理空间中正交权重的位置是必要的。 * * * - ShapeInfo:它包含有限元的形状函数,在单元格上进行评估。 * 除了初始化程序,这个类只实现了一个单一的操作,即所有单元的循环(cell_loop())。这个循环的安排方式是,共享自由度的单元不会同时工作,这意味着可以并行地写入向量(或矩阵),而不必明确地同步访问这些向量和矩阵。这个类没有实现任何形状值,它所做的只是缓存相应的数据。要实现有限元操作,请使用FEEvaluation类(或一些相关的类)。 * 这个类以不同的顺序遍历单元,与deal.II中通常的Triangulation类不同,以便在共享内存和矢量化的并行化方面具有灵活性。 * 矢量化是通过将几个拓扑单元合并成一个所谓的宏观单元来实现的。这使得几个单元的所有相关操作都可以用一条CPU指令来实现,这也是这个框架的主要特点之一。 * 关于这个类的使用细节,见FEEvaluation的描述或 @ref matrixfree "无矩阵模块" * 。 * * * @ingroup matrixfree * */ template <int dim, typename Number = double, typename VectorizedArrayType = VectorizedArray<Number>> class MatrixFree : public Subscriptor { static_assert( std::is_same<Number, typename VectorizedArrayType::value_type>::value, "Type of Number and of VectorizedArrayType do not match."); public: /** * 由模板参数指定的底层数字类型的别名。 * */ using value_type = Number; using vectorized_value_type = VectorizedArrayType; /** * 由模板参数`dim`设定的尺寸。 * */ static const unsigned int dimension = dim; /** * 收集用于MatrixFree类初始化的选项。第一个参数指定要使用的MPI通信器,第二个参数是共享内存中的并行化选项(基于任务的并行化,可以选择无并行化和避免访问相同向量项的单元同时被访问的三种方案),第三个参数是任务并行调度的块大小,第四个参数是这个类应该存储的更新标志。 * 第五个参数指定了三角形中的级别,索引将从该级别开始使用。如果级别设置为 * numbers::invalid_unsigned_int, * ,将遍历活动单元,否则将遍历指定级别的单元。这个选项在给出DoFHandler的情况下没有影响。 * 参数 @p initialize_plain_indices * 表示DoFInfo类是否也应该允许访问向量而不解决约束。 * 两个参数`initialize_indices`和`initialize_mapping`允许用户停用一些初始化过程。例如,如果只需要找到避免同时触及相同向量/矩阵指数的调度,就不需要初始化映射。同样,如果映射从一个迭代到下一个迭代发生了变化,但拓扑结构没有变化(比如使用MappingQEulerian的变形网格时),只需要初始化映射就足够了。 * 两个参数`cell_vectorization_categories`和`cell_vectorization_categories_strict`控制在几个单元上形成向量化的批次。它在使用hp-adaptivity时被隐含使用,但在其他情况下也很有用,比如在本地时间步进中,人们想控制哪些元素一起形成一批单元。数组`cell_vectorization_categories`在`mg_level`设置为 * `numbers::invalid_unsigned_int` * 的情况下,通过cell->active_cell_index()访问活动单元,对于水平单元则通过cell->index()访问。默认情况下,`cell_vectorization_category`中的不同类别可以混合使用,如果算法内部需要,允许算法将较低的类别数字与下一个较高的类别合并,以尽可能避免部分填充的SIMD通道。这样可以更好地利用矢量,但可能需要特殊处理,特别是对面积分。如果设置为 * @p true, * ,算法反而会将不同的类别分开,而不是将它们混合在一个矢量化数组中。 * */ struct AdditionalData { /** * 收集任务并行的选项。参见成员变量 * MatrixFree::AdditionalData::tasks_parallel_scheme * 的文档以获得详尽的描述。 * */ enum TasksParallelScheme { /** * 以串行方式执行应用。 * */ none = internal::MatrixFreeFunctions::TaskInfo::none, /** * 将单元格分成两层,之后形成块状。 * */ partition_partition = internal::MatrixFreeFunctions::TaskInfo::partition_partition, /** * 在全局层面进行分区,并对分区内的单元格进行着色。 * */ partition_color = internal::MatrixFreeFunctions::TaskInfo::partition_color, /** * 使用传统的着色算法:这就像 * TasksParallelScheme::partition_color, ,但只使用一个分区。 * */ color = internal::MatrixFreeFunctions::TaskInfo::color }; /** * 附加数据的构造函数。 * */ AdditionalData( const TasksParallelScheme tasks_parallel_scheme = partition_partition, const unsigned int tasks_block_size = 0, const UpdateFlags mapping_update_flags = update_gradients | update_JxW_values, const UpdateFlags mapping_update_flags_boundary_faces = update_default, const UpdateFlags mapping_update_flags_inner_faces = update_default, const UpdateFlags mapping_update_flags_faces_by_cells = update_default, const unsigned int mg_level = numbers::invalid_unsigned_int, const bool store_plain_indices = true, const bool initialize_indices = true, const bool initialize_mapping = true, const bool overlap_communication_computation = true, const bool hold_all_faces_to_owned_cells = false, const bool cell_vectorization_categories_strict = false) : tasks_parallel_scheme(tasks_parallel_scheme) , tasks_block_size(tasks_block_size) , mapping_update_flags(mapping_update_flags) , mapping_update_flags_boundary_faces(mapping_update_flags_boundary_faces) , mapping_update_flags_inner_faces(mapping_update_flags_inner_faces) , mapping_update_flags_faces_by_cells(mapping_update_flags_faces_by_cells) , mg_level(mg_level) , store_plain_indices(store_plain_indices) , initialize_indices(initialize_indices) , initialize_mapping(initialize_mapping) , overlap_communication_computation(overlap_communication_computation) , hold_all_faces_to_owned_cells(hold_all_faces_to_owned_cells) , cell_vectorization_categories_strict( cell_vectorization_categories_strict) , communicator_sm(MPI_COMM_SELF) {} /** * 复制构造器。 * */ AdditionalData(const AdditionalData &other) : tasks_parallel_scheme(other.tasks_parallel_scheme) , tasks_block_size(other.tasks_block_size) , mapping_update_flags(other.mapping_update_flags) , mapping_update_flags_boundary_faces( other.mapping_update_flags_boundary_faces) , mapping_update_flags_inner_faces(other.mapping_update_flags_inner_faces) , mapping_update_flags_faces_by_cells( other.mapping_update_flags_faces_by_cells) , mg_level(other.mg_level) , store_plain_indices(other.store_plain_indices) , initialize_indices(other.initialize_indices) , initialize_mapping(other.initialize_mapping) , overlap_communication_computation( other.overlap_communication_computation) , hold_all_faces_to_owned_cells(other.hold_all_faces_to_owned_cells) , cell_vectorization_category(other.cell_vectorization_category) , cell_vectorization_categories_strict( other.cell_vectorization_categories_strict) , communicator_sm(other.communicator_sm) {} /** * 拷贝赋值。 * */ AdditionalData & operator=(const AdditionalData &other) { tasks_parallel_scheme = other.tasks_parallel_scheme; tasks_block_size = other.tasks_block_size; mapping_update_flags = other.mapping_update_flags; mapping_update_flags_boundary_faces = other.mapping_update_flags_boundary_faces; mapping_update_flags_inner_faces = other.mapping_update_flags_inner_faces; mapping_update_flags_faces_by_cells = other.mapping_update_flags_faces_by_cells; mg_level = other.mg_level; store_plain_indices = other.store_plain_indices; initialize_indices = other.initialize_indices; initialize_mapping = other.initialize_mapping; overlap_communication_computation = other.overlap_communication_computation; hold_all_faces_to_owned_cells = other.hold_all_faces_to_owned_cells; cell_vectorization_category = other.cell_vectorization_category; cell_vectorization_categories_strict = other.cell_vectorization_categories_strict; communicator_sm = other.communicator_sm; return *this; } /** * 设置任务并行的方案。有四个选项可用。 * 如果设置为 @p none, * ,运算器的应用是以串行方式进行的,没有共享内存并行。如果这个类和MPI一起使用,并且MPI也用于节点内的并行,那么这个标志应该设置为 * @p none. 默认值是 @p partition_partition, * ,即我们实际上用下面描述的第一个选项使用多线程。 * 第一个选项 @p partition_partition * 是在洋葱皮一样的分区中对单元格进行两级分割,并在分割后形成tasks_block_size的块。分区找到独立的单元组,使其能够在不同时访问相同的向量项的情况下并行工作。 * 第二种选择 @p partition_color * 是在全局层面上使用分区,并在分区内为单元格着色(在一个颜色内的所有块是独立的)。在这里,将单元格细分为若干块是在分区之前完成的,如果自由度没有被重新编号,可能会得到更差的分区,但缓存性能更好。 * 第三种方案 @p color * 是在全局层面使用传统的着色算法。这种方案是第二种方案的一个特例,即只存在一个分区。请注意,对于有悬空节点的问题,有相当多的颜色(3D中为50种或更多),这可能会降低并行性能(不良的缓存行为,许多同步点)。 * @note * 对于进行内面积分的情况,线程支持目前是实验性的,如果可能的话,建议使用MPI并行。虽然该方案已经验证了在通常的DG元素的情况下可以使用`partition_partition`选项,但对于更一般的元素系统,如连续和不连续元素的组合,对所有项添加面积分的情况,没有进行全面的测试。 * */ TasksParallelScheme tasks_parallel_scheme; /** * 设置应该形成一个分区的所谓宏单元的数量。如果给定的尺寸为零,该类会尝试根据 * MultithreadInfo::n_threads() * 和存在的单元数为块找到一个好的尺寸。否则,将使用给定的数字。如果给定的数字大于总单元格数的三分之一,这意味着没有并行性。请注意,在使用矢量化的情况下,一个宏单元由一个以上的物理单元组成。 * */ unsigned int tasks_block_size; /** * 这个标志决定了单元格上的映射数据被缓存起来。该类可以缓存梯度计算(反雅各布)、雅各布行列式(JxW)、正交点以及Hessians(雅各布导数)的数据。默认情况下,只有梯度和雅各布行列式乘以正交权重JxW的数据被缓存。如果需要正交点或二次导数,它们必须由这个字段指定(即使这里没有设置这个选项,二次导数仍然可以在笛卡尔单元上评估,因为那里的雅各布系数完全描述了映射)。 * */ UpdateFlags mapping_update_flags; /** * 这个标志决定了边界面上的映射数据要被缓存。注意MatrixFree对面的积分使用单独的循环布局,以便在悬空节点(需要在两边有不同的子面设置)或者在一个VectorizedArray的批次中的一些单元与边界相邻而其他单元不相邻的情况下也能有效地进行矢量。 * 如果设置为不同于update_general的值(默认),面的信息将被显式建立。目前,MatrixFree支持缓存以下面的数据:逆雅各布,雅各布行列式(JxW),正交点,Hessians数据(雅各布的导数),以及法向量。 * @note 为了能够在 MatrixFree::loop()`, 中执行 "face_operation * "或 "boundary_operation",这个字段或 @p * mapping_update_flags_inner_faces 必须被设置为与 * UpdateFlags::update_default. 不同的值。 * */ UpdateFlags mapping_update_flags_boundary_faces; /** * 这个标志决定了要缓存的内部面的映射数据。请注意,MatrixFree对面的积分使用单独的循环布局,以便在悬空节点(需要在两边有不同的子面设置)或者在一个VectorizedArray的批中的一些单元与边界相邻而其他单元不相邻的情况下也能有效地进行矢量化。 * 如果设置为不同于update_general的值(默认),面的信息将被显式建立。目前,MatrixFree支持缓存以下面的数据:逆雅各布,雅各布行列式(JxW),正交点,Hessians数据(雅各布的导数),以及法向量。 * @note 为了能够在 MatrixFree::loop()`, 中执行 "face_operation * "或 "boundary_operation",这个字段或 @p * mapping_update_flags_boundary_faces 必须被设置为与 * UpdateFlags::update_default. 不同的值。 * */ UpdateFlags mapping_update_flags_inner_faces; /** * 这个标志决定了不同布局的面的映射数据与矢量化的关系。当`mapping_update_flags_inner_faces`和`mapping_update_flags_boundary_faces`触发以面为中心的方式建立数据并进行适当的矢量化时,当前的数据域将面的信息附加到单元格及其矢量化的方式。这只在特殊情况下需要,例如在块状Jacobi方法中,单元格的全部算子包括其面都被评估。该数据由 * <code>FEFaceEvaluation::reinit(cell_batch_index, * face_number)</code>访问。然而,目前用这种方法不能计算到邻居的耦合项,因为邻居不是由VectorizedArray数据布局的数组-结构-数组类型的数据结构来布置的。 * 注意,你应该只在真正需要的情况下计算这个数据域,因为它使面的映射数据所需的内存增加了一倍以上。 * 如果设置为不同于update_general的值(默认值),就会显式地建立面的信息。目前,MatrixFree支持缓存以下面的数据:反Jacobian,Jacobian行列式(JxW),正交点,Hessians(Jacobian的导数)数据,以及法向量。 * */ UpdateFlags mapping_update_flags_faces_by_cells; /** * 这个选项可以用来定义我们是否在网格的某一层工作,而不是活动单元。如果设置为invalid_unsigned_int * (这是默认值),就会对活动单元进行处理,否则就按这个参数给定的级别处理。请注意,如果你指定在一个层次上工作,其道夫必须通过使用 * <code>dof_handler.distribute_mg_dofs(fe);</code> 来分配。 * */ unsigned int mg_level; /** * 控制是否启用从向量读取而不解决约束,即只读取向量的局部值。默认情况下,这个选项是启用的。如果你想使用 * FEEvaluationBase::read_dof_values_plain, * ,这个标志需要被设置。 * */ bool store_plain_indices; /** * 选项用于控制是否应该读取存储在DoFHandler中的索引,以及是否应该在MatrixFree的初始化方法中设置任务并行的模式。默认值是true。如果映射需要重新计算(例如,当使用通过MappingEulerian描述的变形网格时),但单元格的拓扑结构保持不变,可以禁用。 * */ bool initialize_indices; /** * 控制是否应该在MatrixFree的初始化方法中计算映射信息的选项。默认值为true。当只需要设置一些索引时可以禁用(例如,当只需要计算一组独立的单元格时)。 * */ bool initialize_mapping; /** * 如果传递给循环的向量支持非阻塞数据交换,可以选择控制循环是否应该尽可能地重叠通信和计算。在大多数情况下,如果要发送的数据量超过几千字节,重叠会更快。如果发送的数据较少,在大多数集群上,通信是有延迟的(按照2016年的标准,在好的集群上,点到点的延迟大约是1微秒)。根据MPI实现和结构的不同,不重叠并等待数据的到来可能会更快。默认情况下是true,即通信和计算是重叠的。 * */ bool overlap_communication_computation; /** * 默认情况下,面的部分将只保存那些要被本地处理的面(和面后面的鬼元素)。如果MatrixFree需要访问本地拥有的单元上的所有邻域,这个选项可以在面域的末端添加相应的面。 * */ bool hold_all_faces_to_owned_cells; /** * 这个数据结构允许在建立矢量化信息时将一部分单元分配给不同的类别。在使用hp-adaptivity时,它被隐含地使用,但在其他情况下也是有用的,比如在本地时间步进中,人们想控制哪些元素共同构成一批单元。 * 在 @p mg_level 设置为 numbers::invalid_unsigned_int * 的活动单元上工作时,通过cell->active_cell_index()给出的数字访问这个数组,对于水平单元则通过cell->index()访问。 * @note * 这个字段在构建AdditionalData时是空的。用户有责任在填充数据时将此字段调整为`triangulation.n_active_cells()`或`triangulation.n_cells(level)`。 * */ std::vector<unsigned int> cell_vectorization_category; /** * 默认情况下, @p cell_vectorization_category * 中的不同类别可以混合,如果在算法内部有必要,允许算法将较低的类别与次高的类别合并。这样可以更好地利用矢量,但可能需要特殊处理,特别是对于面积分。如果设置为 * @p true, * ,算法会将不同的类别分开,而不是将它们混合在一个矢量化的数组中。 * */ bool cell_vectorization_categories_strict; /** * 共享内存的MPI通信器。默认值。MPI_COMM_SELF。 * */ MPI_Comm communicator_sm; }; /** * @name 1:构造和初始化 * */ //@{ /** * 默认的空构造函数。什么都不做。 * */ MatrixFree(); /** * 复制构造函数,调用copy_from * */ MatrixFree(const MatrixFree<dim, Number, VectorizedArrayType> &other); /** * 解构器。 * */ ~MatrixFree() override = default; /** * 提取在单元格上进行循环所需的信息。DoFHandler和AffineConstraints对象描述了自由度的布局,DoFHandler和映射描述了从单元到实数单元的转换,而DoFHandler底层的有限元与正交公式一起描述了局部操作。请注意,DoFHandler底层的有限元必须是标量的,或者包含同一元素的几个副本。不允许将几个不同的元素混入一个FES系统。在这种情况下,使用带有几个DoFHandler参数的初始化函数。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraint, const QuadratureType & quad, const AdditionalData & additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用重载来代替Mapping对象。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraint, const QuadratureType & quad, const AdditionalData & additional_data = AdditionalData()); /** * 提取在单元格上进行循环所需的信息。DoFHandler和AffineConstraints对象描述了自由度的布局,DoFHandler和映射描述了从单元到实数单元的转换,DoFHandler的基础有限元与正交公式一起描述了局部操作。与其他初始化函数处理的标量情况不同,这个函数允许有两个或多个不同的有限元的问题。每个元素的DoFHandlers必须作为指针传递给初始化函数。另外,一个由多个构件组成的系统也可以由一个带有FESystem元素的单一DoFHandler来表示。这种情况的前提条件是FESystem的每个基本元素必须与本类兼容,如FE_Q或FE_DGQ类。 * 这个函数也允许使用多个正交公式,例如当描述中包含不同程度的元素的独立积分时。然而,不同正交公式的数量可以独立于DoFHandlers的数量进行设置,当几个元素总是用同一个正交公式进行积分时。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。与上述相同,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> DEAL_II_DEPRECATED void reinit(const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用获取Mapping对象的重载来代替。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和以前一样,但现在本地拥有的自由度范围的索引集描述取自DoFHandler。此外,只使用一个正交公式,当一个矢量值问题中的几个分量基于同一个正交公式被整合在一起时,这可能是必要的。 * */ template <typename QuadratureType, typename number2, typename MappingType> void reinit(const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。与上述相同,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> DEAL_II_DEPRECATED void reinit(const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用 $Q_1$ 的映射。 * @deprecated 使用获取映射对象的重载来代替。 * */ template <typename QuadratureType, typename number2> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 初始化数据结构。和上面一样,但使用DoFHandlerType。 * @deprecated 使用获取DoFHandler对象的重载来代替。 * */ template <typename QuadratureType, typename number2, typename DoFHandlerType> DEAL_II_DEPRECATED void reinit(const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData &additional_data = AdditionalData()); /** * 复制函数。创建一个所有数据结构的深度拷贝。通常情况下,为不同的操作保留一次数据就足够了,所以不应该经常需要这个函数。 * */ void copy_from( const MatrixFree<dim, Number, VectorizedArrayType> &matrix_free_base); /** * 当底层几何体发生变化(例如,通过像MappingFEField这样可以通过空间配置的变化而变形的映射)而网格和未知数的拓扑结构保持不变时,重新刷新存储在MappingInfo字段中的几何体数据。与reinit()相比,这个操作只需要重新生成几何体阵列,因此可以大大降低成本(取决于评估几何体的成本)。 * */ void update_mapping(const Mapping<dim> &mapping); /** * 与上述相同,但有 hp::MappingCollection. 。 * */ void update_mapping(const std::shared_ptr<hp::MappingCollection<dim>> &mapping); /** * 清除所有的数据字段,使类进入类似于调用了默认构造函数后的状态。 * */ void clear(); //@} /** * 这个类定义了循环()中的面积分的数据访问类型,它被传递给并行向量的`update_ghost_values`和`compress`函数,目的是能够减少必须交换的数据量。数据交换是一个真正的瓶颈,特别是对于高等级的DG方法,因此更严格的交换方式显然是有益的。请注意,这种选择只适用于分配给访问 * `FaceToCellTopology::exterior_cells` * 的单元格外部的FEFaceEvaluation对象;所有<i>interior</i>对象在任何情况下都是可用的。 * */ enum class DataAccessOnFaces { /** * 循环不涉及任何FEFaceEvaluation对邻居的访问,就像只有边界积分(但没有内部面积分)或在类似 * MatrixFree::cell_loop() 的设置中做质量矩阵时的情况。 * */ none, /** * 循环只涉及到FEFaceEvaluation通过函数值访问邻居,如 * FEFaceEvaluation::gather_evaluate() 的参数 EvaluationFlags::values, * ,但没有访问形状函数导数(通常需要访问更多数据)。对于只有部分形状函数在面上有支持的FiniteElement类型,如FE_DGQ元素,其节点在元素表面的拉格朗日多项式,数据交换从`(k+1)^dim`减少到`(k+1)^(dim-1)`。 * */ values, /** * 与上述相同。如果FEFaceEvaluation通过提供单元批号和一个面的编号而被重新初始化,则必须从外部面访问数据时使用。这种配置在以单元为中心的循环中很有用。 * @pre AdditionalData::hold_all_faces_to_owned_cells 必须启用。 * */ values_all_faces, /** * 循环确实涉及到FEFaceEvaluation通过函数值和梯度访问到邻居,但没有二阶导数,比如 * FEFaceEvaluation::gather_evaluate() 设置了 EvaluationFlags::values * 和 EvaluationFlags::gradients * 。对于只有部分形状函数在一个面上有非零值和一阶导数的FiniteElement类型,例如FE_DGQHermite元素,数据交换会减少,例如从`(k+1)^dim`到`2(k+1)^(dim-1)`。请注意,对于不具备这种特殊属性的基数,无论如何都要发送完整的邻接数据。 * */ gradients, /** * 与上述相同。如果FEFaceEvaluation通过提供单元格批号和一个面的编号而被重新初始化的话,要用于必须从外部面访问数据。这种配置在以单元为中心的循环中很有用。 * @pre AdditionalData::hold_all_faces_to_owned_cells 必须启用。 * */ gradients_all_faces, /** * 用户不想做限制的一般设置。这通常比其他选项更昂贵,但也是最保守的一种,因为要在本地计算的面后面的元素的全部数据将被交换。 * */ unspecified }; /** * @name 2:无矩阵循环 * */ //@{ /** * 这种方法在所有单元格上运行循环(并行),并在源向量和目的向量上执行MPI数据交换。 * @param cell_operation `std::function` ,签名为<tt>cell_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元的范围(通常应该处理多个单元以减少开销)。 * 如果一个对象有一个具有正确参数集的`operator()`,人们可以在这个地方传递一个指针,因为这样的指针可以被转换为函数对象。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() * 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是这些外部库所暗示的全局寻址。 * @param src 输入向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环内被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为零,确保向量项尽可能地留在缓存中。 * */ template <typename OutVector, typename InVector> void cell_loop(const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false) const; /** * 这是第二个变种,在所有单元格上运行循环,现在提供一个指向`CLASS`类成员函数的函数指针。这种方法避免了定义lambda函数或调用 * std::bind * 将类绑定到给定的函数中,以防本地函数需要访问类中的数据(即,它是一个非静态成员函数)。 * @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,其中第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理一个以上的单元以减少开销)。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() * 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是那些外部库所暗示的全局寻址。 * @param src 输入向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ),循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为零,确保向量项尽可能地留在缓存中。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector = false) const; /** * 与上述相同,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector = false) const; /** * 这个函数类似于cell_loop,用一个 std::function * 对象来指定要对单元格进行的操作,但增加了两个额外的向量,在计算单元格积分前后执行一些额外的工作。 * 这两个额外的向量在自由度范围内工作,以MPI本地索引中选定的DoFHandler`dof_handler_index_pre_post`的自由度编号表示。向量的参数代表自由度范围,粒度为 * internal::MatrixFreeFunctions::DoFInfo::chunk_size_zero_vector * 个条目(除了最后一个块被设置为本地拥有的条目数),形式为`[first, * last)`。这些向量的想法是使向量上的操作更接近于它们在无矩阵循环中的访问点,目的是通过时间上的定位来增加缓存的点击。这个循环保证了`operation_before_loop`在cell_operation(包括MPI数据交换)中第一次接触到所有相关的未知数之前,就已经击中了这些未知数,允许执行一些`src`向量依赖的向量更新。循环后的操作 * "是类似的 * * * * * - 一旦该范围内的所有自由度被`cell_operation`最后一次触及(包括MPI数据交换),它就开始在该范围的自由度上执行,允许例如计算一些取决于当前`dst`中的单元循环结果的向量操作,或者想修改`src`。缓存的效率取决于自由度的编号,因为范围的粒度不同。 @param cell_operation 指向`CLASS`的成员函数,签名为<tt>cell_operation (const MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned int,unsigned int> &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理多个单元,以减少开销)。 @param owning_class 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 @param dst 保存结果的目标向量。如果向量是 LinearAlgebra::distributed::Vector 类型(或其复合对象,如 LinearAlgebra::distributed::BlockVector), ,循环在内部调用结束时调用 LinearAlgebra::distributed::Vector::compress() 。对于其他向量,包括平行的Trilinos或PETSc向量,不发出这样的调用。请注意,Trilinos/Epetra或PETSc向量目前不能并行工作,因为本类使用MPI本地索引寻址,而不是这些外部库所暗示的全局寻址。 @param src 输入向量。如果向量是 LinearAlgebra::distributed::Vector 类型(或其复合对象,如 LinearAlgebra::distributed::BlockVector), ),循环在内部调用开始时调用 LinearAlgebra::distributed::Vector::update_ghost_values() ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 @param operation_before_loop 这个函数可以用来对`src'和`dst'向量(或其他向量)的条目进行操作,在对单元的操作第一次接触到特定的DoF之前,根据上面文本中的一般描述。这个函数被传递给选定的`dof_handler_index_pre_post`(用MPI本地编号)上的本地拥有的自由度范围。 @param operation_after_loop 这个函数可以用来对`src'和`dst'向量(或其他向量)的条目进行操作,在对单元的操作最后触及一个特定的DoF之后,根据上面文字的一般描述。这个函数被传递给选定的`dof_handler_index_pre_post`(以MPI本地编号)上的本地拥有的自由度范围。 @param dof_handler_index_pre_post 由于MatrixFree可以用DoFHandler对象的矢量初始化,一般来说,每个对象都会有矢量大小,因此返回给`operation_before_loop`和`operation_after_loop`的范围也不同。使用这个变量来指定索引范围应该与哪一个DoFHandler对象相关。默认为`dof_handler_index` 0。 * @note * `operation_before_loop`和`operation_after_loop`的近距离定位目前只在仅MPI的情况下实现。在启用线程的情况下,由于复杂的依赖关系,完整的`operation_before_loop`被安排在并行循环之前,而`operation_after_loop`被严格安排在之后。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 与上述相同,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void cell_loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 同上,但取一个 `std::function` * 作为`cell_operation`,而不是类成员函数。 * */ template <typename OutVector, typename InVector> void cell_loop(const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, OutVector & dst, const InVector & src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post = 0) const; /** * 这个方法在所有单元格上运行一个循环(并行),并在源向量和目的向量上执行MPI数据交换。与其他只在单元格上运行一个函数的变体不同,这个方法还分别以内部面和边界面的函数为参数。 * @param cell_operation `std::function` 的签名为<tt>cell_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元的范围(通常应该处理一个以上的单元以减少开销)。如果有一个 * <code>operator()</code> * 具有正确的参数集,人们可以在这个地方传递一个对象的指针,因为这样的指针可以被转换为函数对象。 * @param face_operation `std::function` 的签名是<tt>face_operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int> * &)</tt>,类似于`cell_operation`,但现在是与内部面的工作有关的部分。请注意,MatrixFree框架将周期性面视为内部面,因此,在调用face_operation时应用周期性约束后,它们将被分配到正确的邻居。 * @param boundary_operation `std::function` * 签名为<tt>boundary_operation (const MatrixFree<dim,Number> &, * OutVector &, InVector &, std::pair<unsigned int,unsigned int> * &)</tt>,与`cell_operation`和`face_operation`类似,但现在是与边界面的工作相关的部分。边界面是由它们的`boundary_id'分开的,可以用 * MatrixFree::get_boundary_id(). * 来查询这个id。注意,内部和面都使用相同的编号,内部的面被分配的编号比边界面低。 * @param dst 保存结果的目的向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * 以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param dst_vector_face_access * 设置对向量`dst`的访问类型,该访问将发生在 @p * face_operation * 函数内部。正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * @param src_vector_face_access * 设置对向量`src`的访问类型,将在 @p face_operation * 函数体内发生,与`dst_vector_face_access`相类似。 * */ template <typename OutVector, typename InVector> void loop(const std::function< void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, const std::function< void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &face_operation, const std::function<void( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &boundary_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 这是第二个变体,在所有的单元格、内部面和边界面上运行循环,现在提供了三个指向 * @p CLASS 类成员函数的函数指针,其签名为<code>operation * (const MatrixFree<dim,Number> &, OutVector &, InVector &, * std::pair<unsigned int,unsigned int>&) * const</code>。如果本地函数需要访问类中的数据(即,它是一个非静态成员函数),该方法就不需要定义lambda函数或调用 * std::bind 将类绑定到给定函数中。 @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,其中第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常应该处理一个以上的单元以减少开销)。注意,这个循环通常会将`cell_range'分割成更小的部分,并交替工作于`cell_operation'、`face_operation'和`boundary_operation',以增加缓存中向量项的潜在重用。 * @param face_operation * 指向`CLASS`的成员函数,其签名为<tt>face_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,与`cell_operation`相类似,但现在是与内部面的工作相关的部分。请注意,MatrixFree框架将周期性面视为内部面,因此,在调用face_operation时应用周期性约束后,它们将被分配给正确的邻居。 * @param boundary_operation * 指向`CLASS`的成员函数,其签名为<tt>boundary_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,与`cell_operation`和`face_operation`类似,但现在是与边界面的工作相关的部分。边界面由它们的`boundary_id'分开,可以使用 * MatrixFree::get_boundary_id(). * 查询该id。注意,内部和面都使用相同的编号,内部的面被分配的编号比边界面低。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(...)`, * `owning_class->face_operation(...)`, * 和`owning_class->boundary_operation(...)`。 @param dst * 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,则循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * 以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为其原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param dst_vector_face_access * 设置对向量`dst`的访问类型,将在 @p face_operation * 函数内部发生。正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * @param src_vector_face_access * 设置对向量`src`的访问类型,将在 @p face_operation * 函数体内发生,与`dst_vector_face_access`相类似。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop( void (CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*face_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*boundary_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 和上面一样,但对于非const的类成员函数。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*face_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*boundary_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces dst_vector_face_access = DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 这个方法与cell_loop()的做法类似,在所有单元格上运行循环(并行)。然而,这个函数的目的是用于面和边界积分也应该被评估的情况。与loop()相反,用户只需提供一个单一的函数,该函数应包含一个单元(或向量化时的一批单元)的单元积分和所有面的面和边界积分。这在文献中被称为 * "以元素为中心的循环 "或 "以单元为中心的循环"。 * 为了能够评估所有的面积分(用来自相邻单元的值或梯度),相邻单元的所有幽灵值都要更新。使用 * FEFaceEvalution::reinit(cell, * face_no)来访问一个单元的任意面和各自的邻居的数量。 * @param cell_operation * 指向`CLASS`的成员函数,其签名为<tt>cell_operation (const * MatrixFree<dim,Number> &, OutVector &, InVector &, std::pair<unsigned * int,unsigned int> * &)</tt>,第一个参数传递调用类的数据,最后一个参数定义应该被处理的单元范围(通常从循环中传递多个单元以减少开销)。 * @param owning_class * 提供`cell_operation`调用的对象。为了与该接口兼容,该类必须允许调用`owning_class->cell_operation(..)`。 * @param dst 保存结果的目标向量。如果向量是 * LinearAlgebra::distributed::Vector 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用结束时调用 * LinearAlgebra::distributed::Vector::compress() 。 @param src * 输入向量。如果向量是 LinearAlgebra::distributed::Vector * 类型(或其复合对象,如 * LinearAlgebra::distributed::BlockVector), * ,循环在内部调用开始时调用 * LinearAlgebra::distributed::Vector::update_ghost_values() * ,以确保所有必要的数据在本地可用。然而,请注意,在循环结束时,向量会被重置为原始状态,即如果向量在进入循环时没有被重影,那么在完成循环时也不会被重影。 * @param zero_dst_vector * 如果这个标志被设置为`true`,向量`dst`将在循环中被设置为零。在你对矩阵对象进行典型的`vmult()`操作时使用这种情况,因为它通常会比在循环之前单独调用`dst * = * 0;`更快。这是因为向量项只在向量的子范围内被设置为0,确保向量项尽可能地留在缓存中。 * @param src_vector_face_access * 设置对向量`src`的访问类型,这将在面积分过程中发生在 * @p cell_operation 函数的内部。 * 正如在DataAccessOnFaces结构的描述中所解释的,这个选择的目的是减少必须通过MPI网络(如果在节点的共享内存区域内,则通过`memcpy`)交换的数据量以获得性能。请注意,没有办法与FEFaceEvaluation类沟通这一设置,因此除了在`face_operation`函数中实现的内容外,这一选择必须在这个地方进行。因此,也没有办法检查传递给这个调用的设置是否与后来`FEFaceEvaluation`所做的一致,确保数据的正确性是用户的责任。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop_cell_centric(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 同上,但对于类的成员函数,它是非const的。 * */ template <typename CLASS, typename OutVector, typename InVector> void loop_cell_centric(void (CLASS::*cell_operation)( const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 与上述相同,但有 std::function. 。 * */ template <typename OutVector, typename InVector> void loop_cell_centric( const std::function<void(const MatrixFree &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector = false, const DataAccessOnFaces src_vector_face_access = DataAccessOnFaces::unspecified) const; /** * 在hp-adaptive情况下,在单元格循环中计算的单元格子范围可能包含不同程度的元素。使用这个函数来计算一个单独的有限元度的子范围是什么。有限元度与函数调用中给出的矢量分量相关。 * */ std::pair<unsigned int, unsigned int> create_cell_subrange_hp(const std::pair<unsigned int, unsigned int> &range, const unsigned int fe_degree, const unsigned int dof_handler_index = 0) const; /** * 在hp-adaptive情况下,在单元循环中计算的单元子范围可能包含不同程度的元素。使用这个函数来计算给定索引的子范围的hp-finite元素,而不是其他函数中的有限元素程度。 * */ std::pair<unsigned int, unsigned int> create_cell_subrange_hp_by_index( const std::pair<unsigned int, unsigned int> &range, const unsigned int fe_index, const unsigned int dof_handler_index = 0) const; /** * 在hp自适应情况下,返回active_fe_indices的数量。 * */ unsigned int n_active_fe_indices() const; /** * 在hp-adaptive情况下,返回单元格范围的active_fe_index。 * */ unsigned int get_cell_active_fe_index( const std::pair<unsigned int, unsigned int> range) const; /** * 在hp-adaptive的情况下,返回一个面域的active_fe_index。 * */ unsigned int get_face_active_fe_index(const std::pair<unsigned int, unsigned int> range, const bool is_interior_face = true) const; //@} /** * @name 3: 向量的初始化 * */ //@{ /** * */ template <typename VectorType> void initialize_dof_vector(VectorType & vec, const unsigned int dof_handler_index = 0) const; /** * */ template <typename Number2> void initialize_dof_vector(LinearAlgebra::distributed::Vector<Number2> &vec, const unsigned int dof_handler_index = 0) const; /** * 返回代表本地拥有的数据的分区器,以及单元格循环需要访问的幽灵索引。分区器是由各自字段给出的本地拥有的道夫和幽灵道夫构建的。如果你想知道这些对象的具体信息,你可以用各自的访问函数来查询它们。如果你只是想初始化一个(平行)向量,你通常应该更喜欢这种数据结构,因为数据交换信息可以从一个向量重复使用到另一个向量。 * */ const std::shared_ptr<const Utilities::MPI::Partitioner> & get_vector_partitioner(const unsigned int dof_handler_index = 0) const; /** * 返回由处理器拥有的单元格集合。 * */ const IndexSet & get_locally_owned_set(const unsigned int dof_handler_index = 0) const; /** * 返回需要但不为处理器所拥有的幽灵单元的集合。 * */ const IndexSet & get_ghost_set(const unsigned int dof_handler_index = 0) const; /** * 返回一个所有被约束的自由度的列表。该列表是在本地拥有的向量范围的MPI本地索引空间中返回的,而不是跨越所有MPI处理器的全局MPI索引空间。要获得全局索引空间的数字,请在向量的一个条目上调用<tt>get_vector_partitioner()->local_to_global</tt>。此外,它只返回本地拥有的自由度的指数,而不是鬼魂的指数。 * */ const std::vector<unsigned int> & get_constrained_dofs(const unsigned int dof_handler_index = 0) const; /** * 根据给定的数据布局,计算自由度的重新编号,使其更符合MatrixFree中的数据布局。注意,这个函数并不重新排列存储在这个类中的信息,而是创建一个重新编号以消耗 * DoFHandler::renumber_dofs. * 为了产生任何效果,必须使用重新编号的DoFHandler和AffineConstraints再次设置MatrixFree对象。注意,如果DoFHandler调用 * DoFHandler::renumber_dofs, ,MatrixFree中的所有信息都会失效。 * */ void renumber_dofs(std::vector<types::global_dof_index> &renumbering, const unsigned int dof_handler_index = 0); //@} /** * @name 4:一般信息 * */ //@{ /** * 返回一个给定的FiniteElement @p fe 是否被这个类所支持。 * */ template <int spacedim> static bool is_supported(const FiniteElement<dim, spacedim> &fe); /** * 返回初始化时指定的不同DoFHandlers的数量。 * */ unsigned int n_components() const; /** * 对于由 @p * dof_handler_index指定的DoFHandler的基础有限元,返回基础元的数量。 * */ unsigned int n_base_elements(const unsigned int dof_handler_index) const; /** * 返回这个结构所基于的单元数。如果你使用的是一个通常的DoFHandler,它对应于(本地拥有的)活动单元的数量。请注意,这个类中的大多数数据结构并不直接作用于这个数字,而是作用于n_cell_batches(),它给出了用矢量化将几个单元拼凑在一起时看到的单元的数量。 * */ unsigned int n_physical_cells() const; /** * @deprecated 用n_cell_batches()代替。 * */ DEAL_II_DEPRECATED unsigned int n_macro_cells() const; /** * 返回该结构所处理的单元格批次的数量。批次是通过在一般的几个单元上应用矢量化而形成的。 * @p cell_loop * 中的细胞范围从零到n_cell_batches()(独占),所以如果你想为所有要处理的细胞存储数据数组,这是一个合适的大小。这个数字大约是 * `n_physical_cells()/VectorizedArray::%size()` * (取决于有多少细胞批没有被完全填满)。 * */ unsigned int n_cell_batches() const; /** * 返回该结构为面层集成而保留的额外单元格批次的数量。请注意,并不是所有在三角形中被重影的单元格都被保留在这个数据结构中,而是只有那些对评估两边的面积分有必要的单元格。 * */ unsigned int n_ghost_cell_batches() const; /** * 返回这个结构所处理的内部面批的数量。 * 这些批次是通过在一般的几个面上应用矢量化而形成的。 * @p loop * 中的面的范围从零到n_inner_face_batches()(独占),所以如果你想为所有要处理的内部面存储数据的数组,这就是合适的大小。 * */ unsigned int n_inner_face_batches() const; /** * 返回这个结构所处理的边界面批的数量。 * 这些批次是通过在一般的几个面上应用矢量化而形成的。 * @p loop * 中的面的范围从n_inner_face_batches()到n_inner_face_batches()+n_boundary_face_batches()(独占),所以如果你需要存储所有边界面而不是内部面的数据的数组,这个数字给出适当的大小。 * */ unsigned int n_boundary_face_batches() const; /** * 返回未在本地处理但属于本地拥有的面的数量。 * */ unsigned int n_ghost_inner_face_batches() const; /** * 为了对边界的不同部分应用不同的运算符,这个方法可以用来查询面孔自己在VectorizedArray中按车道排序的边界ID。只对表示边界面的索引有效。 * */ types::boundary_id get_boundary_id(const unsigned int macro_face) const; /** * 返回一个单元格内的面的边界ID,使用单元格在VectorizedArray中按车道的排序。 * */ std::array<types::boundary_id, VectorizedArrayType::size()> get_faces_by_cells_boundary_id(const unsigned int cell_batch_index, const unsigned int face_number) const; /** * 返回DoFHandler,其索引与reinit()函数中各自的 `std::vector` * 参数一样。 * */ const DoFHandler<dim> & get_dof_handler(const unsigned int dof_handler_index = 0) const; /** * 返回DoFHandler,其索引与reinit()函数中相应的 `std::vector` * 参数一样。注意,如果你想用不同于默认的模板参数来调用这个函数,你需要在函数调用前使用`template`,也就是说,你会有类似`matrix_free.template * get_dof_handler<hp::DoFHandler<dim>>()`. @deprecated * 使用这个函数的非模板化等价物。 * */ template <typename DoFHandlerType> DEAL_II_DEPRECATED const DoFHandlerType & get_dof_handler(const unsigned int dof_handler_index = 0) const; /** * 返回deal.II中的单元格迭代器讲到一个给定的单元格批次(在一个VectorizedArray中填充几个车道)和在这个结构的重新编号中跨单元格的矢量化中的车道索引。 * 请注意,deal.II中的单元格迭代器与本类的单元格循环的处理方式不同。这是因为几个单元被一起处理(跨单元的矢量化),而且在访问远程数据和与计算重叠的通信时,在不同的MPI处理器上有邻居的单元需要在某个时间被访问。 * */ typename DoFHandler<dim>::cell_iterator get_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index = 0) const; /** * 这将返回由get_cell_iterator()对相同参数`cell_batch_index`和`lane_index`所返回的单元的级别和索引。 * */ std::pair<int, int> get_cell_level_and_index(const unsigned int cell_batch_index, const unsigned int lane_index) const; /** * 在deal.II中返回单元格的迭代器,该迭代器与一个面的内部/外部单元格在一对面批和巷道索引中。这一对中的第二个元素是面的编号,这样就可以访问面的迭代器。 * `pair.first()->face(pair.second());`注意deal.II中的面迭代器通过单元格的方式与本类的面/边界循环的方式不同。这是因为几个面是一起工作的(矢量化),而且在访问远程数据和与计算重叠的通信时,在不同的MPI处理器上有相邻单元的面需要在某个时间被访问。 * */ std::pair<typename DoFHandler<dim>::cell_iterator, unsigned int> get_face_iterator(const unsigned int face_batch_index, const unsigned int lane_index, const bool interior = true, const unsigned int fe_component = 0) const; /** * @copydoc MatrixFree::get_cell_iterator() @deprecated * 使用get_cell_iterator()代替。 * */ DEAL_II_DEPRECATED typename DoFHandler<dim>::active_cell_iterator get_hp_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index = 0) const; /** * 由于该类使用的是矢量数据类型,数据域中通常有多个值,因此可能会出现矢量类型的某些分量与网格中的实际单元不对应的情况。当只使用这个类时,通常不需要理会这个事实,因为这些值是用零填充的。然而,当这个类与访问单元格的deal.II混合时,需要注意。如果不是所有给定的`cell_batch_index`的`n_lanes`单元都对应于网格中的实际单元,有些只是为了填充的原因而出现,则该函数返回 * @p true * 。要知道有多少单元被实际使用,可以使用函数n_active_entries_per_cell_batch()。 * */ bool at_irregular_cell(const unsigned int cell_batch_index) const; /** * @deprecated 使用n_active_entries_per_cell_batch()代替。 * */ DEAL_II_DEPRECATED unsigned int n_components_filled(const unsigned int cell_batch_number) const; /** * 这个查询返回在一个单元格批中的 * `VectorizedArrayType::size()` * 个单元格中,有多少单元格是网格中的实际单元格,而不是因为填充的原因而出现的。对于大多数给定的n_cell_batches()中的单元格批次,这个数字等于 * `VectorizedArrayType::size()`, * ,但在网格中可能有一个或几个单元格批次(数字不相加),其中只有一个批次中的一些单元格被使用,由函数at_irregular_cell()表示。 * */ unsigned int n_active_entries_per_cell_batch(const unsigned int cell_batch_index) const; /** * 使用这个函数找出在矢量化数据类型的长度上有多少个面对应于网格中的真实面(包括内部和边界面,因为这些面使用相同的索引,但范围不同)。对于大多数在n_inner_faces_batches()和n_boundary_face_batches()中给定的索引,这只是 * @p vectorization_length * 个,但可能有一个或几个网格(数字不相加),其中有更少的这种道的填充。 * */ unsigned int n_active_entries_per_face_batch(const unsigned int face_batch_index) const; /** * 返回给定hp-index的每个单元的自由度数量。 * */ unsigned int get_dofs_per_cell(const unsigned int dof_handler_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的每个单元的正交点的数量。 * */ unsigned int get_n_q_points(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的单元格每个面上的自由度数量。 * */ unsigned int get_dofs_per_face(const unsigned int dof_handler_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的单元格每个面上的正交点的数量。 * */ unsigned int get_n_q_points_face(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的正交规则。 * */ const Quadrature<dim> & get_quadrature(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回给定hp-index的正交规则。 * */ const Quadrature<dim - 1> & get_face_quadrature(const unsigned int quad_index = 0, const unsigned int hp_active_fe_index = 0) const; /** * 返回当前批次的电池被分配到的类别。对于非hp-DoFHandler类型,类别在字段 * AdditionalData::cell_vectorization_category * 中的给定值之间运行,在hp-adaptive情况下返回活动的FE指数。 * */ unsigned int get_cell_category(const unsigned int cell_batch_index) const; /** * 返回当前一批面的两边的单元格上的类别。 * */ std::pair<unsigned int, unsigned int> get_face_category(const unsigned int macro_face) const; /** * 查询是否已经设置了索引。 * */ bool indices_initialized() const; /** * 查询单元格的几何相关信息是否已被设置。 * */ bool mapping_initialized() const; /** * 返回要处理的网格的级别。如果在活动单元上工作,返回 * numbers::invalid_unsigned_int 。 * */ unsigned int get_mg_level() const; /** * 返回该类的内存消耗量的近似值,单位为字节。 * */ std::size_t memory_consumption() const; /** * 在给定的输出流中打印出该类不同结构的内存消耗的详细摘要。 * */ template <typename StreamType> void print_memory_consumption(StreamType &out) const; /** * 在给定的输出流中打印这个类的摘要。它集中在索引上,并不打印所有存储的数据。 * */ void print(std::ostream &out) const; //@} /** * @name 5: 访问内部数据结构 注意:专家模式,接口在不同版本之间不稳定。 * */ //@{ /** * 返回任务图的信息。 * */ const internal::MatrixFreeFunctions::TaskInfo & get_task_info() const; /*返回单元格上与几何有关的信息。 * */ const internal::MatrixFreeFunctions:: MappingInfo<dim, Number, VectorizedArrayType> & get_mapping_info() const; /** * 返回关于索引自由度的信息。 * */ const internal::MatrixFreeFunctions::DoFInfo & get_dof_info(const unsigned int dof_handler_index_component = 0) const; /** * 返回约束池中的权重数量。 * */ unsigned int n_constraint_pool_entries() const; /** * 返回一个指向约束池数据中第一个数字的指针,索引为 * @p pool_index (与 @p constraint_pool_end()). 一起使用 * */ const Number * constraint_pool_begin(const unsigned int pool_index) const; /** * 返回一个指向约束池数据中最后一个数字的指针,索引为 * @p pool_index (与 @p constraint_pool_begin()一起使用)。 * */ const Number * constraint_pool_end(const unsigned int pool_index) const; /** * 返回给定hp-index的单元格信息。 * */ const internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType> & get_shape_info(const unsigned int dof_handler_index_component = 0, const unsigned int quad_index = 0, const unsigned int fe_base_element = 0, const unsigned int hp_active_fe_index = 0, const unsigned int hp_active_quad_index = 0) const; /** * 返回一个面的连接信息。 * */ const internal::MatrixFreeFunctions::FaceToCellTopology< VectorizedArrayType::size()> & get_face_info(const unsigned int face_batch_index) const; /** * 返回将宏观单元格号、单元格内的面的索引和向量的单元格批内的索引这三者转化为面数组内的索引的表格。 * */ const Table<3, unsigned int> & get_cell_and_face_to_plain_faces() const; /** * 获取一个内部使用的抓取数据对象。请确保事后将你从这个对象获得的指针传递给release_scratch_data()函数,以释放它。这个接口被FEEvaluation对象用来存储其数据结构。 内部数据结构的组织是一个线程本地存储的向量列表。多个线程将各自获得一个单独的存储域和单独的向量,确保线程安全。获取和释放对象的机制类似于WorkStream的本地贡献机制,见 @ref workstream_paper "WorkStream论文" * 。 * */ AlignedVector<VectorizedArrayType> * acquire_scratch_data() const; /** * 使得抓取板的对象再次可用。 * */ void release_scratch_data(const AlignedVector<VectorizedArrayType> *memory) const; /** * 获取一个用于内部使用的划痕数据对象。确保事后将你从这个对象获得的指针传递给release_scratch_data_non_threadsafe()函数,以释放它。注意,与acquisition_scratch_data()相反,这个方法一次只能由一个线程调用,但与acquisition_scratch_data()相反,释放scratch数据的线程也有可能与获取它的线程不同。 * */ AlignedVector<Number> * acquire_scratch_data_non_threadsafe() const; /** * 使得从头数据的对象再次可用。 * */ void release_scratch_data_non_threadsafe( const AlignedVector<Number> *memory) const; //@} private: /** * 这是实际的reinit函数,为DoFHandler的情况设置索引。 * */ template <typename number2, int q_dim> void internal_reinit( const std::shared_ptr<hp::MappingCollection<dim>> & mapping, const std::vector<const DoFHandler<dim, dim> *> & dof_handlers, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<IndexSet> & locally_owned_set, const std::vector<hp::QCollection<q_dim>> & quad, const AdditionalData & additional_data); /** * 初始化DoFInfo中的字段和约束池,约束池中保存了所有不同的权重(不是DoFInfo的一部分,因为几个DoFInfo类可以有相同的权重,因此只需要存储一次)。 * */ template <typename number2> void initialize_indices( const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<IndexSet> & locally_owned_set, const AdditionalData & additional_data); /** * 基于DoFHandler<dim>参数初始化DoFHandlers。 * */ void initialize_dof_handlers( const std::vector<const DoFHandler<dim, dim> *> &dof_handlers, const AdditionalData & additional_data); /** * 指向当前问题基础的DoFHandlers的指针。 * */ std::vector<SmartPointer<const DoFHandler<dim>>> dof_handlers; /** * 包含各个单元格上的自由度和约束信息。 * */ std::vector<internal::MatrixFreeFunctions::DoFInfo> dof_info; /** * 包含存储在DoFInfo中的约束条件的权重。填充到一个单独的字段中,因为几个向量组件可能共享类似的权重,这样可以减少内存消耗。此外,它省去了DoFInfo上的模板参数,使之成为一个只有索引的普通字段。 * */ std::vector<Number> constraint_pool_data; /** * 包含一个指向约束池数据中第i个索引开始的指标。 * */ std::vector<unsigned int> constraint_pool_row_index; /** * 保存单元格从参考单元格到实数单元格的转换信息,这是评估积分所需要的。 * */ internal::MatrixFreeFunctions::MappingInfo<dim, Number, VectorizedArrayType> mapping_info; /** * 包含单元格的形状值信息。 * */ Table<4, internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType>> shape_info; /** * 描述了单元格是如何被穿过的。有了单元格级别(该字段的第一个索引)和级别内的索引,就可以重建一个deal.II单元格迭代器,并使用deal.II提供的所有传统的单元格迭代器的功能。 * */ std::vector<std::pair<unsigned int, unsigned int>> cell_level_index; /** * 对于非连续Galerkin,cell_level_index包括不在本地处理器上的单元,但需要用来计算单元积分。在cell_level_index_end_local中,我们存储本地单元的数量。 * */ unsigned int cell_level_index_end_local; /** * 存储要处理的单元和面的基本布局,包括共享内存并行化的任务布局以及与MPI的通信和计算之间可能的重叠。 * */ internal::MatrixFreeFunctions::TaskInfo task_info; /** * 持有面孔信息的向量。只在build_face_info=true时初始化。 * */ internal::MatrixFreeFunctions::FaceInfo<VectorizedArrayType::size()> face_info; /** * 存储索引是否已被初始化。 * */ bool indices_are_initialized; /** * 存储索引是否已被初始化。 * */ bool mapping_is_initialized; /** * 用于评估的刮板内存。我们允许超过一个评估对象附加到这个字段(这个,外 * std::vector), * 所以我们需要跟踪某个数据字段是否已经被使用(第一部分对)并保持一个对象的列表。 * */ mutable Threads::ThreadLocalStorage< std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>> scratch_pad; /** * 用于评估和其他情况下的Scratchpad内存,非线程安全的变体。 * */ mutable std::list<std::pair<bool, AlignedVector<Number>>> scratch_pad_non_threadsafe; /** * 存储了要处理的网格的级别。 * */ unsigned int mg_level; }; /*----------------------- Inline functions ----------------------------------*/ #ifndef DOXYGEN template <int dim, typename Number, typename VectorizedArrayType> template <typename VectorType> inline void MatrixFree<dim, Number, VectorizedArrayType>::initialize_dof_vector( VectorType & vec, const unsigned int comp) const { AssertIndexRange(comp, n_components()); vec.reinit(dof_info[comp].vector_partitioner->size()); } template <int dim, typename Number, typename VectorizedArrayType> template <typename Number2> inline void MatrixFree<dim, Number, VectorizedArrayType>::initialize_dof_vector( LinearAlgebra::distributed::Vector<Number2> &vec, const unsigned int comp) const { AssertIndexRange(comp, n_components()); vec.reinit(dof_info[comp].vector_partitioner, task_info.communicator_sm); } template <int dim, typename Number, typename VectorizedArrayType> inline const std::shared_ptr<const Utilities::MPI::Partitioner> & MatrixFree<dim, Number, VectorizedArrayType>::get_vector_partitioner( const unsigned int comp) const { AssertIndexRange(comp, n_components()); return dof_info[comp].vector_partitioner; } template <int dim, typename Number, typename VectorizedArrayType> inline const std::vector<unsigned int> & MatrixFree<dim, Number, VectorizedArrayType>::get_constrained_dofs( const unsigned int comp) const { AssertIndexRange(comp, n_components()); return dof_info[comp].constrained_dofs; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_components() const { AssertDimension(dof_handlers.size(), dof_info.size()); return dof_handlers.size(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_base_elements( const unsigned int dof_no) const { AssertDimension(dof_handlers.size(), dof_info.size()); AssertIndexRange(dof_no, dof_handlers.size()); return dof_handlers[dof_no]->get_fe().n_base_elements(); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::TaskInfo & MatrixFree<dim, Number, VectorizedArrayType>::get_task_info() const { return task_info; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_macro_cells() const { return *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_physical_cells() const { return task_info.n_active_cells; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_cell_batches() const { return *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_ghost_cell_batches() const { return *(task_info.cell_partition_data.end() - 1) - *(task_info.cell_partition_data.end() - 2); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_inner_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return task_info.face_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_boundary_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return task_info.boundary_partition_data.back() - task_info.face_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_ghost_inner_face_batches() const { if (task_info.face_partition_data.size() == 0) return 0; return face_info.faces.size() - task_info.boundary_partition_data.back(); } template <int dim, typename Number, typename VectorizedArrayType> inline types::boundary_id MatrixFree<dim, Number, VectorizedArrayType>::get_boundary_id( const unsigned int macro_face) const { Assert(macro_face >= task_info.boundary_partition_data[0] && macro_face < task_info.boundary_partition_data.back(), ExcIndexRange(macro_face, task_info.boundary_partition_data[0], task_info.boundary_partition_data.back())); return types::boundary_id(face_info.faces[macro_face].exterior_face_no); } template <int dim, typename Number, typename VectorizedArrayType> inline std::array<types::boundary_id, VectorizedArrayType::size()> MatrixFree<dim, Number, VectorizedArrayType>::get_faces_by_cells_boundary_id( const unsigned int cell_batch_index, const unsigned int face_number) const { AssertIndexRange(cell_batch_index, n_cell_batches()); AssertIndexRange(face_number, GeometryInfo<dim>::faces_per_cell); Assert(face_info.cell_and_face_boundary_id.size(0) >= n_cell_batches(), ExcNotInitialized()); std::array<types::boundary_id, VectorizedArrayType::size()> result; result.fill(numbers::invalid_boundary_id); for (unsigned int v = 0; v < n_active_entries_per_cell_batch(cell_batch_index); ++v) result[v] = face_info.cell_and_face_boundary_id(cell_batch_index, face_number, v); return result; } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions:: MappingInfo<dim, Number, VectorizedArrayType> & MatrixFree<dim, Number, VectorizedArrayType>::get_mapping_info() const { return mapping_info; } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::DoFInfo & MatrixFree<dim, Number, VectorizedArrayType>::get_dof_info( const unsigned int dof_index) const { AssertIndexRange(dof_index, n_components()); return dof_info[dof_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_constraint_pool_entries() const { return constraint_pool_row_index.size() - 1; } template <int dim, typename Number, typename VectorizedArrayType> inline const Number * MatrixFree<dim, Number, VectorizedArrayType>::constraint_pool_begin( const unsigned int row) const { AssertIndexRange(row, constraint_pool_row_index.size() - 1); return constraint_pool_data.empty() ? nullptr : constraint_pool_data.data() + constraint_pool_row_index[row]; } template <int dim, typename Number, typename VectorizedArrayType> inline const Number * MatrixFree<dim, Number, VectorizedArrayType>::constraint_pool_end( const unsigned int row) const { AssertIndexRange(row, constraint_pool_row_index.size() - 1); return constraint_pool_data.empty() ? nullptr : constraint_pool_data.data() + constraint_pool_row_index[row + 1]; } template <int dim, typename Number, typename VectorizedArrayType> inline std::pair<unsigned int, unsigned int> MatrixFree<dim, Number, VectorizedArrayType>::create_cell_subrange_hp( const std::pair<unsigned int, unsigned int> &range, const unsigned int degree, const unsigned int dof_handler_component) const { if (dof_info[dof_handler_component].cell_active_fe_index.empty()) { AssertDimension( dof_info[dof_handler_component].fe_index_conversion.size(), 1); AssertDimension( dof_info[dof_handler_component].fe_index_conversion[0].size(), 1); if (dof_info[dof_handler_component].fe_index_conversion[0][0] == degree) return range; else return {range.second, range.second}; } const unsigned int fe_index = dof_info[dof_handler_component].fe_index_from_degree(0, degree); if (fe_index >= dof_info[dof_handler_component].max_fe_index) return {range.second, range.second}; else return create_cell_subrange_hp_by_index(range, fe_index, dof_handler_component); } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::at_irregular_cell( const unsigned int cell_batch_index) const { AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); return VectorizedArrayType::size() > 1 && cell_level_index[(cell_batch_index + 1) * VectorizedArrayType::size() - 1] == cell_level_index[(cell_batch_index + 1) * VectorizedArrayType::size() - 2]; } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_fe_indices() const { return shape_info.size(2); } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_cell_active_fe_index( const std::pair<unsigned int, unsigned int> range) const { const auto &fe_indices = dof_info[0].cell_active_fe_index; if (fe_indices.empty() == true) return 0; const auto index = fe_indices[range.first]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[i]); return index; } template <int dim, typename Number, typename VectorizedArrayType> unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_face_active_fe_index( const std::pair<unsigned int, unsigned int> range, const bool is_interior_face) const { const auto &fe_indices = dof_info[0].cell_active_fe_index; if (fe_indices.empty() == true) return 0; if (is_interior_face) { const unsigned int index = fe_indices[face_info.faces[range.first].cells_interior[0] / VectorizedArrayType::size()]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[face_info.faces[i].cells_interior[0] / VectorizedArrayType::size()]); return index; } else { const unsigned int index = fe_indices[face_info.faces[range.first].cells_exterior[0] / VectorizedArrayType::size()]; for (unsigned int i = range.first; i < range.second; ++i) AssertDimension(index, fe_indices[face_info.faces[i].cells_exterior[0] / VectorizedArrayType::size()]); return index; } } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_components_filled( const unsigned int cell_batch_index) const { return n_active_entries_per_cell_batch(cell_batch_index); } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_entries_per_cell_batch( const unsigned int cell_batch_index) const { AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); unsigned int n_lanes = VectorizedArrayType::size(); while (n_lanes > 1 && cell_level_index[cell_batch_index * VectorizedArrayType::size() + n_lanes - 1] == cell_level_index[cell_batch_index * VectorizedArrayType::size() + n_lanes - 2]) --n_lanes; AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); return n_lanes; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::n_active_entries_per_face_batch( const unsigned int face_batch_index) const { AssertIndexRange(face_batch_index, face_info.faces.size()); unsigned int n_lanes = VectorizedArrayType::size(); while (n_lanes > 1 && face_info.faces[face_batch_index].cells_interior[n_lanes - 1] == numbers::invalid_unsigned_int) --n_lanes; AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); return n_lanes; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_dofs_per_cell( const unsigned int dof_handler_index, const unsigned int active_fe_index) const { return dof_info[dof_handler_index].dofs_per_cell[active_fe_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_n_q_points( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.cell_data.size()); return mapping_info.cell_data[quad_index] .descriptor[active_fe_index] .n_q_points; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_dofs_per_face( const unsigned int dof_handler_index, const unsigned int active_fe_index) const { return dof_info[dof_handler_index].dofs_per_face[active_fe_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_n_q_points_face( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.face_data.size()); return mapping_info.face_data[quad_index] .descriptor[active_fe_index] .n_q_points; } template <int dim, typename Number, typename VectorizedArrayType> inline const IndexSet & MatrixFree<dim, Number, VectorizedArrayType>::get_locally_owned_set( const unsigned int dof_handler_index) const { return dof_info[dof_handler_index].vector_partitioner->locally_owned_range(); } template <int dim, typename Number, typename VectorizedArrayType> inline const IndexSet & MatrixFree<dim, Number, VectorizedArrayType>::get_ghost_set( const unsigned int dof_handler_index) const { return dof_info[dof_handler_index].vector_partitioner->ghost_indices(); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::ShapeInfo<VectorizedArrayType> & MatrixFree<dim, Number, VectorizedArrayType>::get_shape_info( const unsigned int dof_handler_index, const unsigned int index_quad, const unsigned int index_fe, const unsigned int active_fe_index, const unsigned int active_quad_index) const { AssertIndexRange(dof_handler_index, dof_info.size()); const unsigned int ind = dof_info[dof_handler_index].global_base_element_offset + index_fe; AssertIndexRange(ind, shape_info.size(0)); AssertIndexRange(index_quad, shape_info.size(1)); AssertIndexRange(active_fe_index, shape_info.size(2)); AssertIndexRange(active_quad_index, shape_info.size(3)); return shape_info(ind, index_quad, active_fe_index, active_quad_index); } template <int dim, typename Number, typename VectorizedArrayType> inline const internal::MatrixFreeFunctions::FaceToCellTopology< VectorizedArrayType::size()> & MatrixFree<dim, Number, VectorizedArrayType>::get_face_info( const unsigned int macro_face) const { AssertIndexRange(macro_face, face_info.faces.size()); return face_info.faces[macro_face]; } template <int dim, typename Number, typename VectorizedArrayType> inline const Table<3, unsigned int> & MatrixFree<dim, Number, VectorizedArrayType>::get_cell_and_face_to_plain_faces() const { return face_info.cell_and_face_to_plain_faces; } template <int dim, typename Number, typename VectorizedArrayType> inline const Quadrature<dim> & MatrixFree<dim, Number, VectorizedArrayType>::get_quadrature( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.cell_data.size()); return mapping_info.cell_data[quad_index] .descriptor[active_fe_index] .quadrature; } template <int dim, typename Number, typename VectorizedArrayType> inline const Quadrature<dim - 1> & MatrixFree<dim, Number, VectorizedArrayType>::get_face_quadrature( const unsigned int quad_index, const unsigned int active_fe_index) const { AssertIndexRange(quad_index, mapping_info.face_data.size()); return mapping_info.face_data[quad_index] .descriptor[active_fe_index] .quadrature; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_cell_category( const unsigned int cell_batch_index) const { AssertIndexRange(0, dof_info.size()); AssertIndexRange(cell_batch_index, dof_info[0].cell_active_fe_index.size()); if (dof_info[0].cell_active_fe_index.empty()) return 0; else return dof_info[0].cell_active_fe_index[cell_batch_index]; } template <int dim, typename Number, typename VectorizedArrayType> inline std::pair<unsigned int, unsigned int> MatrixFree<dim, Number, VectorizedArrayType>::get_face_category( const unsigned int macro_face) const { AssertIndexRange(macro_face, face_info.faces.size()); if (dof_info[0].cell_active_fe_index.empty()) return std::make_pair(0U, 0U); std::pair<unsigned int, unsigned int> result; for (unsigned int v = 0; v < VectorizedArrayType::size() && face_info.faces[macro_face].cells_interior[v] != numbers::invalid_unsigned_int; ++v) result.first = std::max( result.first, dof_info[0] .cell_active_fe_index[face_info.faces[macro_face].cells_interior[v]]); if (face_info.faces[macro_face].cells_exterior[0] != numbers::invalid_unsigned_int) for (unsigned int v = 0; v < VectorizedArrayType::size() && face_info.faces[macro_face].cells_exterior[v] != numbers::invalid_unsigned_int; ++v) result.second = std::max( result.first, dof_info[0] .cell_active_fe_index[face_info.faces[macro_face].cells_exterior[v]]); else result.second = numbers::invalid_unsigned_int; return result; } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::indices_initialized() const { return indices_are_initialized; } template <int dim, typename Number, typename VectorizedArrayType> inline bool MatrixFree<dim, Number, VectorizedArrayType>::mapping_initialized() const { return mapping_is_initialized; } template <int dim, typename Number, typename VectorizedArrayType> inline unsigned int MatrixFree<dim, Number, VectorizedArrayType>::get_mg_level() const { return mg_level; } template <int dim, typename Number, typename VectorizedArrayType> AlignedVector<VectorizedArrayType> * MatrixFree<dim, Number, VectorizedArrayType>::acquire_scratch_data() const { using list_type = std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; list_type &data = scratch_pad.get(); for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) if (it->first == false) { it->first = true; return &it->second; } data.emplace_front(true, AlignedVector<VectorizedArrayType>()); return &data.front().second; } template <int dim, typename Number, typename VectorizedArrayType> void MatrixFree<dim, Number, VectorizedArrayType>::release_scratch_data( const AlignedVector<VectorizedArrayType> *scratch) const { using list_type = std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; list_type &data = scratch_pad.get(); for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) if (&it->second == scratch) { Assert(it->first == true, ExcInternalError()); it->first = false; return; } AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); } template <int dim, typename Number, typename VectorizedArrayType> AlignedVector<Number> * MatrixFree<dim, Number, VectorizedArrayType>:: acquire_scratch_data_non_threadsafe() const { for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = scratch_pad_non_threadsafe.begin(); it != scratch_pad_non_threadsafe.end(); ++it) if (it->first == false) { it->first = true; return &it->second; } scratch_pad_non_threadsafe.push_front( std::make_pair(true, AlignedVector<Number>())); return &scratch_pad_non_threadsafe.front().second; } template <int dim, typename Number, typename VectorizedArrayType> void MatrixFree<dim, Number, VectorizedArrayType>:: release_scratch_data_non_threadsafe( const AlignedVector<Number> *scratch) const { for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = scratch_pad_non_threadsafe.begin(); it != scratch_pad_non_threadsafe.end(); ++it) if (&it->second == scratch) { Assert(it->first == true, ExcInternalError()); it->first = false; return; } AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); } // ------------------------------ reinit functions --------------------------- namespace internal { namespace MatrixFreeImplementation { template <int dim, int spacedim> inline std::vector<IndexSet> extract_locally_owned_index_sets( const std::vector<const ::dealii::DoFHandler<dim, spacedim> *> &dofh, const unsigned int level) { std::vector<IndexSet> locally_owned_set; locally_owned_set.reserve(dofh.size()); for (unsigned int j = 0; j < dofh.size(); j++) if (level == numbers::invalid_unsigned_int) locally_owned_set.push_back(dofh[j]->locally_owned_dofs()); else locally_owned_set.push_back(dofh[j]->locally_owned_mg_dofs(level)); return locally_owned_set; } } // namespace MatrixFreeImplementation } // namespace internal template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraints_in, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<const DoFHandler<dim, dim> *> dof_handlers; std::vector<const AffineConstraints<number2> *> constraints; std::vector<QuadratureType> quads; dof_handlers.push_back(&dof_handler); constraints.push_back(&constraints_in); quads.push_back(quad); std::vector<IndexSet> locally_owned_sets = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handlers, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handlers, constraints, locally_owned_sets, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const DoFHandler<dim> & dof_handler, const AffineConstraints<number2> &constraints_in, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<const DoFHandler<dim, dim> *> dof_handlers; std::vector<const AffineConstraints<number2> *> constraints; dof_handlers.push_back(&dof_handler); constraints.push_back(&constraints_in); std::vector<IndexSet> locally_owned_sets = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handlers, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handlers, constraints, locally_owned_sets, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; for (unsigned int q = 0; q < quad.size(); ++q) quad_hp.emplace_back(quad[q]); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dh); this->reinit(mapping, dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>( StaticMappingQ1<dim>::mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; quad_hp.emplace_back(quad); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandler<dim> *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const std::vector<QuadratureType> & quad, const typename MatrixFree<dim, Number, VectorizedArrayType>::AdditionalData &additional_data) { std::vector<IndexSet> locally_owned_set = internal::MatrixFreeImplementation::extract_locally_owned_index_sets( dof_handler, additional_data.mg_level); std::vector<hp::QCollection<dim>> quad_hp; for (unsigned int q = 0; q < quad.size(); ++q) quad_hp.emplace_back(quad[q]); internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), dof_handler, constraint, locally_owned_set, quad_hp, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType, typename MappingType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const MappingType & mapping, const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(mapping, dof_handlers, constraint, quad, additional_data); } template <int dim, typename Number, typename VectorizedArrayType> template <typename QuadratureType, typename number2, typename DoFHandlerType> void MatrixFree<dim, Number, VectorizedArrayType>::reinit( const std::vector<const DoFHandlerType *> & dof_handler, const std::vector<const AffineConstraints<number2> *> &constraint, const QuadratureType & quad, const AdditionalData & additional_data) { static_assert(dim == DoFHandlerType::dimension, "Dimension dim not equal to DoFHandlerType::dimension."); std::vector<const DoFHandler<dim> *> dof_handlers; for (const auto dh : dof_handler) dof_handlers.push_back(dof_handler); this->reinit(dof_handlers, constraint, quad, additional_data); } // ------------------------------ implementation of loops -------------------- // internal helper functions that define how to call MPI data exchange // functions: for generic vectors, do nothing at all. For distributed vectors, // call update_ghost_values_start function and so on. If we have collections // of vectors, just do the individual functions of the components. In order to // keep ghost values consistent (whether we are in read or write mode), we // also reset the values at the end. the whole situation is a bit complicated // by the fact that we need to treat block vectors differently, which use some // additional helper functions to select the blocks and template magic. namespace internal { /** * 用于交换向量间数据的内部类。 * */ template <int dim, typename Number, typename VectorizedArrayType> struct VectorDataExchange { // A shift for the MPI messages to reduce the risk for accidental // interaction with other open communications that a user program might // set up (parallel vectors support unfinished communication). We let // the other vectors use the first 20 assigned numbers and start the // matrix-free communication. static constexpr unsigned int channel_shift = 20; /** * 构造函数。接受MF数据,DG中面部访问的标志和组件的数量。 * */ VectorDataExchange( const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free, const typename dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces vector_face_access, const unsigned int n_components) : matrix_free(matrix_free) , vector_face_access( matrix_free.get_task_info().face_partition_data.empty() ? dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::unspecified : vector_face_access) , ghosts_were_set(false) # ifdef DEAL_II_WITH_MPI , tmp_data(n_components) , requests(n_components) # endif { (void)n_components; if (this->vector_face_access != dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::unspecified) for (unsigned int c = 0; c < matrix_free.n_components(); ++c) AssertDimension( matrix_free.get_dof_info(c).vector_exchanger_face_variants.size(), 5); } /** * 解构器。 * */ ~VectorDataExchange() // NOLINT { # ifdef DEAL_II_WITH_MPI for (unsigned int i = 0; i < tmp_data.size(); ++i) if (tmp_data[i] != nullptr) matrix_free.release_scratch_data_non_threadsafe(tmp_data[i]); # endif } /** * 遍历MF对象中的所有组件,选择其分区器与该组件中的分区器兼容的组件。 * */ template <typename VectorType> unsigned int find_vector_in_mf(const VectorType &vec, const bool check_global_compatibility = true) const { // case 1: vector was set up with MatrixFree::initialize_dof_vector() for (unsigned int c = 0; c < matrix_free.n_components(); ++c) if (vec.get_partitioner().get() == matrix_free.get_dof_info(c).vector_partitioner.get()) return c; // case 2: user provided own partitioner (compatibility mode) for (unsigned int c = 0; c < matrix_free.n_components(); ++c) if (check_global_compatibility ? vec.get_partitioner()->is_globally_compatible( *matrix_free.get_dof_info(c).vector_partitioner) : vec.get_partitioner()->is_compatible( *matrix_free.get_dof_info(c).vector_partitioner)) return c; Assert(false, ExcNotImplemented("Could not find partitioner that fits vector")); return numbers::invalid_unsigned_int; } /** * 为给定的 @p mf_component * 获取分区器,同时考虑到构造函数中设置的vector_face_access。 * */ const internal::MatrixFreeFunctions::VectorDataExchange::Base & get_partitioner(const unsigned int mf_component) const { AssertDimension(matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants.size(), 5); if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::none) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[0]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::values) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[1]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::gradients) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[2]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::values_all_faces) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[3]; else if (vector_face_access == dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces::gradients_all_faces) return *matrix_free.get_dof_info(mf_component) .vector_exchanger_face_variants[4]; else return *matrix_free.get_dof_info(mf_component).vector_exchanger.get(); } /** * 开始为序列向量更新_ghost_value * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int /*component_in_block_vector*/ , const VectorType & /*vec*/ ) {} /** * 对于不支持分割成_start()和finish()阶段的向量,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< !has_update_ghost_values_start<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; vec.update_ghost_values(); } /** * 对于那些支持分成_start()和finish()阶段,但不支持在DoF子集上交换的向量,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; vec.update_ghost_values_start(component_in_block_vector + channel_shift); } /** * 最后,对于那些支持分成_start()和finish()阶段,并且支持在子集DoF上交换的向量,即 * LinearAlgebra::distributed::Vector ,开始更新_ghost_value。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_start(const unsigned int component_in_block_vector, const VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; bool ghosts_set = vec.has_ghost_elements(); if (ghosts_set) ghosts_were_set = true; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && part.n_import_sm_procs() == 0) return; tmp_data[component_in_block_vector] = matrix_free.acquire_scratch_data_non_threadsafe(); tmp_data[component_in_block_vector]->resize_fast( part.n_import_indices()); AssertDimension(requests.size(), tmp_data.size()); part.export_to_ghosted_array_start( component_in_block_vector * 2 + channel_shift, ArrayView<const Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(const_cast<Number *>(vec.begin()) + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); # endif } } /** * 对于不支持分成_start()和finish()阶段的向量和串行向量,完成update_ghost_value。 * */ template < typename VectorType, typename std::enable_if<!has_update_ghost_values_start<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int /*component_in_block_vector*/ , const VectorType & /*vec*/ ) {} /** * 完成对支持分割成_start()和finish()阶段的向量的 * update_ghost_value,但不支持在DoF的子集上进行交换。 * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int component_in_block_vector, const VectorType & vec) { (void)component_in_block_vector; vec.update_ghost_values_finish(); } /** * 完成update_ghost_value,用于_支持分成_start()和finish()阶段的向量,也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector * */ template <typename VectorType, typename std::enable_if< has_update_ghost_values_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void update_ghost_values_finish(const unsigned int component_in_block_vector, const VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertIndexRange(component_in_block_vector, tmp_data.size()); AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || part.n_import_sm_procs() != 0) { part.export_to_ghosted_array_finish( ArrayView<const Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(const_cast<Number *>(vec.begin()) + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), this->requests[component_in_block_vector]); matrix_free.release_scratch_data_non_threadsafe( tmp_data[component_in_block_vector]); tmp_data[component_in_block_vector] = nullptr; } # endif } // let vector know that ghosts are being updated and we can read from // them vec.set_ghost_state(true); } /** * 对串行向量进行启动压缩 * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int /*component_in_block_vector*/ , VectorType & /*vec*/ ) {} /** * 对于不支持分割成_start()和finish()阶段的向量,开始压缩 * */ template <typename VectorType, typename std::enable_if<!has_compress_start<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); vec.compress(dealii::VectorOperation::add); } /** * 对于支持分割成_start()和finish()阶段的向量开始压缩,但不支持在DoF的一个子集上交换。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); vec.compress_start(component_in_block_vector + channel_shift); } /** * 开始压缩那些_支持分割成_start()和finish()阶段的向量,并且也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector 。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_start(const unsigned int component_in_block_vector, VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && part.n_import_sm_procs() == 0) return; tmp_data[component_in_block_vector] = matrix_free.acquire_scratch_data_non_threadsafe(); tmp_data[component_in_block_vector]->resize_fast( part.n_import_indices()); AssertDimension(requests.size(), tmp_data.size()); part.import_from_ghosted_array_start( dealii::VectorOperation::add, component_in_block_vector * 2 + channel_shift, ArrayView<Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(vec.begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); # endif } } /** * 对不支持分成_start()和finish()阶段的向量和串行向量进行完成压缩 * */ template <typename VectorType, typename std::enable_if<!has_compress_start<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int /*component_in_block_vector*/ , VectorType & /*vec*/ ) {} /** * 对于支持分割成_start()和finish()阶段的向量完成压缩,但不支持在DoF的子集上交换。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && !has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int component_in_block_vector, VectorType & vec) { (void)component_in_block_vector; vec.compress_finish(dealii::VectorOperation::add); } /** * 开始压缩那些_支持分割成_start()和finish()阶段的向量,并且也支持在子集DoF上的交换,即 * LinearAlgebra::distributed::Vector 。 * */ template < typename VectorType, typename std::enable_if<has_compress_start<VectorType>::value && has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void compress_finish(const unsigned int component_in_block_vector, VectorType & vec) { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); (void)component_in_block_vector; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertIndexRange(component_in_block_vector, tmp_data.size()); AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || part.n_import_sm_procs() != 0) { part.import_from_ghosted_array_finish( VectorOperation::add, ArrayView<Number>(vec.begin(), part.locally_owned_size()), vec.shared_vector_data(), ArrayView<Number>(vec.begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices()), ArrayView<const Number>( tmp_data[component_in_block_vector]->begin(), part.n_import_indices()), this->requests[component_in_block_vector]); matrix_free.release_scratch_data_non_threadsafe( tmp_data[component_in_block_vector]); tmp_data[component_in_block_vector] = nullptr; } if (Utilities::MPI::job_supports_mpi()) { const int ierr = MPI_Barrier(matrix_free.get_task_info().communicator_sm); AssertThrowMPI(ierr); } # endif } } /** * 重置串行向量的所有幽灵值 * */ template <typename VectorType, typename std::enable_if<is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType & /*vec*/ ) const {} /** * 重置不支持在子集DoF上交换的向量的所有鬼值 * */ template < typename VectorType, typename std::enable_if<!has_exchange_on_subset<VectorType>::value && !is_serial_or_dummy<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType &vec) const { if (ghosts_were_set == true) return; vec.zero_out_ghost_values(); } /** * 重置_支持在子集DoF上交换的向量的所有鬼魂值,即 * LinearAlgebra::distributed::Vector 。 * */ template <typename VectorType, typename std::enable_if<has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void reset_ghost_values(const VectorType &vec) const { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); if (ghosts_were_set == true) return; if (vec.size() != 0) { # ifdef DEAL_II_WITH_MPI AssertDimension(requests.size(), tmp_data.size()); const unsigned int mf_component = find_vector_in_mf(vec); const auto &part = get_partitioner(mf_component); if (part.n_ghost_indices() > 0) { part.reset_ghost_values(ArrayView<Number>( const_cast<LinearAlgebra::distributed::Vector<Number> &>(vec) .begin() + part.locally_owned_size(), matrix_free.get_dof_info(mf_component) .vector_partitioner->n_ghost_indices())); } # endif } // let vector know that it's not ghosted anymore vec.set_ghost_state(false); } /** * 对于_do_ support exchange on a subset of DoFs <==> begin() + ind == * local_element(ind), i.e. LinearAlgebra::distributed::Vector * 的向量区域清零。 * */ template <typename VectorType, typename std::enable_if<has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr> void zero_vector_region(const unsigned int range_index, VectorType &vec) const { static_assert( std::is_same<Number, typename VectorType::value_type>::value, "Type mismatch between VectorType and VectorDataExchange"); if (range_index == numbers::invalid_unsigned_int) vec = Number(); else { const unsigned int mf_component = find_vector_in_mf(vec, false); const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(mf_component); Assert(dof_info.vector_zero_range_list_index.empty() == false, ExcNotInitialized()); Assert(vec.partitioners_are_compatible(*dof_info.vector_partitioner), ExcInternalError()); AssertIndexRange(range_index, dof_info.vector_zero_range_list_index.size() - 1); for (unsigned int id = dof_info.vector_zero_range_list_index[range_index]; id != dof_info.vector_zero_range_list_index[range_index + 1]; ++id) std::memset(vec.begin() + dof_info.vector_zero_range_list[id].first, 0, (dof_info.vector_zero_range_list[id].second - dof_info.vector_zero_range_list[id].first) * sizeof(Number)); } } /** * 对于不支持在DoFs子集上进行交换的向量,将向量区域清零 * <==> begin() + ind == local_element(ind) 但仍然是向量类型。 * */ template < typename VectorType, typename std::enable_if<!has_exchange_on_subset<VectorType>::value, VectorType>::type * = nullptr, typename VectorType::value_type * = nullptr> void zero_vector_region(const unsigned int range_index, VectorType &vec) const { if (range_index == numbers::invalid_unsigned_int || range_index == 0) vec = typename VectorType::value_type(); } /** * 对于非向量类型,即没有 VectorType::value_type * 的类,将向量区域清零。 * */ void zero_vector_region(const unsigned int, ...) const { Assert(false, ExcNotImplemented("Zeroing is only implemented for vector types " "which provide VectorType::value_type")); } const dealii::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free; const typename dealii::MatrixFree<dim, Number, VectorizedArrayType>:: DataAccessOnFaces vector_face_access; bool ghosts_were_set; # ifdef DEAL_II_WITH_MPI std::vector<AlignedVector<Number> *> tmp_data; std::vector<std::vector<MPI_Request>> requests; # endif }; // VectorDataExchange template <typename VectorStruct> unsigned int n_components(const VectorStruct &vec); template <typename VectorStruct> unsigned int n_components_block(const VectorStruct &vec, std::integral_constant<bool, true>) { unsigned int components = 0; for (unsigned int bl = 0; bl < vec.n_blocks(); ++bl) components += n_components(vec.block(bl)); return components; } template <typename VectorStruct> unsigned int n_components_block(const VectorStruct &, std::integral_constant<bool, false>) { return 1; } template <typename VectorStruct> unsigned int n_components(const VectorStruct &vec) { return n_components_block( vec, std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); } template <typename VectorStruct> inline unsigned int n_components(const std::vector<VectorStruct> &vec) { unsigned int components = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) components += n_components_block( vec[comp], std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); return components; } template <typename VectorStruct> inline unsigned int n_components(const std::vector<VectorStruct *> &vec) { unsigned int components = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) components += n_components_block( *vec[comp], std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); return components; } // A helper function to identify block vectors with many components where we // should not try to overlap computations and communication because there // would be too many outstanding communication requests. // default value for vectors that do not have communication_block_size template < typename VectorStruct, typename std::enable_if<!has_communication_block_size<VectorStruct>::value, VectorStruct>::type * = nullptr> constexpr unsigned int get_communication_block_size(const VectorStruct &) { return numbers::invalid_unsigned_int; } template < typename VectorStruct, typename std::enable_if<has_communication_block_size<VectorStruct>::value, VectorStruct>::type * = nullptr> constexpr unsigned int get_communication_block_size(const VectorStruct &) { return VectorStruct::communication_block_size; } // -------------------------------------------------------------------------- // below we have wrappers to distinguish between block and non-block vectors. // -------------------------------------------------------------------------- // // update_ghost_values_start // // update_ghost_values for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_start( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // don't forget to set ghosts_were_set, that otherwise happens // inside VectorDataExchange::update_ghost_values_start() exchanger.ghosts_were_set = vec.has_ghost_elements(); vec.update_ghost_values(); } else { for (unsigned int i = 0; i < vec.n_blocks(); ++i) update_ghost_values_start(vec.block(i), exchanger, channel + i); } } // update_ghost_values for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_start( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.update_ghost_values_start(channel, vec); } // update_ghost_values_start() for vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_start( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_start(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // update_ghost_values_start() for vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_start( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_start(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // update_ghost_values_finish // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_finish( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // do nothing, everything has already been completed in the _start() // call } else for (unsigned int i = 0; i < vec.n_blocks(); ++i) update_ghost_values_finish(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> void update_ghost_values_finish( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.update_ghost_values_finish(channel, vec); } // for vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_finish( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_finish(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void update_ghost_values_finish( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { update_ghost_values_finish(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // compress_start // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_start( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) vec.compress(dealii::VectorOperation::add); else for (unsigned int i = 0; i < vec.n_blocks(); ++i) compress_start(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_start( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.compress_start(channel, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_start( std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_start(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_start( std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_start(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // compress_finish // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_finish( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { if (get_communication_block_size(vec) < vec.n_blocks()) { // do nothing, everything has already been completed in the _start() // call } else for (unsigned int i = 0; i < vec.n_blocks(); ++i) compress_finish(vec.block(i), exchanger, channel + i); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void compress_finish( VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, const unsigned int channel = 0) { exchanger.compress_finish(channel, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_finish( std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_finish(vec[comp], exchanger, component_index); component_index += n_components(vec[comp]); } } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void compress_finish( std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { unsigned int component_index = 0; for (unsigned int comp = 0; comp < vec.size(); comp++) { compress_finish(*vec[comp], exchanger, component_index); component_index += n_components(*vec[comp]); } } // // reset_ghost_values: // // if the input vector did not have ghosts imported, clear them here again // in order to avoid subsequent operations e.g. in linear solvers to work // with ghosts all the time // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void reset_ghost_values( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int i = 0; i < vec.n_blocks(); ++i) reset_ghost_values(vec.block(i), exchanger); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void reset_ghost_values( const VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { exchanger.reset_ghost_values(vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void reset_ghost_values( const std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int comp = 0; comp < vec.size(); comp++) reset_ghost_values(vec[comp], exchanger); } // for std::vector of pointer to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void reset_ghost_values( const std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { // return immediately if there is nothing to do. if (exchanger.ghosts_were_set == true) return; for (unsigned int comp = 0; comp < vec.size(); comp++) reset_ghost_values(*vec[comp], exchanger); } // // zero_vector_region // // for block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void zero_vector_region( const unsigned int range_index, VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int i = 0; i < vec.n_blocks(); ++i) exchanger.zero_vector_region(range_index, vec.block(i)); } // for non-block vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType, typename std::enable_if<!IsBlockVector<VectorStruct>::value, VectorStruct>::type * = nullptr> inline void zero_vector_region( const unsigned int range_index, VectorStruct & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { exchanger.zero_vector_region(range_index, vec); } // for std::vector of vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void zero_vector_region( const unsigned int range_index, std::vector<VectorStruct> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int comp = 0; comp < vec.size(); comp++) zero_vector_region(range_index, vec[comp], exchanger); } // for std::vector of pointers to vectors template <int dim, typename VectorStruct, typename Number, typename VectorizedArrayType> inline void zero_vector_region( const unsigned int range_index, std::vector<VectorStruct *> & vec, VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) { for (unsigned int comp = 0; comp < vec.size(); comp++) zero_vector_region(range_index, *vec[comp], exchanger); } namespace MatrixFreeFunctions { // struct to select between a const interface and a non-const interface // for MFWorker template <typename, typename, typename, typename, bool> struct InterfaceSelector {}; // Version for constant functions template <typename MF, typename InVector, typename OutVector, typename Container> struct InterfaceSelector<MF, InVector, OutVector, Container, true> { using function_type = void (Container::*)( const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const; }; // Version for non-constant functions template <typename MF, typename InVector, typename OutVector, typename Container> struct InterfaceSelector<MF, InVector, OutVector, Container, false> { using function_type = void (Container::*)(const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &); }; } // namespace MatrixFreeFunctions // A implementation class for the worker object that runs the various // operations we want to perform during the matrix-free loop template <typename MF, typename InVector, typename OutVector, typename Container, bool is_constant> class MFWorker : public MFWorkerInterface { public: // An alias to make the arguments further down more readable using function_type = typename MatrixFreeFunctions:: InterfaceSelector<MF, InVector, OutVector, Container, is_constant>:: function_type; // constructor, binds all the arguments to this class MFWorker(const MF & matrix_free, const InVector & src, OutVector & dst, const bool zero_dst_vector_setting, const Container & container, function_type cell_function, function_type face_function, function_type boundary_function, const typename MF::DataAccessOnFaces src_vector_face_access = MF::DataAccessOnFaces::none, const typename MF::DataAccessOnFaces dst_vector_face_access = MF::DataAccessOnFaces::none, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop = {}, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop = {}, const unsigned int dof_handler_index_pre_post = 0) : matrix_free(matrix_free) , container(const_cast<Container &>(container)) , cell_function(cell_function) , face_function(face_function) , boundary_function(boundary_function) , src(src) , dst(dst) , src_data_exchanger(matrix_free, src_vector_face_access, n_components(src)) , dst_data_exchanger(matrix_free, dst_vector_face_access, n_components(dst)) , src_and_dst_are_same(PointerComparison::equal(&src, &dst)) , zero_dst_vector_setting(zero_dst_vector_setting && !src_and_dst_are_same) , operation_before_loop(operation_before_loop) , operation_after_loop(operation_after_loop) , dof_handler_index_pre_post(dof_handler_index_pre_post) {} // Runs the cell work. If no function is given, nothing is done virtual void cell(const std::pair<unsigned int, unsigned int> &cell_range) override { if (cell_function != nullptr && cell_range.second > cell_range.first) for (unsigned int i = 0; i < matrix_free.n_active_fe_indices(); ++i) { const auto cell_subrange = matrix_free.create_cell_subrange_hp_by_index(cell_range, i); if (cell_subrange.second <= cell_subrange.first) continue; (container.* cell_function)(matrix_free, this->dst, this->src, cell_subrange); } } virtual void cell(const unsigned int range_index) override { process_range(cell_function, matrix_free.get_task_info().cell_partition_data_hp_ptr, matrix_free.get_task_info().cell_partition_data_hp, range_index); } virtual void face(const unsigned int range_index) override { process_range(face_function, matrix_free.get_task_info().face_partition_data_hp_ptr, matrix_free.get_task_info().face_partition_data_hp, range_index); } virtual void boundary(const unsigned int range_index) override { process_range(boundary_function, matrix_free.get_task_info().boundary_partition_data_hp_ptr, matrix_free.get_task_info().boundary_partition_data_hp, range_index); } private: void process_range(const function_type & fu, const std::vector<unsigned int> &ptr, const std::vector<unsigned int> &data, const unsigned int range_index) { if (fu == nullptr) return; for (unsigned int i = ptr[range_index]; i < ptr[range_index + 1]; ++i) (container.*fu)(matrix_free, this->dst, this->src, std::make_pair(data[2 * i], data[2 * i + 1])); } public: // Starts the communication for the update ghost values operation. We // cannot call this update if ghost and destination are the same because // that would introduce spurious entries in the destination (there is also // the problem that reading from a vector that we also write to is usually // not intended in case there is overlap, but this is up to the // application code to decide and we cannot catch this case here). virtual void vector_update_ghosts_start() override { if (!src_and_dst_are_same) internal::update_ghost_values_start(src, src_data_exchanger); } // Finishes the communication for the update ghost values operation virtual void vector_update_ghosts_finish() override { if (!src_and_dst_are_same) internal::update_ghost_values_finish(src, src_data_exchanger); } // Starts the communication for the vector compress operation virtual void vector_compress_start() override { internal::compress_start(dst, dst_data_exchanger); } // Finishes the communication for the vector compress operation virtual void vector_compress_finish() override { internal::compress_finish(dst, dst_data_exchanger); if (!src_and_dst_are_same) internal::reset_ghost_values(src, src_data_exchanger); } // Zeros the given input vector virtual void zero_dst_vector_range(const unsigned int range_index) override { if (zero_dst_vector_setting) internal::zero_vector_region(range_index, dst, dst_data_exchanger); } virtual void cell_loop_pre_range(const unsigned int range_index) override { if (operation_before_loop) { const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(dof_handler_index_pre_post); if (range_index == numbers::invalid_unsigned_int) { // Case with threaded loop -> currently no overlap implemented dealii::parallel::apply_to_subranges( 0U, dof_info.vector_partitioner->locally_owned_size(), operation_before_loop, internal::VectorImplementation::minimum_parallel_grain_size); } else { AssertIndexRange(range_index, dof_info.cell_loop_pre_list_index.size() - 1); for (unsigned int id = dof_info.cell_loop_pre_list_index[range_index]; id != dof_info.cell_loop_pre_list_index[range_index + 1]; ++id) operation_before_loop(dof_info.cell_loop_pre_list[id].first, dof_info.cell_loop_pre_list[id].second); } } } virtual void cell_loop_post_range(const unsigned int range_index) override { if (operation_after_loop) { const internal::MatrixFreeFunctions::DoFInfo &dof_info = matrix_free.get_dof_info(dof_handler_index_pre_post); if (range_index == numbers::invalid_unsigned_int) { // Case with threaded loop -> currently no overlap implemented dealii::parallel::apply_to_subranges( 0U, dof_info.vector_partitioner->locally_owned_size(), operation_after_loop, internal::VectorImplementation::minimum_parallel_grain_size); } else { AssertIndexRange(range_index, dof_info.cell_loop_post_list_index.size() - 1); for (unsigned int id = dof_info.cell_loop_post_list_index[range_index]; id != dof_info.cell_loop_post_list_index[range_index + 1]; ++id) operation_after_loop(dof_info.cell_loop_post_list[id].first, dof_info.cell_loop_post_list[id].second); } } } private: const MF & matrix_free; Container & container; function_type cell_function; function_type face_function; function_type boundary_function; const InVector &src; OutVector & dst; VectorDataExchange<MF::dimension, typename MF::value_type, typename MF::vectorized_value_type> src_data_exchanger; VectorDataExchange<MF::dimension, typename MF::value_type, typename MF::vectorized_value_type> dst_data_exchanger; const bool src_and_dst_are_same; const bool zero_dst_vector_setting; const std::function<void(const unsigned int, const unsigned int)> operation_before_loop; const std::function<void(const unsigned int, const unsigned int)> operation_after_loop; const unsigned int dof_handler_index_pre_post; }; /** * 一个内部类,将三个函数指针转换为上述带有虚拟函数的方案。 * */ template <class MF, typename InVector, typename OutVector> struct MFClassWrapper { using function_type = std::function<void(const MF &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)>; MFClassWrapper(const function_type cell, const function_type face, const function_type boundary) : cell(cell) , face(face) , boundary(boundary) {} void cell_integrator(const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (cell) cell(mf, dst, src, range); } void face_integrator(const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (face) face(mf, dst, src, range); } void boundary_integrator( const MF & mf, OutVector & dst, const InVector & src, const std::pair<unsigned int, unsigned int> &range) const { if (boundary) boundary(mf, dst, src, range); } const function_type cell; const function_type face; const function_type boundary; }; } // end of namespace internal template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, false, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &cell_operation, const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> &face_operation, const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & boundary_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, face_operation, boundary_operation); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, false, *owning_class, function_pointer, nullptr, nullptr, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( void (CLASS::*cell_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*face_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, void (CLASS::*boundary_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, cell_operation, face_operation, boundary_operation, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const bool zero_dst_vector) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::cell_loop( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector &src, const std::function<void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function<void(const unsigned int, const unsigned int)> & operation_after_loop, const unsigned int dof_handler_index_pre_post) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, false, *owning_class, function_pointer, nullptr, nullptr, DataAccessOnFaces::none, DataAccessOnFaces::none, operation_before_loop, operation_after_loop, dof_handler_index_pre_post); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop( void (CLASS::*cell_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*face_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), void (CLASS::*boundary_operation)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces dst_vector_face_access, const DataAccessOnFaces src_vector_face_access) const { internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, cell_operation, face_operation, boundary_operation, src_vector_face_access, dst_vector_face_access); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &) const, const CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, true> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename CLASS, typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( void (CLASS::*function_pointer)( const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &), CLASS * owning_class, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, CLASS, false> worker(*this, src, dst, zero_dst_vector, *owning_class, function_pointer, nullptr, nullptr, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } template <int dim, typename Number, typename VectorizedArrayType> template <typename OutVector, typename InVector> inline void MatrixFree<dim, Number, VectorizedArrayType>::loop_cell_centric( const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, OutVector &, const InVector &, const std::pair<unsigned int, unsigned int> &)> & cell_operation, OutVector & dst, const InVector & src, const bool zero_dst_vector, const DataAccessOnFaces src_vector_face_access) const { auto src_vector_face_access_temp = src_vector_face_access; if (DataAccessOnFaces::gradients == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; else if (DataAccessOnFaces::values == src_vector_face_access_temp) src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; using Wrapper = internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector>; Wrapper wrap(cell_operation, nullptr, nullptr); internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, InVector, OutVector, Wrapper, true> worker(*this, src, dst, zero_dst_vector, wrap, &Wrapper::cell_integrator, &Wrapper::face_integrator, &Wrapper::boundary_integrator, src_vector_face_access_temp, DataAccessOnFaces::none); task_info.loop(worker); } #endif // ifndef DOXYGEN DEAL_II_NAMESPACE_CLOSE #endif
[ "jiaqiwang969@gmail.com" ]
jiaqiwang969@gmail.com
0d60a0f0c0031d84fd6522338a76d0e2dd6850ee
a3effde3c27c072090f0021bdae3306961eb2d92
/Codeforces/1221/B.cpp
1fab4dd6106cf6181137eac291ce7851236cda08
[]
no_license
anmolgup/Competitive-programming-code
f4837522bf648c90847d971481f830a47722da29
329101c4e45be68192715c9a0718f148e541b58b
refs/heads/master
2022-12-03T19:00:40.261727
2020-08-08T09:21:58
2020-08-08T09:21:58
286,011,774
1
0
null
null
null
null
UTF-8
C++
false
false
4,308
cpp
#include<bits/stdc++.h> using namespace std; //Optimisations #pragma GCC target ("avx2") #pragma GCC optimization ("unroll-loops") #pragma GCC optimize("O2") //shortcuts for functions #define pb push_back #define mp make_pair #define ff first #define ss second #define endl "\n" #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(),v.rend() #define th(n) cout<<n<<endl #define gc getchar_unlocked #define ms(s, n) memset(s, n, sizeof(s)) #define prec(n) fixed<<setprecision(n) #define n_l '\n' // make it python #define gcd __gcd #define append push_back #define str to_string #define upper(s) transform(s.begin(),s.end(),s.begin(),::toupper) #define lower(s) transform(s.begin(),s.end(),s.begin(),::tolower) #define print(arr) for(auto el: arr) cout<<el<<" ";cout<<endl // utility functions shortcuts #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define sswap(a,b) {a=a^b;b=a^b;a=a^b;} #define swap(a,b) {auto temp=a; a=b; b=temp;} #define set0(dp) memset(dp,0,sizeof(dp)); #define bits(x) __builtin_popcount(x) #define SORT(v) sort(all(v)) #define endl "\n" #define forr(i,n) for(ll i=0;i<n;i++) #define formatrix(i,n) for(ll i=0;i<n;i++, cout<<"\n") #define eof (scanf("%d" ,&n))!=EOF // declaration shortcuts #define vll vector<ll> #define vvl vector<vector<ll>> #define vpll vector<pair<ll,ll> > #define pll pair<ll,ll> #define ppl pair<ll,pll> #define ull unsigned long long #define ll long long #define mll map< ll, ll > #define sll set< ll > #define uni(v) v.erase(unique(v.begin(),v.end()),v.end()); #define ini(a, v) memset(a, v, sizeof(a)) // Constants constexpr int dx[] = {-1, 0, 1, 0, 1, 1, -1, -1}; constexpr int dy[] = {0, -1, 0, 1, 1, -1, 1, -1}; constexpr ll INF = 1999999999999999997; constexpr int inf= INT_MAX; constexpr int MAXSIZE = int(1e6)+5; constexpr auto PI = 3.14159265358979323846L; constexpr auto oo = numeric_limits<int>::max() / 2 - 2; constexpr auto eps = 1e-6; constexpr auto mod = 1000000007; constexpr auto MOD = 1000000007; constexpr auto MOD9 = 1000000009; constexpr auto maxn = 200006; // Debugging // For reference: https://codeforces.com/blog/entry/65311 #define dbg(...) cout << "[" << #__VA_ARGS__ << "]: "; cout << to_string(__VA_ARGS__) << endl template <typename T, size_t N> int SIZE(const T (&t)[N]){ return N; } template<typename T> int SIZE(const T &t){ return t.size(); } string to_string(string s, int x1=0, int x2=1e9){ return '"' + ((x1 < s.size()) ? s.substr(x1, x2-x1+1) : "") + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(char c){ return string({c}); } template<size_t N> string to_string(bitset<N> &b, int x1=0, int x2=1e9){ string t = ""; for(int __iii__ = min(x1,SIZE(b)), __jjj__ = min(x2, SIZE(b)-1); __iii__ <= __jjj__; ++__iii__){ t += b[__iii__] + '0'; } return '"' + t + '"'; } template <typename A, typename... C> string to_string(A (&v), int x1=0, int x2=1e9, C... coords); int l_v_l_v_l = 0, t_a_b_s = 0; template <typename A, typename B> string to_string(pair<A, B> &p) { l_v_l_v_l++; string res = "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; l_v_l_v_l--; return res; } template <typename A, typename... C> string to_string(A (&v), int x1, int x2, C... coords) { int rnk = rank<A>::value; string tab(t_a_b_s, ' '); string res = ""; bool first = true; if(l_v_l_v_l == 0) res += n_l; res += tab + "["; x1 = min(x1, SIZE(v)), x2 = min(x2, SIZE(v)); auto l = begin(v); advance(l, x1); auto r = l; advance(r, (x2-x1) + (x2 < SIZE(v))); for (auto e = l; e != r; e = next(e)) { if (!first) { res += ", "; } first = false; l_v_l_v_l++; if(e != l){ if(rnk > 1) { res += n_l; t_a_b_s = l_v_l_v_l; }; } else{ t_a_b_s = 0; } res += to_string(*e, coords...); l_v_l_v_l--; } res += "]"; if(l_v_l_v_l == 0) res += n_l; return res; } void dbgs(){;} template<typename Heads, typename... Tails> void dbgs(Heads H, Tails... T){ cout << to_string(H) << " | "; dbgs(T...); } #define dbgm(...) cout << "[" << #__VA_ARGS__ << "]: "; dbgs(__VA_ARGS__); cout << endl; #define n_l '\n' int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll n; cin>>n; forr(i,n) { forr(j,n) { if((i + j)%2) cout<<"B"; else cout<<"W"; } cout<<endl; } }
[ "anmolgupta9557@gmail.com" ]
anmolgupta9557@gmail.com
ca51b1bece3f7ac98ba449a10d5789389d716611
0acbe61f45c084b6bcfd2a6c7268e42197ebffe2
/IB/painters-partition-problem.cpp
445f0046b592a52f56bfb687c08e4102a4e6736a
[]
no_license
projectescape/cp-archive
a86c6fd844978e2e34690e7ba90c68968b72395a
2beaf2f554af413054052a6ce8d9cd58552bcc10
refs/heads/master
2021-07-06T21:10:11.556169
2020-09-27T16:43:15
2020-09-27T16:43:15
193,668,314
0
1
null
2020-09-25T08:16:37
2019-06-25T08:37:04
C++
UTF-8
C++
false
false
706
cpp
int Solution::paint(int A, int B, vector<int> &C) { int e = 0, s = INT_MIN; for (auto i : C) { e += i; s = max(s, i); } long long ans = LLONG_MAX, i, j, k, m; for (; s <= e;) { m = (s + e) / 2; for (i = j = k = 0; i < C.size() && k < A; i++) { j += C[i]; if (j > m) { i--; k++; j = 0; } else if (j == m) { k++; j = 0; } } if (k < A || (k == A && i == C.size())) { ans = min(ans, m); e = m - 1; } else { s = m + 1; } } return (ans * B) % 10000003; }
[ "escaperealityproject@gmail.com" ]
escaperealityproject@gmail.com
0c97d88e93ca3a05fafef3db9a61ceb83f6400f8
d09092dbe69c66e916d8dd76d677bc20776806fe
/.libs/puno_automatic_generated/inc/types/com/sun/star/security/CertificateException.hpp
c0f25e759e25f1d3aca1b96ec39d326779b30f33
[]
no_license
GXhua/puno
026859fcbc7a509aa34ee857a3e64e99a4568020
e2f8e7d645efbde5132b588678a04f70f1ae2e00
refs/heads/master
2020-03-22T07:35:46.570037
2018-07-11T02:19:26
2018-07-11T02:19:26
139,710,567
0
0
null
2018-07-04T11:03:58
2018-07-04T11:03:58
null
UTF-8
C++
false
false
2,164
hpp
#ifndef INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP #define INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP #include "sal/config.h" #include "com/sun/star/security/CertificateException.hdl" #include "com/sun/star/uno/SecurityException.hpp" #include "com/sun/star/uno/Type.hxx" #include "cppu/unotype.hxx" namespace com { namespace sun { namespace star { namespace security { inline CertificateException::CertificateException() : ::css::uno::SecurityException() { } inline CertificateException::CertificateException(const ::rtl::OUString& Message_, const ::css::uno::Reference< ::css::uno::XInterface >& Context_) : ::css::uno::SecurityException(Message_, Context_) { } #if !defined LIBO_INTERNAL_ONLY CertificateException::CertificateException(CertificateException const & the_other): ::css::uno::SecurityException(the_other) {} CertificateException::~CertificateException() {} CertificateException & CertificateException::operator =(CertificateException const & the_other) { //TODO: Just like its implicitly-defined counterpart, this function definition is not exception-safe ::css::uno::SecurityException::operator =(the_other); return *this; } #endif } } } } namespace com { namespace sun { namespace star { namespace security { inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::security::CertificateException const *) { static typelib_TypeDescriptionReference * the_type = 0; if ( !the_type ) { const ::css::uno::Type& rBaseType = ::cppu::UnoType< const ::css::uno::SecurityException >::get(); typelib_static_compound_type_init( &the_type, typelib_TypeClass_EXCEPTION, "com.sun.star.security.CertificateException", rBaseType.getTypeLibType(), 0, 0 ); } return * reinterpret_cast< const ::css::uno::Type * >( &the_type ); } } } } } SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::security::CertificateException const *) { return ::cppu::UnoType< ::css::security::CertificateException >::get(); } #endif // INCLUDED_COM_SUN_STAR_SECURITY_CERTIFICATEEXCEPTION_HPP
[ "guoxinhua@10.10.12.142" ]
guoxinhua@10.10.12.142
a784dbbdebcf2e0528cc181492f69c0d1c23feab
90d253b075c47054ab1d6bf6206f37e810330068
/Codeforces/1689/d.cpp
9e45d14aa708c54b75495445b43bceb3acc29837
[ "MIT" ]
permissive
eyangch/competitive-programming
45684aa804cbcde1999010332627228ac1ac4ef8
de9bb192c604a3dfbdd4c2757e478e7265516c9c
refs/heads/master
2023-07-10T08:59:25.674500
2023-06-25T09:30:43
2023-06-25T09:30:43
178,763,969
22
8
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
#include <bits/stdc++.h> #define endl '\n' #define eat cin #define moo cout #define int long long using namespace std; int T, N, M, d[1000][1000]; string b[1000]; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; int dist(int x1, int y1, int x2, int y2){ return abs(x1 - x2) + abs(y1 - y2); } int32_t main(){ eat.tie(0) -> sync_with_stdio(0); eat >> T; while(T--){ eat >> N >> M; for(int i = 0; i < N; i++){ eat >> b[i]; } for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) d[i][j] = -1; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(b[i][j] == 'W') continue; d[0][0] = max(d[0][0], dist(0, 0, i, j)); d[N-1][0] = max(d[N-1][0], dist(N-1, 0, i, j)); d[0][M-1] = max(d[0][M-1], dist(0, M-1, i, j)); d[N-1][M-1] = max(d[N-1][M-1], dist(N-1, M-1, i, j)); } } priority_queue<pair<int, pair<int, int>>> pq; pq.push({d[0][0], {0, 0}}); pq.push({d[N-1][0], {N-1, 0}}); pq.push({d[0][M-1], {0, M-1}}); pq.push({d[N-1][M-1], {N-1, M-1}}); while(!pq.empty()){ int cd = pq.top().first; int cx = pq.top().second.first; int cy = pq.top().second.second; pq.pop(); for(int i = 0; i < 4; i++){ int nx = cx + dx[i]; int ny = cy + dy[i]; if(nx < 0 || ny < 0 || nx >= N || ny >= M) continue; if(d[nx][ny] != -1) continue; d[nx][ny] = cd - 1; pq.push({cd-1, {nx, ny}}); } } int best = 9999999; int bx = 0, by = 0; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(d[i][j] < best){ best = d[i][j]; bx = i; by = j; } } } moo << bx+1 << ' ' << by+1 << endl; } }
[ "eyangch@gmail.com" ]
eyangch@gmail.com
dae5293442e4970e4bd339184f2219cfaec69a65
4d68064a06d8dc390762564c216b6040c28c2fd1
/0141/724432WA.cpp
c2b9adc1a8f547445286f0e70f86877970ba8b14
[]
no_license
pocke/aoj_codes
ea35fe295cd87080f9af6c9f23d38476820910b5
668e46de83d7f95fbed1f82df058a006fb3e05f6
refs/heads/master
2021-01-23T02:41:23.089223
2014-01-24T04:04:46
2014-01-24T04:04:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,555
cpp
#include <iostream> using namespace std; class Guruguru { public: Guruguru(int n); ~Guruguru(); void Show(); private: char** m_guruguru; int m_n; int m_now_i; int m_now_j; int m_direction; // 0:上 1:右 2:下 3:左 void make_guruguru(); void put_point(); void move_point(); void change_direction(); bool check_point(); }; Guruguru::Guruguru(int n) { m_n = n; m_guruguru = new char*[m_n]; for (int i=0; i<m_n; i++) { m_guruguru[i] = new char[m_n]; } for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { m_guruguru[i][j] = ' '; } } m_now_i = m_n-1; m_now_j = 0; m_direction = 0; make_guruguru(); } Guruguru::~Guruguru() { for (int i=0; i<m_n; i++) { delete[] m_guruguru[i]; } delete[] m_guruguru; } void Guruguru::make_guruguru() { int num = 0; while(true) { put_point(); if (! check_point() ) { if ( num == m_n-1 ) return; change_direction(); num++; } move_point(); } } void Guruguru::put_point() { m_guruguru[m_now_i][m_now_j] = '#'; } void Guruguru::move_point() { switch(m_direction) { case 0: m_now_i--; break; case 1: m_now_j++; break; case 2: m_now_i++; break; case 3: m_now_j--; break; } } void Guruguru::change_direction() { switch(m_direction) { case 3: m_direction = 0; break; default: m_direction++; break; } } bool Guruguru::check_point() { int next_i = m_now_i; int next_j = m_now_j; int next_next_i = next_i; int next_next_j = next_j; switch(m_direction) { case 0: next_i--; next_next_i-=2; break; case 1: next_j++; next_next_j+=2; break; case 2: next_i++; next_next_i+=2; break; case 3: next_j--; next_next_j-=2; break; } if ( next_i < 0 || m_n <= next_i || next_j < 0 || m_n <= next_j ) { return false; } else if ( next_next_i < 0 || m_n <= next_next_i || next_next_j < 0 || m_n <= next_next_j ) { return true; } else { if ( '#' == m_guruguru[next_next_i][next_next_j] ) { return false; } return true; } } void Guruguru::Show() { for (int i=0; i<m_n; i++) { for (int j=0; j<m_n; j++) { cout << m_guruguru[i][j] << flush; } cout << endl; } } int main() { int d; // データセットの個数 cin >> d; for (int dataset=0; dataset<d; dataset++) { int n; // 辺の長さ cin >> n; Guruguru guruguru(n); guruguru.Show(); cout << endl; } }
[ "p.ck.t22@gmail.com" ]
p.ck.t22@gmail.com
909059235b295f406534258033dd51c9e217b4f4
1d4ef971ba3294a07011fafc08a8be78f6062840
/src/pdb_serial.hpp
d6157465a8bed406f65d555bd9e746fc14576721
[]
no_license
tcgriffith/nsp
153f635b67ef1a598f52b27ee7486f2b8bb3ed3d
021c5b590cbafb51c68ea6f3cbad6cfc3951570d
refs/heads/master
2021-01-25T11:20:37.339250
2017-12-05T23:42:44
2017-12-05T23:42:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,034
hpp
#pragma once #include <fstream> #include <sstream> #include "pdb_molecule.hpp" BEGIN_JN class MolSerial { public: std::fstream m_stream; MolSerial(S out, std::ios::openmode mode) { m_stream.open(out, std::ios::binary | mode); } ~MolSerial() { m_stream.close(); } void write(char c) { m_stream.write(reinterpret_cast<const char*>(&c), sizeof(char)); } void read(char &c) { m_stream.read(reinterpret_cast<char*>(&c), sizeof(char)); } template<typename T, JN_ENABLE(std::is_integral<T>::value)> void write(T n) { short m = short(n); m_stream.write(reinterpret_cast<const char*>(&m), sizeof(short)); } template<typename T, JN_ENABLE(std::is_integral<T>::value)> void read(T &n) { short m; m_stream.read(reinterpret_cast<char*>(&m), sizeof(short)); n = T(m); } template<typename T, JN_ENABLE(std::is_floating_point<T>::value)> void write(T n) { float m = float(n); m_stream.write(reinterpret_cast<const char*>(&m), sizeof(float)); } template<typename T, JN_ENABLE(std::is_floating_point<T>::value)> void read(T &n) { float m; m_stream.read(reinterpret_cast<char*>(&m), sizeof(float)); n = T(m); } void write(const S &s) { //write(s.size()); m_stream.write(s.c_str(), s.size() + 1); } void read(S &s) { char c[2]; std::ostringstream stream; while (true) { m_stream.read(c, 1); if (c[0] == '\0') break; stream << c[0]; } s = stream.str(); } template<typename T1, typename T2, typename... Rest> void write(T1 && t1, T2 && t2, Rest && ...rest) { write(t1); write(t2, rest...); } template<typename T1, typename T2, typename... Rest> void read(T1 && t1, T2 && t2, Rest && ...rest) { read(t1); read(t2, rest...); } void write(const Atom &atom) { write('A', atom.name, atom.num, atom.mass, atom[0], atom[1], atom[2]); } void read(Atom &atom) { read(atom.name, atom.num, atom.mass, atom[0], atom[1], atom[2]); } void write(const Residue &res) { write('R', res.name, res.num, res.m_cg); for (auto && atom : res) { write(atom); } write('r'); } void read(Residue &res) { char c; read(res.name, res.num, res.m_cg); while (true) { read(c); if (c == 'r') { return; } else if (c == 'A') { res.push_back(Atom{}); read(res.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write(const Chain &chain) { write('C', chain.name, chain.type, chain.model_name, chain.m_cg); for (auto && res : chain) { write(res); } write('c'); } void read(Chain &chain) { char c; read(chain.name, chain.type, chain.model_name, chain.m_cg); while (true) { read(c); if (c == 'c') { return; } else if (c == 'R') { chain.push_back(Residue{}); read(chain.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write(const Model &model) { write('M', model.name, model.num, model.type, model.m_cg); for (auto && chain : model) { write(chain); } write('m'); } void read(Model &model) { char c; read(model.name, model.num, model.type, model.m_cg); while (true) { read(c); if (c == 'm') { return; } else if (c == 'C') { model.push_back(Chain{}); read(model.back()); } else { throw "This is not a standard '.jn' file! Illegal " + c; } } } void write_mol(S filename) { for_each_model(filename, [this](const Model &model, int i) { write(model); }); write('o'); } void write(const Molecule &mol) { for (auto && model : mol) { write(model); } write('o'); } void read(Molecule &mol) { char c; while (true) { read(c); if (c == 'o') { break; } else if (c == 'M') { mol.push_back(Model{}); read(mol.back()); } else { throw "This is not a standard '.jn' file ! Illegal " + c; } } } }; }
[ "wj_hust08@hust.edu.cn" ]
wj_hust08@hust.edu.cn
5fb2296c97591754976dfd43970a4c051efe4c28
c210a7753fb88b632cd13eb0f1b0b2fef5ad1423
/src/include/CheckConservation.h
35d2b19545f386a846d108ce9bae1a3c4ceab97c
[]
no_license
vijaysm/Camellia
879840f37fa0c3cde55fc1e01452f5fbc87e185e
a34c27a783028cbd70dd0544187e2f188784a6d7
refs/heads/master
2021-01-16T00:43:04.063673
2016-09-06T19:39:21
2016-09-06T19:39:21
41,429,234
0
0
null
2015-08-26T14:07:23
2015-08-26T14:07:21
null
UTF-8
C++
false
false
3,350
h
// @HEADER // *********************************************************************** // // © 2016 UChicago Argonne. For licensing details, see LICENSE-Camellia in the licenses directory. // // Questions? Contact Nathan V. Roberts (nate@nateroberts.com) // // *********************************************************************** // @HEADER #ifndef CHECKCONSERVATION_H #define CHECKCONSERVATION_H #include "InnerProductScratchPad.h" #include "Mesh.h" #include "CamelliaCellTools.h" #include <Teuchos_Tuple.hpp> namespace Camellia { Teuchos::Tuple<double, 3> checkConservation(TFunctionPtr<double> flux, TFunctionPtr<double> source, Teuchos::RCP<Mesh> mesh, int cubatureEnrichment = 0) { double maxMassFluxIntegral = 0.0; double totalMassFlux = 0.0; double totalAbsMassFlux = 0.0; vector<ElementPtr> elems = mesh->activeElements(); for (vector<ElementPtr>::iterator it = elems.begin(); it != elems.end(); ++it) { ElementPtr elem = *it; int cellID = elem->cellID(); ElementTypePtr elemType = elem->elementType(); Intrepid::FieldContainer<double> physicalCellNodes = mesh->physicalCellNodesForCell(cellID); BasisCachePtr basisCache = BasisCache::basisCacheForCell(mesh, cellID, cubatureEnrichment); Intrepid::FieldContainer<double> volumeIntegral(1); source->integrate(volumeIntegral, basisCache, true); int numSides = CamelliaCellTools::getSideCount(basisCache->cellTopology()); double surfaceIntegral = 0; for (int sideIndex = 0; sideIndex < numSides; sideIndex++) { Intrepid::FieldContainer<double> sideIntegral(1); flux->integrate(sideIntegral, basisCache->getSideBasisCache(sideIndex), true); surfaceIntegral += sideIntegral(0); } double massFlux = surfaceIntegral - volumeIntegral(0); maxMassFluxIntegral = max(abs(massFlux), maxMassFluxIntegral); totalMassFlux += massFlux; totalAbsMassFlux += abs( massFlux ); } Teuchos::Tuple<double, 3> fluxImbalances = Teuchos::tuple(maxMassFluxIntegral, totalMassFlux, totalAbsMassFlux); return fluxImbalances; } double computeFluxOverElementSides(TFunctionPtr<double> flux, Teuchos::RCP<Mesh> mesh, vector< pair<ElementPtr, int> > originalElemFaces, int cubatureEnrichment=0) { double totalMassFlux = 0.0; for (vector< pair<ElementPtr, int> >::iterator origIt = originalElemFaces.begin(); origIt != originalElemFaces.end(); ++origIt) { int originalSideIndex = origIt->second; vector< pair<int, int> > cellFaces = origIt->first->getDescendantsForSide(originalSideIndex); for (vector< pair<int, int> >::iterator it = cellFaces.begin(); it != cellFaces.end(); ++it) { int cellID = it->first; int sideIndex = it->second; BasisCachePtr basisCache = BasisCache::basisCacheForCell(mesh, cellID, cubatureEnrichment); BasisCachePtr sideBasisCache = basisCache->getSideBasisCache(sideIndex); // Intrepid::FieldContainer<double> physicalCubaturePoints = sideBasisCache->getPhysicalCubaturePoints(); // double xCell0 = physicalCubaturePoints(0,0,0); // cout << physicalCubaturePoints << endl; Intrepid::FieldContainer<double> sideIntegral(1); flux->integrate(sideIntegral, sideBasisCache, true); totalMassFlux += sideIntegral(0); } } return totalMassFlux; } } #endif /* end of include guard: CHECKCONSERVATION_H */
[ "nvroberts@alcf.anl.gov" ]
nvroberts@alcf.anl.gov
9290045312b20ec137e9a21d0eb2114a3578eacc
f7276082f5e4d00b45ed7f49f1cd4e3221664f1b
/Branches/preNYC/Sensors/IMU.h
01699c4e45ac7beb656cf6a288ba1b28344c98b7
[]
no_license
Team846/code-2012
2e2448e09348717403222e850354019568262fe5
9a59ef25a7d52fcab97cec0ae064d86117b8b555
refs/heads/master
2021-04-30T23:00:05.958692
2012-12-18T00:04:53
2012-12-18T00:04:53
68,423,200
0
0
null
null
null
null
UTF-8
C++
false
false
3,961
h
#ifndef IMU_H_ #define IMU_H_ #include "../Log/Loggable.h" class I2C; class ActionData; /*! * I2C inteface with Arduimu, running specific code on the IMU side. * @author Robert Ying * @author Brian Axelrod * @author Alexander Kanaris */ class IMU: public Loggable { public: /*! * Constructs an IMU object and initializes the I2C * @param address I2C address of the slave, defaults to 0x29. 7-bit. * @param module digital module to init I2C on, defaults to 1 */ explicit IMU(uint8_t address = kAddress, uint8_t module = 1); /*! * Destroys an IMU object and deletes the I2C handle */ virtual ~IMU(); /*! * To be called before any get() methods, such that data is fresh. blocking. */ void update(); /*! * Updates actiondata directly * @param action pointer to actiondata */ void update(ActionData * action); /*! * Returns most recent roll value * @return roll, in degrees */ double getRoll(); /*! * Returns most recent yaw value * @return yaw, in degrees */ double getYaw(); /*! * Returns most recent pitch value * @return pitch, in degrees */ double getPitch(); /*! * Returns raw acceleration in x in m/s^2 * @return acceleration in x */ double getAccelX(); /*! * Returns raw acceleration in y in m/s^2 * @return acceleration in y */ double getAccelY(); /*! * Returns raw acceleration in z in m/s^2 * @return acceleration in z */ double getAccelZ(); /*! * Returns raw angular rate about x in degrees per second * @return angular rate about x */ double getGyroX(); /*! * Returns raw angular rate about y in degrees per second * @return angular rate about y */ double getGyroY(); /*! * Returns raw angular rate about y in degrees per second * @return angular rate about y */ double getGyroYDelta(); /*! * Returns raw angular rate about z in degrees per second * @return angular rate about z */ double getGyroZ(); /*! * Prints all data via printf for debug */ void printAll(); /*! * Logs data */ virtual void log(); /*! * Starts the task */ void releaseSemaphore(); /*! * */ void startTask(); /*! * */ void stopTask(); private: /*! * Helper method to get kNumPackets of data and fill m_i2c_buf * @return 0 on success */ int getPacket(); /*! * starts the task * @param ptr to the IMU */ static void taskEntryPoint(int ptr); /*! * Is the task */ void task(); const static uint8_t kAddress = (0x29); // 7-bit default address const static uint8_t kNumPackets = 4; // number of 7-byte packets to concatenate const static double kAccelConversion = 0.001; const static double kGyroConversion = 0.001; /*! * indices in the data packet of various variables */ enum DATA_STRUCT { STATUS = 0x00, //!< STATUS number of updates on IMU since last request PITCH = 0x01, //!< PITCH fixed-point pitch in degrees * 100 ROLL = 0x03, //!< ROLL fixed-point roll in degrees * 100 YAW = 0x05, //!< YAW fixed-point yaw in degrees * 100 ACCEL_X = 0x07, //!< ACCEL_X raw acceleration in x ACCEL_Y = 0x09, //!< ACCEL_Y raw acceleration in y ACCEL_Z = 0x0b, //!< ACCEL_Z raw acceleration in z GYRO_X = 0x0d, //!< GYRO_X raw angular velocity about x GYRO_Y = 0x0f, //!< GYRO_Y raw angular velocity about y GYRO_Z = 0x11, //!< GYRO_Z raw angular velocity about z }; I2C* m_i2c; DigitalOutput * m_dio; uint8_t m_i2c_buf[kNumPackets * 6 + 1]; int16_t getInt16(uint8_t index); uint8_t getUint8(uint8_t index); uint8_t m_expected_packet_num; int16_t m_accel_x, m_accel_y, m_accel_z, m_gyro_x, m_gyro_y, m_gyro_z; uint8_t m_status; double m_last_gyro_y, m_gyro_y_delta; double m_roll, m_pitch, m_yaw; int m_time; SEM_ID m_sem; Task *m_task; bool m_is_running; }; #endif
[ "brianaxelrod@1c69c455-704f-4920-a974-72747f0ffa95" ]
brianaxelrod@1c69c455-704f-4920-a974-72747f0ffa95
77f48b1c39dee3c3a4af6770dbbd3dea13a904b6
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
/opencascade/TopOpeBRepBuild_FaceBuilder.hxx
8b107bb993096d2cc918799b74a2837939b3fcf5
[ "Apache-2.0" ]
permissive
CadQuery/OCP
fbee9663df7ae2c948af66a650808079575112b5
b5cb181491c9900a40de86368006c73f169c0340
refs/heads/master
2023-07-10T18:35:44.225848
2023-06-12T18:09:07
2023-06-12T18:09:07
228,692,262
64
28
Apache-2.0
2023-09-11T12:40:09
2019-12-17T20:02:11
C++
UTF-8
C++
false
false
4,393
hxx
// Created on: 1995-12-21 // Created by: Jean Yves LEBEY // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRepBuild_FaceBuilder_HeaderFile #define _TopOpeBRepBuild_FaceBuilder_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <TopoDS_Face.hxx> #include <TopOpeBRepBuild_LoopSet.hxx> #include <TopOpeBRepBuild_BlockIterator.hxx> #include <TopOpeBRepBuild_BlockBuilder.hxx> #include <TopOpeBRepBuild_FaceAreaBuilder.hxx> #include <TopTools_DataMapOfShapeInteger.hxx> #include <TopTools_IndexedDataMapOfShapeShape.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <Standard_Integer.hxx> class TopOpeBRepBuild_WireEdgeSet; class TopoDS_Shape; class TopOpeBRepBuild_ShapeSet; class TopOpeBRepBuild_FaceBuilder { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRepBuild_FaceBuilder(); //! Create a FaceBuilder to build the faces on //! the shapes (wires, blocks of edge) described by <LS>. Standard_EXPORT TopOpeBRepBuild_FaceBuilder(TopOpeBRepBuild_WireEdgeSet& ES, const TopoDS_Shape& F, const Standard_Boolean ForceClass = Standard_False); Standard_EXPORT void InitFaceBuilder (TopOpeBRepBuild_WireEdgeSet& ES, const TopoDS_Shape& F, const Standard_Boolean ForceClass); //! Removes are non 3d-closed wires. //! Fills up maps <mapVVsameG> and <mapVon1Edge>, in order to //! correct 3d-closed but unclosed (topologic connexity) wires. //! modifies myBlockBuilder Standard_EXPORT void DetectUnclosedWire (TopTools_IndexedDataMapOfShapeShape& mapVVsameG, TopTools_IndexedDataMapOfShapeShape& mapVon1Edge); //! Using the given maps, change the topology of the 3d-closed //! wires, in order to get closed wires. Standard_EXPORT void CorrectGclosedWire (const TopTools_IndexedDataMapOfShapeShape& mapVVref, const TopTools_IndexedDataMapOfShapeShape& mapVon1Edge); //! Removes edges appearing twice (FORWARD,REVERSED) with a bounding //! vertex not connected to any other edge. //! mapE contains edges found. //! modifies myBlockBuilder. Standard_EXPORT void DetectPseudoInternalEdge (TopTools_IndexedMapOfShape& mapE); //! return myFace Standard_EXPORT const TopoDS_Shape& Face() const; Standard_EXPORT Standard_Integer InitFace(); Standard_EXPORT Standard_Boolean MoreFace() const; Standard_EXPORT void NextFace(); Standard_EXPORT Standard_Integer InitWire(); Standard_EXPORT Standard_Boolean MoreWire() const; Standard_EXPORT void NextWire(); Standard_EXPORT Standard_Boolean IsOldWire() const; //! Returns current wire //! This wire may be : //! * an old wire OldWire(), which has not been reconstructed; //! * a new wire made of edges described by ...NewEdge() methods. Standard_EXPORT const TopoDS_Shape& OldWire() const; //! Iterates on myBlockIterator until finding a valid element Standard_EXPORT void FindNextValidElement(); Standard_EXPORT Standard_Integer InitEdge(); Standard_EXPORT Standard_Boolean MoreEdge() const; Standard_EXPORT void NextEdge(); //! Returns current new edge of current new wire. Standard_EXPORT const TopoDS_Shape& Edge() const; Standard_EXPORT Standard_Integer EdgeConnexity (const TopoDS_Shape& E) const; Standard_EXPORT Standard_Integer AddEdgeWire (const TopoDS_Shape& E, TopoDS_Shape& W) const; protected: private: Standard_EXPORT void MakeLoops (TopOpeBRepBuild_ShapeSet& SS); TopoDS_Face myFace; TopOpeBRepBuild_LoopSet myLoopSet; TopOpeBRepBuild_BlockIterator myBlockIterator; TopOpeBRepBuild_BlockBuilder myBlockBuilder; TopOpeBRepBuild_FaceAreaBuilder myFaceAreaBuilder; TopTools_DataMapOfShapeInteger myMOSI; }; #endif // _TopOpeBRepBuild_FaceBuilder_HeaderFile
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
b7c808305cb6f5253b146635348dd8c5ade238ca
2d627fbba7bfb4a83cc7fd70c730e1ba5952e199
/hackerrank/counting valles.cpp
1b735d7a285e8f40a8f73101a9a64db21ce62795
[]
no_license
shivamsatyam/datastructure-and-algorithm
8f8660ef576b59113ede3deb7b4e6188af4f2bac
5b2a14f1e05f347ae2515dce59c60743fa901a3b
refs/heads/master
2023-02-10T00:13:23.019148
2021-01-14T14:55:13
2021-01-14T14:55:13
329,647,058
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include<iostream> #include<string> using namespace std; int main() { int n; cin>>n; string s; cin>>s; int sea = 0; int count=0; for(int i=0;i<n;i++){ if(s.at(i)=='U'){ ++sea; }else{ --sea; } if(sea==0){ ++count; } } cout<<count<<"\n"; return 0; }
[ "softgooddeveloper@gmail.com" ]
softgooddeveloper@gmail.com
6a8f832d0c61d8f5fcd71da32e912b20b1e21f1b
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chromeos/components/multidevice/logging/log_buffer.h
436744367e017655a02482d713549ae7d32d82da
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,443
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_COMPONENTS_MULTIDEVICE_LOGGING_LOG_BUFFER_H_ #define CHROMEOS_COMPONENTS_MULTIDEVICE_LOGGING_LOG_BUFFER_H_ #include <stddef.h> #include <list> #include "base/logging.h" #include "base/macros.h" #include "base/observer_list.h" #include "base/time/time.h" namespace chromeos { namespace multidevice { // Contains logs specific to the Proximity Auth. This buffer has a maximum size // and will discard entries in FIFO order. // Call LogBuffer::GetInstance() to get the global LogBuffer instance. class LogBuffer { public: // Represents a single log entry in the log buffer. struct LogMessage { const std::string text; const base::Time time; const std::string file; const int line; const logging::LogSeverity severity; LogMessage(const std::string& text, const base::Time& time, const std::string& file, int line, logging::LogSeverity severity); }; class Observer { public: // Called when a new message is added to the log buffer. virtual void OnLogMessageAdded(const LogMessage& log_message) = 0; // Called when all messages in the log buffer are cleared. virtual void OnLogBufferCleared() = 0; }; LogBuffer(); ~LogBuffer(); // Returns the global instance. static LogBuffer* GetInstance(); // Adds and removes log buffer observers. void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); // Adds a new log message to the buffer. If the number of log messages exceeds // the maximum, then the earliest added log will be removed. void AddLogMessage(const LogMessage& log_message); // Clears all logs in the buffer. void Clear(); // Returns the maximum number of logs that can be stored. size_t MaxBufferSize() const; // Returns the list logs in the buffer, sorted chronologically. const std::list<LogMessage>* logs() { return &log_messages_; } private: // The messages currently in the buffer. std::list<LogMessage> log_messages_; // List of observers. base::ObserverList<Observer>::Unchecked observers_; DISALLOW_COPY_AND_ASSIGN(LogBuffer); }; } // namespace multidevice } // namespace chromeos #endif // CHROMEOS_COMPONENTS_MULTIDEVICE_LOGGING_LOG_BUFFER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
9cf4edeeeaac011ed9116bdd59cc7318009e01c8
39868e1360447f5892d7feece2b82e0d6da47630
/thrill/net/dispatcher_thread.cpp
c1cfa519455f52fdf55e554bf40af70e92538c0b
[ "BSD-2-Clause" ]
permissive
Robert-Williger/thrill
a5c66d527b96039ee483e1898c835290c0bccbe8
79a3b8d7e5dff83ee87aa10e0a1c0f561178db72
refs/heads/master
2020-12-30T16:27:13.622790
2017-05-11T13:27:55
2017-05-11T13:27:55
90,977,337
0
0
null
2017-05-11T12:35:54
2017-05-11T12:35:54
null
UTF-8
C++
false
false
6,150
cpp
/******************************************************************************* * thrill/net/dispatcher_thread.cpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <thrill/net/dispatcher.hpp> #include <thrill/net/dispatcher_thread.hpp> #include <thrill/net/group.hpp> #include <deque> #include <string> #include <vector> namespace thrill { namespace net { DispatcherThread::DispatcherThread( mem::Manager& mem_manager, std::unique_ptr<class Dispatcher>&& dispatcher, const mem::by_string& thread_name) : mem_manager_(&mem_manager, "DispatcherThread"), dispatcher_(std::move(dispatcher)), name_(thread_name) { // start thread thread_ = std::thread(&DispatcherThread::Work, this); } DispatcherThread::DispatcherThread( mem::Manager& mem_manager, Group& group, const mem::by_string& thread_name) : DispatcherThread( mem_manager, group.ConstructDispatcher(mem_manager), thread_name) { } DispatcherThread::~DispatcherThread() { Terminate(); } //! Terminate the dispatcher thread (if now already done). void DispatcherThread::Terminate() { if (terminate_) return; // set termination flags. terminate_ = true; // interrupt select(). WakeUpThread(); // wait for last round to finish. thread_.join(); } //! Register a relative timeout callback void DispatcherThread::AddTimer( std::chrono::milliseconds timeout, TimerCallback cb) { Enqueue([=]() { dispatcher_->AddTimer(timeout, cb); }); WakeUpThread(); } //! Register a buffered read callback and a default exception callback. void DispatcherThread::AddRead(Connection& c, AsyncCallback read_cb) { Enqueue([=, &c]() { dispatcher_->AddRead(c, read_cb); }); WakeUpThread(); } //! Register a buffered write callback and a default exception callback. void DispatcherThread::AddWrite(Connection& c, AsyncCallback write_cb) { Enqueue([=, &c]() { dispatcher_->AddWrite(c, write_cb); }); WakeUpThread(); } //! Cancel all callbacks on a given connection. void DispatcherThread::Cancel(Connection& c) { Enqueue([=, &c]() { dispatcher_->Cancel(c); }); WakeUpThread(); } //! asynchronously read n bytes and deliver them to the callback void DispatcherThread::AsyncRead( Connection& c, size_t size, AsyncReadCallback done_cb) { Enqueue([=, &c]() { dispatcher_->AsyncRead(c, size, done_cb); }); WakeUpThread(); } //! asynchronously read the full ByteBlock and deliver it to the callback void DispatcherThread::AsyncRead( Connection& c, size_t size, data::PinnedByteBlockPtr&& block, AsyncReadByteBlockCallback done_cb) { assert(block.valid()); Enqueue([=, &c, b = std::move(block)]() mutable { dispatcher_->AsyncRead(c, size, std::move(b), done_cb); }); WakeUpThread(); } //! asynchronously write TWO buffers and callback when delivered. The //! buffer2 are MOVED into the async writer. This is most useful to write a //! header and a payload Buffers that are hereby guaranteed to be written in //! order. void DispatcherThread::AsyncWrite( Connection& c, Buffer&& buffer, AsyncWriteCallback done_cb) { // the following captures the move-only buffer in a lambda. Enqueue([=, &c, b = std::move(buffer)]() mutable { dispatcher_->AsyncWrite(c, std::move(b), done_cb); }); WakeUpThread(); } //! asynchronously write buffer and callback when delivered. The buffer is //! MOVED into the async writer. void DispatcherThread::AsyncWrite( Connection& c, Buffer&& buffer, data::PinnedBlock&& block, AsyncWriteCallback done_cb) { assert(block.IsValid()); // the following captures the move-only buffer in a lambda. Enqueue([=, &c, b1 = std::move(buffer), b2 = std::move(block)]() mutable { dispatcher_->AsyncWrite(c, std::move(b1)); dispatcher_->AsyncWrite(c, std::move(b2), done_cb); }); WakeUpThread(); } //! asynchronously write buffer and callback when delivered. COPIES the data //! into a Buffer! void DispatcherThread::AsyncWriteCopy( Connection& c, const void* buffer, size_t size, AsyncWriteCallback done_cb) { return AsyncWrite(c, Buffer(buffer, size), done_cb); } //! asynchronously write buffer and callback when delivered. COPIES the data //! into a Buffer! void DispatcherThread::AsyncWriteCopy(Connection& c, const std::string& str, AsyncWriteCallback done_cb) { return AsyncWriteCopy(c, str.data(), str.size(), done_cb); } //! Enqueue job in queue for dispatching thread to run at its discretion. void DispatcherThread::Enqueue(Job&& job) { return jobqueue_.push(std::move(job)); } //! What happens in the dispatcher thread void DispatcherThread::Work() { common::NameThisThread(name_); // pin DispatcherThread to last core common::SetCpuAffinity(std::thread::hardware_concurrency() - 1); while (!terminate_ || dispatcher_->HasAsyncWrites() || !jobqueue_.empty()) { // process jobs in jobqueue_ { Job job; while (jobqueue_.try_pop(job)) job(); } // set busy flag, but check once again for jobs. busy_ = true; { Job job; if (jobqueue_.try_pop(job)) { busy_ = false; job(); continue; } } // run one dispatch dispatcher_->Dispatch(); busy_ = false; } } //! wake up select() in dispatching thread. void DispatcherThread::WakeUpThread() { if (busy_) dispatcher_->Interrupt(); } } // namespace net } // namespace thrill /******************************************************************************/
[ "tbgit@panthema.net" ]
tbgit@panthema.net
a81abad1f8b23f3ca4e7d6c5ffc7a3e15ec810dd
5e38928648065977b10c3b479948a22f1d62e398
/Source/CSS/CSS/SDK/Main/BaseEntity/BaseEntity.cpp
20545284645e7dac4e7e6065ee5a03f6f2eeb107
[]
no_license
KaylinOwO/moonshot
4054903c28fdba4250bea1d586fa370a0526d5da
66ade11c7854cbd65f63a56d71abe23d59a2db54
refs/heads/main
2023-06-25T07:01:55.961667
2021-07-31T01:21:05
2021-07-31T01:21:05
391,210,766
5
2
null
null
null
null
UTF-8
C++
false
false
14,490
cpp
#include "BaseEntity.h" #include "../../SDK.h" float C_BaseEntity::GetStepSize() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "localdata", "m_flStepSize"); } float C_BaseEntity::GetConveyorSpeed() { DYNVAR_RETURN(float, this, "DT_FuncConveyor", "m_flConveyorSpeed"); } bool C_BaseEntity::IsPlayer() { return GetClientClass()->iClassID == (int)EClientClass::CCSPlayer; } C_BaseEntity* C_BaseEntity::GetGroundEntity() { DYNVAR(pHandle, int, "DT_BasePlayer", "m_hGroundEntity"); return reinterpret_cast<C_BaseEntity*>(gInts.EntityList->GetClientEntityFromHandle(pHandle.GetValue(this))); } std::array<float, MAXSTUDIOPOSEPARAM> C_BaseEntity::GetPoseParam() { static DWORD dwOffset = gNetVars.get_offset("DT_BaseAnimating", "m_flPoseParameter"); return *reinterpret_cast<std::array<float, MAXSTUDIOPOSEPARAM>*>(this + dwOffset); } bool C_BaseEntity::GetHitboxMinsAndMaxsAndMatrix(int nHitbox, Vec3& mins, Vec3& maxs, matrix3x4& matrix, Vec3* center) { model_t* pModel = GetModel(); if (!pModel) return false; studiohdr_t* pHdr = (studiohdr_t*)gInts.ModelInfo->GetStudioModel(pModel); if (!pHdr) return false; matrix3x4 BoneMatrix[128]; if (!this->SetupBones(BoneMatrix, 128, 0x100, gInts.GlobalVars->curtime)) return false; mstudiohitboxset_t* pSet = pHdr->pHitboxSet(this->GetHitboxSet()); if (!pSet) return false; mstudiobbox_t* pBox = pSet->hitbox(nHitbox); if (!pBox) return false; mins = pBox->bbmin; maxs = pBox->bbmax; memcpy(matrix, BoneMatrix[pBox->bone], sizeof(matrix3x4)); if (center) Math::VectorTransform(((pBox->bbmin + pBox->bbmax) * 0.5f), BoneMatrix[pBox->bone], *center); return true; } bool C_BaseEntity::GetHitboxMinsAndMaxs(int nHitbox, Vec3& mins, Vec3& maxs, Vec3* center) { model_t* pModel = GetModel(); if (!pModel) return false; studiohdr_t* pHdr = (studiohdr_t*)gInts.ModelInfo->GetStudioModel(pModel); if (!pHdr) return false; matrix3x4 BoneMatrix[128]; if (!this->SetupBones(BoneMatrix, 128, 0x100, gInts.GlobalVars->curtime)) return false; mstudiohitboxset_t* pSet = pHdr->pHitboxSet(this->GetHitboxSet()); if (!pSet) return false; mstudiobbox_t* pBox = pSet->hitbox(nHitbox); if (!pBox) return false; mins = pBox->bbmin; maxs = pBox->bbmax; if (center) Math::VectorTransform(((pBox->bbmin + pBox->bbmax) * 0.5f), BoneMatrix[pBox->bone], *center); return true; } MoveType_t C_BaseEntity::GetMoveType() { DYNVAR_RETURN(MoveType_t, this, "DT_BaseEntity", "movetype"); } float C_BaseEntity::GetSurfaceFriction() { return *reinterpret_cast<float*>(this + 0x12D4); } float C_BaseEntity::GetMaxSpeed() { DYNVAR_RETURN(float, this, "DT_BasePlayer", "m_flMaxspeed"); } float C_BaseEntity::GetWaterJumpTime() { return *reinterpret_cast<float*>(this + 0x10FC); //reference /* float m_flMaxspeed; int m_iBonusProgress; int m_iBonusChallenge; CInterpolatedVar< Vector > m_iv_vecViewOffset; Vector m_vecWaterJumpVel; float m_flWaterJumpTime; */ } void C_BaseEntity::SetTickBase(int tickbase) { DYNVAR_SET(int, this, tickbase, "DT_BasePlayer", "localdata", "m_nTickBase"); } bool C_BaseEntity::IsInValidTeam() { int Team = this->GetTeamNum(); return (Team == 2 || Team == 3); } C_BaseEntity* C_BaseEntity::FirstMoveChild() { return gInts.EntityList->GetClientEntity(*reinterpret_cast<int*>(this + 0x1B0) & 0xFFF); } C_BaseEntity* C_BaseEntity::NextMovePeer() { return gInts.EntityList->GetClientEntity(*reinterpret_cast<int*>(this + 0x1B4) & 0xFFF); } void C_BaseEntity::UpTickBase() { static CDynamicNetvar<int> n("DT_BasePlayer", "localdata", "m_nTickBase"); n.SetValue(this, n.GetValue(this) + 1); } void C_BaseEntity::UpdateClientSideAnimation() { void* renderable = (PVOID)(this + 0x4); typedef void(__thiscall* FN)(PVOID); return GetVFunc<FN>(renderable, 3)(renderable); } const Vec3& C_BaseEntity::GetRenderAngles() { void* renderable = (PVOID)(this + 0x4); typedef const Vec3& (__thiscall* FN)(PVOID); return GetVFunc<FN>(renderable, 2)(renderable); } void C_BaseEntity::SetRenderAngles(const Vec3& v) { Vec3* pRenderAngles = const_cast<Vec3*>(&this->GetRenderAngles()); *pRenderAngles = v; } void C_BaseEntity::SetAbsOrigin(const Vec3& v) { typedef void(__thiscall* FN)(C_BaseEntity*, const Vec3&); static DWORD dwFN = gPattern.Find("client.dll", "55 8B EC 56 57 8B F1 E8 ? ? ? ? 8B 7D 08 F3 0F 10 07"); FN func = (FN)dwFN; func(this, v); } void C_BaseEntity::SetAbsAngles(const Vec3& v) { /*typedef void(__thiscall *FN)(C_BaseEntity *, const Vec3 &); static DWORD dwFN = gPattern.FindInClient("55 8B EC 83 EC 60 56 57 8B F1 E8 ? ? ? ? 8B 7D 08 F3 0F 10 07 0F 2E 86 ? ? ? ? 9F F6 C4 44 7A 28 F3 0F 10 47 ?"); FN func = (FN)dwFN; func(this, v);*/ Vec3* pAbsAngles = const_cast<Vec3*>(&this->GetAbsAngles()); *pAbsAngles = v; } const Vec3& C_BaseEntity::GetAbsOrigin() { typedef Vec3& (__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 9)(this); } //Recreated from "C_TFPlayer" //Supposed to be used from local. bool C_BaseEntity::IsPlayerOnSteamFriendList(C_BaseEntity* pEntity) { /*PlayerInfo_t pi; if (gInts.Engine->GetPlayerInfo(pEntity->GetIndex(), &pi) && pi.friendsID) { CSteamID steamID{ pi.friendsID, 1, k_EUniversePublic, k_EAccountTypeIndividual }; if (gSteam.Friends002->HasFriend(steamID, k_EFriendFlagImmediate)) return true; }*/ return false; } const Vec3& C_BaseEntity::GetAbsAngles() { typedef Vec3& (__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 10)(this); } Vec3 C_BaseEntity::GetEyeAngles() { DYNVAR_RETURN(Vec3, this, "DT_TFPlayer", "tfnonlocaldata", "m_angEyeAngles[0]"); } Vec3 C_BaseEntity::GetViewOffset() { DYNVAR_RETURN(Vec3, this, "DT_BasePlayer", "localdata", "m_vecViewOffset[0]"); } Vec3 C_BaseEntity::GetEyePosition() { DYNVAR_RETURN(Vec3, this, "DT_BasePlayer", "localdata", "m_vecViewOffset[0]") + GetAbsOrigin(); } C_UserCmd* C_BaseEntity::GetCurrentCommand() { DYNVAR_RETURN(C_UserCmd*, (this - 0x4), "DT_BasePlayer", "localdata", "m_hConstraintEntity"); } int C_BaseEntity::GetChockedTicks() { float flDiff = gInts.GlobalVars->curtime - flSimulationTime(); float flLatency = 0.0f; if (auto pNet = gInts.Engine->GetNetChannelInfo()) flLatency = pNet->GetAvgLatency(FLOW_INCOMING); return TIME_TO_TICKS(std::max(0.0f, flDiff - flLatency)); } void C_BaseEntity::SetCurrentCmd(C_UserCmd* cmd) { DYNVAR_SET(C_UserCmd*, (this - 0x4), cmd, "DT_BasePlayer", "localdata", "m_hConstraintEntity"); } Vec3 C_BaseEntity::GetPunchAngles() { return *reinterpret_cast<Vec3*>(this + 0xE48); } Vec3 C_BaseEntity::GetVecOrigin() { DYNVAR_RETURN(Vec3, this, "DT_BaseEntity", "m_vecOrigin"); } void C_BaseEntity::SetVecOrigin(Vec3& vOrigin) { DYNVAR_SET(Vec3, this, vOrigin, "DT_BaseEntity", "m_vecOrigin"); } bool C_BaseEntity::GetTouched() { return *reinterpret_cast<bool*>(this + 0x8F8); } int C_BaseEntity::GetType() { return *reinterpret_cast<int*>(this + 0x8FC); } const char* C_BaseEntity::GetModelName() { return gInts.ModelInfo->GetModelName(this->GetModel()); } int C_BaseEntity::GetAmmo() { DYNVAR_RETURN(int, (this + 4), "DT_BasePlayer", "localdata", "m_iAmmo"); } bool C_BaseEntity::IsBaseCombatWeapon() { typedef bool(__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 137)(this); } bool C_BaseEntity::IsWearable() { typedef bool(__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 138)(this); } int C_BaseEntity::GetHitboxSet() { DYNVAR_RETURN(int, this, "DT_BaseAnimating", "m_nHitboxSet"); } int C_BaseEntity::GetTickBase() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "localdata", "m_nTickBase"); } void C_BaseEntity::IncreaseTickBase() { static CDynamicNetvar<int>n("DT_BasePlayer", "localdata", "m_nTickBase"); n.SetValue(this, n.GetValue(this) + 1); } float C_BaseEntity::flSimulationTime() { DYNVAR_RETURN(float, this, "DT_BaseEntity", "m_flSimulationTime"); } int C_BaseEntity::GetOwner() { DYNVAR_RETURN(int, this, "DT_BaseEntity", "m_hOwnerEntity"); } Vec3 C_BaseEntity::GetWorldSpaceCenter() { Vec3 vMin, vMax; this->GetRenderBounds(vMin, vMax); Vec3 vWorldSpaceCenter = this->GetAbsOrigin(); vWorldSpaceCenter.z += (vMin.z + vMax.z) / 2.0f; return vWorldSpaceCenter; } model_t* C_BaseEntity::GetModel() { PVOID pRenderable = (PVOID)(this + 0x4); typedef model_t* (__thiscall* FN)(PVOID); return GetVFunc<FN>(pRenderable, 9)(pRenderable); } int C_BaseEntity::DrawModel(int flags) { void* renderable = (PVOID)(this + 0x4); typedef int(__thiscall* FN)(PVOID, int); return GetVFunc<FN>(renderable, 10)(renderable, flags); } bool C_BaseEntity::SetupBones(matrix3x4* pBoneToWorldOut, int nMaxBones, int nBoneMask, float fCurrentTime) { PVOID pRenderable = (PVOID)(this + 0x4); typedef bool(__thiscall* FN)(PVOID, matrix3x4*, int, int, float); return GetVFunc<FN>(pRenderable, 16)(pRenderable, pBoneToWorldOut, nMaxBones, nBoneMask, fCurrentTime); } C_ClientClass* C_BaseEntity::GetClientClass() { PVOID pNetworkable = (PVOID)(this + 0x8); typedef C_ClientClass* (__thiscall* FN)(PVOID); return GetVFunc<FN>(pNetworkable, 2)(pNetworkable); } bool C_BaseEntity::IsDormant() { PVOID pNetworkable = (PVOID)(this + 0x8); typedef bool(__thiscall* FN)(PVOID); return GetVFunc<FN>(pNetworkable, 8)(pNetworkable); } int C_BaseEntity::GetIndex() { PVOID pNetworkable = (PVOID)(this + 0x8); typedef int(__thiscall* FN)(PVOID); return GetVFunc<FN>(pNetworkable, 9)(pNetworkable); } void C_BaseEntity::GetRenderBounds(Vec3& vMins, Vec3& vMaxs) { PVOID pRenderable = (PVOID)(this + 0x4); typedef void(__thiscall* FN)(PVOID, Vec3&, Vec3&); GetVFunc<FN>(pRenderable, 20)(pRenderable, vMins, vMaxs); } matrix3x4& C_BaseEntity::GetRgflCoordinateFrame() { PVOID pRenderable = (PVOID)(this + 0x4); typedef matrix3x4& (__thiscall* FN)(PVOID); return GetVFunc<FN>(pRenderable, 34)(pRenderable); } Vec3 C_BaseEntity::GetVelocity() { typedef void(__thiscall* EstimateAbsVelocityFn)(C_BaseEntity*, Vec3&); static DWORD dwFn = gPattern.Find("client.dll", "E8 ? ? ? ? F3 0F 10 4D ? 8D 85 ? ? ? ? F3 0F 10 45 ? F3 0F 59 C9 56 F3 0F 59 C0 F3 0F 58 C8 0F 2F 0D ? ? ? ? 76 07") + 0x1; static DWORD dwEstimate = ((*(PDWORD)(dwFn)) + dwFn + 0x4); EstimateAbsVelocityFn vel = (EstimateAbsVelocityFn)dwEstimate; Vec3 v; vel(this, v); return v; } int C_BaseEntity::GetMaxHealth() { typedef int(__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 107)(this); } int C_BaseEntity::GetHealth() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "m_iHealth"); } int C_BaseEntity::GetTeamNum() { DYNVAR_RETURN(int, this, "DT_BaseEntity", "m_iTeamNum"); } int C_BaseEntity::GetFlags() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "m_fFlags"); } void C_BaseEntity::SetFlags(int nFlags) { DYNVAR_SET(int, this, nFlags, "DT_BasePlayer", "m_fFlags"); } BYTE C_BaseEntity::GetLifeState() { DYNVAR_RETURN(BYTE, this, "DT_BasePlayer", "m_lifeState"); } int C_BaseEntity::GetClassId() { return this->GetClientClass()->iClassID; } int C_BaseEntity::GetTFClass() { DYNVAR_RETURN(int, this, "DT_TFPlayer", "m_PlayerClass", "m_iClass"); } Vec3 C_BaseEntity::GetCollideableMins() { DYNVAR_RETURN(Vec3, this, "DT_BaseEntity", "m_Collision", "m_vecMins"); } Vec3 C_BaseEntity::GetCollideableMaxs() { DYNVAR_RETURN(Vec3, this, "DT_BaseEntity", "m_Collision", "m_vecMaxs"); } bool C_BaseEntity::IsOnGround() { return (this->GetFlags() & FL_ONGROUND); } bool C_BaseEntity::IsInWater() { return (this->GetFlags() & FL_INWATER); //it's better to use IsSwimming method cuz this one doesn't work iirc. } Vec3 C_BaseEntity::GetHitboxPos(int nHitbox) { model_t* pModel = GetModel(); if (!pModel) return Vec3(); studiohdr_t* pHdr = (studiohdr_t*)gInts.ModelInfo->GetStudioModel(pModel); if (!pHdr) return Vec3(); mstudiohitboxset_t* pSet = pHdr->pHitboxSet(this->GetHitboxSet()); if (!pSet) return Vec3(); mstudiobbox_t* pBox = pSet->hitbox(nHitbox); if (!pBox) return Vec3(); Vec3 vPos = (pBox->bbmin + pBox->bbmax) * 0.5f; Vec3 vOut = Vec3(); matrix3x4 BoneMatrix[128]; if (!this->SetupBones(BoneMatrix, 128, 0x100, gInts.GlobalVars->curtime)) return Vec3(); Math::VectorTransform(vPos, BoneMatrix[pBox->bone], vOut); // Math::VectorTransform(vPos, BoneMatrix[pBox->bone], vOut); return vOut; } int C_BaseEntity::GetNumOfHitboxes() { model_t* pModel = GetModel(); if (!pModel) return 0; studiohdr_t* pHdr = (studiohdr_t*)gInts.ModelInfo->GetStudioModel(pModel); if (!pHdr) return 0; mstudiohitboxset_t* pSet = pHdr->pHitboxSet(this->GetHitboxSet()); if (!pSet) return 0; return pSet->numhitboxes; } Vec3 C_BaseEntity::GetBonePos(int nBone) { matrix3x4 matrix[128]; if (this->SetupBones(matrix, 128, 0x100, GetTickCount64())) return Vec3(matrix[nBone][0][3], matrix[nBone][1][3], matrix[nBone][2][3]); return Vec3(0.0f, 0.0f, 0.0f); } C_BaseCombatWeapon* C_BaseEntity::GetActiveWeapon() { DYNVAR(pHandle, int, "DT_BaseCombatCharacter", "m_hActiveWeapon"); return reinterpret_cast<C_BaseCombatWeapon*>(gInts.EntityList->GetClientEntityFromHandle(pHandle.GetValue(this))); } float C_BaseEntity::GetNextAttack() { DYNVAR_RETURN(float, this, "DT_BaseCombatCharacter", "bcc_localdata", "m_flNextAttack"); } bool C_BaseEntity::IsAlive() { return (this->GetLifeState() == LIFE_ALIVE); } int C_BaseEntity::GetFov() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "m_iFOV"); } void C_BaseEntity::SetFov(int nFov) { DYNVAR_SET(int, this, nFov, "DT_BasePlayer", "m_iFOV"); } bool C_BaseEntity::IsDucking() { return (this->GetFlags() & FL_DUCKING); } int C_BaseEntity::GetObserverTarget() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "m_hObserverTarget"); } int C_BaseEntity::GetObserverMode() { DYNVAR_RETURN(int, this, "DT_BasePlayer", "m_iObserverMode"); } void C_BaseEntity::RemoveEffect(byte Effect) { *reinterpret_cast<byte*>(this + 0x7C) &= ~Effect; if (Effect == EF_NODRAW) { static auto AddToLeafSystemFn = reinterpret_cast<int(__thiscall*)(PVOID, int)>(gPattern.Find("client.dll", "55 8B EC 56 FF 75 08 8B F1 B8")); if (AddToLeafSystemFn) AddToLeafSystemFn(this, RENDER_GROUP_OPAQUE_ENTITY); } } void C_BaseEntity::UpdateGlowEffect() { typedef void(__thiscall* FN)(PVOID); return GetVFunc<FN>(this, 226)(this); } void* C_BaseEntity::GetThrower() { DYNVAR_RETURN(C_BaseEntity*, this, "DT_BaseGrenade", "m_hThrower"); } float C_BaseEntity::GetDamageRadius() { DYNVAR_RETURN(float, this, "DT_BaseGrenade", "m_DmgRadius"); } float C_BaseEntity::GetSimulationTime() { DYNVAR_RETURN(float, this, "DT_BaseEntity", "m_flSimulationTime"); }
[ "calliexen@gmail.com" ]
calliexen@gmail.com
dd07434596fda14519e0d559a513adf871d9949a
bd40e16292a88a109391ee14ae08acb488c9adf3
/FinalProject_GCC_Version/BondStreamingService.hpp
b5f214ab3091a7f7900fa584b9634040013f2291
[]
no_license
gansuranga/MTH9815-Software-Engineering
4d843f85ee8cc4d22894bf507ca8adfc4cc1ad4c
176b10ede5d048a48cb2353ce5b5c06a305b0998
refs/heads/master
2020-03-28T14:08:33.482500
2017-01-10T21:24:35
2017-01-10T21:24:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
hpp
#pragma once /** * BondStreamingService.hpp * Define BondStreamingService class * @Create by Xinlu Xiao */ #ifndef BONDSTREAMINGSERVICE_HPP #define BONDSTREAMINGSERVICE_HPP #include <iostream> #include <fstream> #include "products.hpp" #include "soa.hpp" #include "streamingservice.hpp" #include "BondHistoricalDataService.hpp" using namespace std; class BondStreamingService : public Service<string, PriceStream<Bond>> { public: // override the virtual function //virtual PriceStream<Bond>& GetData(string key) override {}; // override the virtual function virtual void OnMessage(PriceStream<Bond> &data) override {}; // Initialize a BondHistoricalDataService object pointer and use connector to publish a price void PublishPrice(PriceStream<Bond> &priceStream) { BondHistoricalDataService::Add_example()-> Persist_Streaming(priceStream); } // Initialize the BondStreamingService object as a pointer static BondStreamingService* Add_example() { static BondStreamingService example; return &example; } private: // ctor BondStreamingService() {}; }; #endif
[ "xinluxiao.baruch@gmail.com" ]
xinluxiao.baruch@gmail.com
f090a095529f3a326b32e7c1d51ca2099b992f31
e3e74c3167e26dbcf80f8ddf72ebaa5b86a90ec3
/lab_5/code/Portero.h
d1f7393a91d79462ce3c0ea8d1d393bbb8fb73eb
[]
no_license
CursosIE/IE-0217-II-16-G5
af6c22755d190f070f8e5b2f926cb556dd44113a
062e485f3048d8d240408351b8f146e5cef7904b
refs/heads/master
2020-06-19T08:36:58.646356
2017-09-25T04:06:35
2017-09-25T04:06:35
68,147,776
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
#ifndef PORTERO_H #define PORTERO_H #include "LCP.h" class Portero { public: //Atributos int cE; int cT; double cD; int ciclos; /// Sala de espera de ejecutivos: COLA LCP<char>* sala_E; /// Sala de espera de trabajadores: COLA LCP<char>* sala_T; /// Sala de espera de desempleados: COLA LCP<char>* sala_D; Portero(); ~Portero(); void ubicar(char** clientes); char llamar_jugador(); }; #endif /* PORTERO_H */
[ "s4sibarahona@gmail.com" ]
s4sibarahona@gmail.com
03a557897c2e5f94f7ab7ae7229ec77daf858157
0ec756cae161ecead71b4bb1cd6cce61b739e566
/src/color/hwb/set/blue.hpp
0d897c930ac13066a4dd503acbc7b068c20f6ef9
[ "Apache-2.0" ]
permissive
tesch1/color
f6ac20abd3935bb323c5a302289b8a499fa36101
659874e8efcfca88ffa897e55110fd344207175e
refs/heads/master
2021-07-21T22:08:08.032630
2017-09-06T11:55:55
2017-09-06T11:55:55
108,835,892
0
1
null
2017-10-30T10:32:12
2017-10-30T10:32:12
null
UTF-8
C++
false
false
1,086
hpp
#ifndef color_hwb_set_blue #define color_hwb_set_blue // ::color::set::blue( c ) #include "../../rgb/akin/hwb.hpp" #include "../../rgb/trait/component.hpp" #include "../category.hpp" namespace color { namespace set { template< typename tag_name > inline void blue ( ::color::model< ::color::category::hwb< tag_name > > & color_parameter ,typename ::color::trait::component< typename ::color::akin::rgb< ::color::category::hwb< tag_name > >::akin_type >::input_const_type component_parameter ) { typedef ::color::category::hwb< tag_name > category_type; typedef typename ::color::akin::rgb< category_type >::akin_type akin_type; enum { blue_p = ::color::place::_internal::blue<akin_type>::position_enum }; ::color::model< akin_type > rgb( color_parameter ); rgb.template set<blue_p > ( component_parameter ); color_parameter = rgb; } } } #endif
[ "dmilos@gmail.com" ]
dmilos@gmail.com
46a219efe9f78a0729513cd3c674458d4c46ba6f
94bda99d30fd6c417081780dd73af71a12d142df
/Engine/Component.h
0f881d14f20c3fbad727d85207846e967901b621
[]
no_license
Reticulatas/MochaEngineFinal
e5c972166cc64e6885a630f35ac81b3838393ce7
18ddc1574eb212e668be022327701f030a14b9f2
refs/heads/master
2016-09-14T07:15:42.224826
2016-05-21T00:06:36
2016-05-21T00:06:36
59,332,791
8
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,314
h
/*----------------------------------------------------------------- ----- © 2012 DigiPen Corporation (USA), All Rights Reserved ----- ----------------------------------------------------------------- -* Original Author: Nicholas Fuller -* See Footer for Revisions */ #pragma once #include "IRegisterable.h" #include "Collision.h" #include "meta.h" struct BaseState; class CCamera; //helper to make the clone method for every component #define COMPONENTCLONE(CompName)\ virtual ::Component* Clone(GameObject* newgobj) const {\ CompName* c = new CompName();\ c->gameObject = newgobj;\ c->OnInit();\ c->CopyFrom(this);\ return reinterpret_cast<Component*>(c); } class GameObject; class Component : public IRegisterable { public: virtual ~Component(void) { }; Component(void) : enabled(true), managedComponent(true) { }; virtual void OnStart(void) { assert(gameObject != 0); }; virtual void OnInit(void) = 0; virtual void OnUpdate(void) = 0; virtual void OnAlwaysUpdate(void); virtual void OnFree(void) = 0; virtual void OnDraw(void) { } virtual void OnMouseClick(CCamera* cam) { } virtual void OnMouseEnter(CCamera* cam) { } virtual void OnEditorUpdate(void) { } virtual void OnEditorStart(void) {} virtual void OnEditorFree(void) {} /* call to check whether another component has been added to our parent game object * if it does not exist, the component will be added * should only be used in ONSTART */ template <typename T> T* RequireDependency(void) { LogLock(); T* c = gameObject->GetComponent<T>(); LogUnlock(); if (!c) c = gameObject->AddComponent<T>(); return c; } /*! \brief If false, this component will never receive update calls. If it's a CScript, no OnUpdate()'s will be called */ bool isEnabled(); void setEnabled(bool v); bool globalEnabled(void); bool GetManagedComponent(); /*! \brief The game object this component is attached to */ GameObject* gameObject; BaseState* GetState(); std::string myType; virtual void CopyFrom(const ::Component* c) { enabled = c->enabled; myType = c->myType; //gameObject must be pre-linked //assert(gameObject != 0); } //check the top of this file for the helper macro that must be in every component ::Component* CloneTo(GameObject* newGObj) const { return Clone(newGObj); } void Destroy(); private: virtual ::Component* Clone(GameObject* newgobj) const = 0; bool enabled; protected: bool managedComponent; //is this component capable of being indexed? (turned off for cscripts, mostly) ___SERIALIZE_SAVE_BEGIN___ ___DEFBASE(IRegisterable) ___DEFSER(enabled, 1) ___DEFSER(gameObject, 1) ___DEFSER(myType, 3) //do not ser myState ___SERIALIZE_END___ ___SERIALIZE_LOAD_BEGIN___ ___DEFBASE(IRegisterable) ___DEFSER(enabled, 1) ___DEFSER(gameObject, 1) ___DEFSER(myType, 3) OnInit(); //do not ser myState ___SERIALIZE_END___ ___SERIALIZE_SAVE_LOAD___ public: metabasedef(Component) m_add(std::string, myType) m_add(bool, enabled) m_addfunc(Destroy) endmetabasedef; }; ___SERIALIZE_CLASS(Component, 3); //BOOST_SERIALIZATION_ASSUME_ABSTRACT(Component); void Destroy(::Component * c); ///////////////////////////////////// //Original Author: Nicholas Fuller //Modifications: // Date - Change
[ "nfuller@strangeloopgames.com" ]
nfuller@strangeloopgames.com
1da8dd4c4e97aea5eaaac561562c8e9d0cdee1d7
7056e994a800fe06b75eeecadb85ec79139b20c1
/src/remote_control.cpp
3989dc242e444b7c7d97cedbbeb6d6736a880226
[]
no_license
hjjayakrishnan/rviz_visual_tools
e43e5862d4829c2d36a37f68c5d4c578e10a3120
8332d51752cdce87da5d8b5aa2e36b2c48df70b0
refs/heads/kinetic-devel
2021-01-01T04:27:49.248349
2017-07-06T23:33:53
2017-07-06T23:33:53
97,178,564
0
0
null
2017-07-14T01:12:21
2017-07-14T01:12:21
null
UTF-8
C++
false
false
5,334
cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2016, PickNik LLC * 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 PickNik LLC 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. *********************************************************************/ /* Author: Dave Coleman <dave@dav.ee> Desc: Contains all hooks for debug interface */ // C++ #include <string> #include <rviz_visual_tools/remote_control.h> #define CONSOLE_COLOR_RESET "\033[0m" #define CONSOLE_COLOR_CYAN "\033[96m" #define CONSOLE_COLOR_BROWN "\033[93m" namespace rviz_visual_tools { /** * \brief Constructor */ RemoteControl::RemoteControl(ros::NodeHandle nh) : nh_(nh) { std::string rviz_dashboard_topic = "/rviz_visual_tools_gui"; // Subscribe to Rviz Dashboard const std::size_t button_queue_size = 10; rviz_dashboard_sub_ = nh_.subscribe<sensor_msgs::Joy>(rviz_dashboard_topic, button_queue_size, &RemoteControl::rvizDashboardCallback, this); ROS_INFO_STREAM_NAMED(name_, "RemoteControl Ready."); } void RemoteControl::rvizDashboardCallback(const sensor_msgs::Joy::ConstPtr& msg) { if (msg->buttons[1]) setReadyForNextStep(); else if (msg->buttons[2]) setAutonomous(); else if (msg->buttons[3]) setFullAutonomous(); else if (msg->buttons[4]) setStop(); else ROS_ERROR_STREAM_NAMED(name_, "Unknown input button"); } bool RemoteControl::setReadyForNextStep() { stop_ = false; if (is_waiting_) { next_step_ready_ = true; } return true; } void RemoteControl::setAutonomous(bool autonomous) { autonomous_ = autonomous; stop_ = false; } void RemoteControl::setFullAutonomous(bool autonomous) { full_autonomous_ = autonomous; autonomous_ = autonomous; stop_ = false; } void RemoteControl::setStop(bool stop) { stop_ = stop; if (stop) { autonomous_ = false; full_autonomous_ = false; } } bool RemoteControl::getStop() { return stop_; } bool RemoteControl::getAutonomous() { return autonomous_; } bool RemoteControl::getFullAutonomous() { return full_autonomous_; } bool RemoteControl::waitForNextStep(const std::string& caption) { // Check if we really need to wait if (!(!next_step_ready_ && !autonomous_ && ros::ok())) return true; // Show message std::cout << std::endl; std::cout << CONSOLE_COLOR_CYAN << "Waiting to continue: " << caption << CONSOLE_COLOR_RESET << std::flush; if (displayWaitingState_) displayWaitingState_(true); is_waiting_ = true; // Wait until next step is ready while (!next_step_ready_ && !autonomous_ && ros::ok()) { ros::Duration(0.25).sleep(); ros::spinOnce(); } if (!ros::ok()) exit(0); next_step_ready_ = false; is_waiting_ = false; std::cout << CONSOLE_COLOR_CYAN << "... continuing" << CONSOLE_COLOR_RESET << std::endl; if (displayWaitingState_) displayWaitingState_(false); return true; } bool RemoteControl::waitForNextFullStep(const std::string& caption) { // Check if we really need to wait if (!(!next_step_ready_ && !full_autonomous_ && ros::ok())) return true; // Show message std::cout << std::endl; std::cout << CONSOLE_COLOR_CYAN << "Waiting to continue: " << caption << CONSOLE_COLOR_RESET << std::flush; if (displayWaitingState_) displayWaitingState_(true); is_waiting_ = true; // Wait until next step is ready while (!next_step_ready_ && !full_autonomous_ && ros::ok()) { ros::Duration(0.25).sleep(); ros::spinOnce(); } if (!ros::ok()) exit(0); next_step_ready_ = false; is_waiting_ = false; std::cout << CONSOLE_COLOR_CYAN << "... continuing" << CONSOLE_COLOR_RESET << std::endl; if (displayWaitingState_) displayWaitingState_(false); return true; } } // namespace rviz_visual_tools
[ "davetcoleman@gmail.com" ]
davetcoleman@gmail.com
dc2eb98bac9987bb2c9fa72a738fa1e5b59f833c
68393cc174986df5ce765f971bb46a764184990f
/codeforces/contest_1141/C.cpp
5e1429c30aa15dfc2f0f556dd4406645564a78f2
[]
no_license
zhangji0629/algorithm
151e9a0bc8978863da4d6de5aa282c3593c02386
530026b4329adbab8eb2002ee547951f5d6b8418
refs/heads/master
2021-05-10T16:38:30.036308
2020-05-24T11:41:50
2020-05-24T11:41:50
118,584,175
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
#include<bits/stdc++.h> using LL = long long; LL num[300300],pre[300300]; int main() { int n; while(std::cin >> n) { memset(pre, 0, sizeof(pre)); LL minn = 0, minx = 1; for(int i = 2; i <= n; i++) { std::cin >> num[i]; pre[i] = pre[i-1] + num[i]; if(minn > pre[i]) { minn = pre[i]; minx = i; } } int xx = 1 - minn; std::map<LL, int> mp; bool ok = true; for(int i = 1; i <= n; i++) { pre[i] += xx; if(mp.find(pre[i]) != mp.end() || pre[i] > n || pre[i] <= 0) { ok = false; break; } mp[pre[i]] = i; } if(!ok) { std::cout << -1 << std::endl; continue; } for(int i = 1; i <= n; i++) { std::cout << pre[i] << " "; } std::cout << std::endl; } return 0; }
[ "ji.zhang@ushow.media" ]
ji.zhang@ushow.media
34fb1361114d4ecd29f57e33f36356909b06ed60
1baca084493a425d9d197b3ed360e36eaede548f
/Source/OrcMustFry/OMFBoomBarrelTrap.cpp
9981cfcd7a3b8bc022f6781071e492023c6c946e
[]
no_license
IanisP/OrcMustFry
4c168d4a28e24ebb2ff74d366feccde7aa2ca551
cf88a598d4878acfb89ca3ce4d97f7dd3b511650
refs/heads/master
2020-04-06T18:41:09.444401
2018-11-16T12:04:07
2018-11-16T12:04:07
157,708,484
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "OMFBoomBarrelTrap.h"
[ "ianispignon@gmail.com" ]
ianispignon@gmail.com
55543d5409d442684ada0047706e8807cd0a8576
2cb7a5837d0ccefe5a50dbb90d2756c35cd6303b
/src/SerialPort.h
833e5ce57a004dfcb63ca36411856a3bd3f0cfc1
[]
no_license
ct7ahx/CA
90c83c7257c04f5a4581c4a15f06401b1884b3b0
68439f3e34a2dc50777f018ef6af24309e5b3864
refs/heads/master
2018-12-29T02:34:37.930230
2014-03-23T21:45:46
2014-03-23T21:45:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
646
h
/* * SerialPort.h * * Created on: Jun 20, 2011 * Author: jose */ #ifndef SERIALPORT_H_ #define SERIALPORT_H_ #include <stdio.h> #include <iostream> #include <termios.h> #include <unistd.h> /* UNIX standard function definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <fcntl.h> #include <unistd.h> using namespace std; class SerialPort { private: int fileDescriptor; public: int connect (const char device[]); void disconnect(void); int sendArray(string buffer, int len); int getArray (string buffer, int len); int bytesToRead(); void clear(); }; #endif /* SERIALPORT_H_ */
[ "rubencapitao@gmail.com" ]
rubencapitao@gmail.com
a618b827c1f9ff5821245a43536125328fec85bd
8fbc0a30921bee6ec0161b9e263fb3cef2a3c0a4
/bzoj/3573.cpp
a46e40def2cbef538abed01c72c4cf37218614f5
[ "WTFPL" ]
permissive
swwind/code
57d0d02c166d1c64469e0361fc14355d866079a8
c240122a236e375e43bcf145d67af5a3a8299298
refs/heads/master
2023-06-17T15:25:07.412105
2023-05-29T11:21:31
2023-05-29T11:21:31
93,724,691
3
0
null
null
null
null
UTF-8
C++
false
false
1,051
cpp
#include <bits/stdc++.h> #define N 500050 #define ll long long using namespace std; double a[N], s[N], val[N]; int d[N], last[N], tmp = 1, ans, n, cnt, x, y; struct node{ int to, nxt; node(){} node(int x, int y):to(x), nxt(y){} }e[N<<1]; void insert(int x, int y){ e[++cnt] = node(y, last[x]); last[x] = cnt; e[++cnt] = node(x, last[y]); last[y] = cnt; } void dfs(int x, int fa){ for(int i = last[x]; i; i = e[i].nxt) if(e[i].to != fa) s[e[i].to] = s[x] + log(d[x]), dfs(e[i].to, x); } int main(){ scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", a+i); for(int i = 1; i < n; i++) scanf("%d%d", &x, &y), insert(x, y), d[x]++, d[y]++; for(int i = 2; i <= n; i++) d[i]--; s[1] = log(1); dfs(1, 0); for(int i = 1; i <= n; i++) val[i] = s[i] + log(a[i]); sort(val+1, val+n+1); for(int i = 2; i <= n; i++) if(val[i]-val[i-1] < 1e-5) tmp++; else ans = max(ans, tmp), tmp = 1; ans = max(ans, tmp); printf("%d\n", n-ans); return 0; } //Copy from hzwer.com
[ "swwind233@gmail.com" ]
swwind233@gmail.com
51d353caedd02e4b3d36867208c8687c6ef35776
af8385ee2686f41bb99605a4725a9c23e8955111
/Source Code/game.cpp
cede2c6100fcf7bfc8897484a7035a03580ba8c6
[]
no_license
AbhiSharma1999/Bloxorz_clone
c218956359315ee48c685c328d39cfd39a597cfa
ee49446b78d0de19097ea5163efbf82fa265909d
refs/heads/master
2022-11-05T00:59:23.706537
2020-06-23T20:06:01
2020-06-23T20:06:01
274,499,014
0
0
null
null
null
null
UTF-8
C++
false
false
74,725
cpp
/* Abhishek Ashwanikumar Sharma 2017A7PS0150P Pulkit Agarwal 2016A7PS0060P */ #include <iostream> #include <cmath> #include <fstream> #include <vector> #include <map> #include <ao/ao.h> #include <mpg123.h> #include <include/glad/glad.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> #define BITS 8 using namespace std; typedef struct VAO { GLuint VertexArrayID; GLuint VertexBuffer; GLuint ColorBuffer; GLenum PrimitiveMode; GLenum FillMode; int NumVertices; }VAO; typedef struct COLOUR { float r; float g; float b; }COLOUR; typedef struct Sprite { string name; COLOUR colour; float x,y,z; VAO* object; int status; float height,width,depth; float x_change,y_change,z_change; float angle; //Current Angle float radius; int fixed; float flag ; //Value from 0 to 1 int direction; //0 for clockwise and 1 for anticlockwise for animation }Sprite; struct GLMatrices { glm::mat4 projection; glm::mat4 model; glm::mat4 view; GLuint MatrixID; } Matrices; struct GLMatrices Matrices1; map <string, Sprite> tiles; map <string, Sprite> weakTiles; map <string, Sprite> block; map <string, Sprite> switches; map <string, Sprite> point1; map <string, Sprite> point2; map <string, Sprite> point3; map <string, Sprite> s1; map <string, Sprite> s2; map <string, Sprite> m1; map <string, Sprite> m2; map <string, Sprite> label; map <string, Sprite> endlabel; glm::mat4 rotateblock = glm::mat4(1.0f); int seconds=0; float zoomCamera = 1; float gameOver=0; GLuint programID; //load Shaders GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if(VertexShaderStream.is_open()) { std::string Line = ""; while(getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if(FragmentShaderStream.is_open()){ std::string Line = ""; while(getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Vertex Shader: %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader printf("Fragment Shader: %s\n", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program fprintf(stdout, "Creating Program Link\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) ); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } static void errorHandling(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } void quitGame(GLFWwindow *window) { glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } /* Generate VAO, VBOs and return VAO handle */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertexBufferData, const GLfloat* colorBufferData, GLenum fill_mode=GL_FILL) { struct VAO* vao = new struct VAO; vao->PrimitiveMode = primitive_mode; vao->NumVertices = numVertices; vao->FillMode = fill_mode; // Create Vertex Array Object // Should be done after CreateWindow and before any other GL calls glGenVertexArrays(1, &(vao->VertexArrayID)); // VAO glGenBuffers (1, &(vao->VertexBuffer)); // VBO - vertices glGenBuffers (1, &(vao->ColorBuffer)); // VBO - colors glBindVertexArray (vao->VertexArrayID); // Bind the VAO glBindBuffer (GL_ARRAY_BUFFER, vao->VertexBuffer); // Bind the VBO vertices glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), vertexBufferData, GL_STATIC_DRAW); // Copy the vertices into VBO glVertexAttribPointer( 0, // attribute 0. Vertices 3, // size (x,y,z) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glBindBuffer (GL_ARRAY_BUFFER, vao->ColorBuffer); // Bind the VBO colors glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), colorBufferData, GL_STATIC_DRAW); // Copy the vertex colors glVertexAttribPointer( 1, // attribute 1. Color 3, // size (r,g,b) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); return vao; } /* Generate VAO, VBOs and return VAO handle - Common Color for all vertices */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertexBufferData, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode=GL_FILL) { GLfloat* colorBufferData = new GLfloat [3*numVertices]; for(int i=0; i<numVertices;i++){ colorBufferData [3*i] = red; colorBufferData [3*i + 1] = green; colorBufferData [3*i + 2] = blue; } return create3DObject(primitive_mode, numVertices, vertexBufferData, colorBufferData, fill_mode); } /* Render the VBOs handled by VAO */ void draw3DObject (struct VAO* vao) { // Change the Fill Mode for this object glPolygonMode (GL_FRONT_AND_BACK, vao->FillMode); // Bind the VAO to use glBindVertexArray (vao->VertexArrayID); // Enable Vertex Attribute 0 - 3d Vertices glEnableVertexAttribArray(0); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->VertexBuffer); // Enable Vertex Attribute 1 - Color glEnableVertexAttribArray(1); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->ColorBuffer); // Draw the geometry ! glDrawArrays(vao->PrimitiveMode, 0, vao->NumVertices); // Starting from vertex 0; 3 vertices total -> 1 triangle } int level =0; int moves =0; double launch_angle=0; int keyboard_pressed=0; bool upKeyPressed=0; bool downKeyPressed=0; bool leftKeyPressed=0; bool rightKeyPressed=0; void mousescroll(GLFWwindow* window, double xoffset, double yoffset){ Matrices.projection = glm::perspective(glm::radians(45.0f),(float)1000/(float)800, 0.1f, 5000.0f); } bool tKeyPressed =0; //int hKeyPressed =0; bool fKeyPressed =0; bool bKeyPressed =0; float xEye = -300; float yEye = 1000; float zEye = 600; float xTarget = -200; float yTarget = -100; float zTarget = 0; mpg123_handle *mh; unsigned char *buffer; size_t bufferSize; size_t done; int err; int driver; ao_device *dev; ao_sample_format format; int channels, encoding; long rate; void initializeAudio() { ao_initialize(); driver = ao_default_driver_id(); mpg123_init(); mh = mpg123_new(NULL, &err); bufferSize = 3500; buffer = (unsigned char*) malloc(bufferSize * sizeof(unsigned char)); mpg123_open(mh, "./background.mp3"); mpg123_getformat(mh, &rate, &channels, &encoding); format.bits = mpg123_encsize(encoding) * BITS; format.rate = rate; format.channels = channels; format.byte_format = AO_FMT_NATIVE; format.matrix = 0; dev = ao_open_live(driver, &format, NULL); } void playAudio() { if (mpg123_read(mh, buffer, bufferSize, &done) == MPG123_OK) ao_play(dev, (char*) buffer, done); else mpg123_seek(mh, 0, SEEK_SET); } void clearAudio() { free(buffer); ao_close(dev); mpg123_close(mh); mpg123_delete(mh); mpg123_exit(); ao_shutdown(); } void keyPress (GLFWwindow* window, int key, int scancode, int action, int mods){ if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_F: //front view fKeyPressed =1; tKeyPressed =0; bKeyPressed =0; break; case GLFW_KEY_B: //back view bKeyPressed =1; tKeyPressed =0; fKeyPressed =0; break; case GLFW_KEY_T: //top view tKeyPressed = 1; bKeyPressed =0; fKeyPressed =0; break; case GLFW_KEY_H: //Helicopter view xEye = -300; yEye = 1000; zEye = 600; xTarget = -200; yTarget = -100; zTarget = 0; tKeyPressed =0; fKeyPressed =0; bKeyPressed =0; break; case GLFW_KEY_DOWN: // go back downKeyPressed =1; moves++; break; case GLFW_KEY_UP: //go ahead upKeyPressed = 1; moves++; break; case GLFW_KEY_LEFT: //go left leftKeyPressed =1; moves++; break; case GLFW_KEY_RIGHT: //go right rightKeyPressed =1; moves++; break; case GLFW_KEY_ESCAPE: //quit game quitGame(window); break; default: break; } } } void reshapeWindow (GLFWwindow* window, int width, int height) { int fbwidth=width, fbheight=height; glfwGetFramebufferSize(window, &fbwidth, &fbheight); GLfloat fov = 90.0f; // sets the viewport of openGL renderer glViewport (0, 0, (GLsizei) fbwidth, (GLsizei) fbheight); Matrices.projection = glm::perspective(fov,(float)fbwidth/(float)fbheight, 0.1f, 5000.0f); } //Creating the Cubes void makeCube(string name,COLOUR top,COLOUR bottom,COLOUR right,COLOUR left,COLOUR away,COLOUR close,float x, float y ,float z,float width,float height,float depth,string part) { GLfloat vertexBufferData []= { //Face1 -(width/2),-(height/2),-(depth/2), //vertex1 -(width/2),(height/2),-(depth/2), //vertex2 (width/2),(height/2),-(depth/2), //vertex3 (width/2),(height/2),-(depth/2), //vertex3 (width/2),-(height/2),-(depth/2), //vertex4 -(width/2),-(height/2),-(depth/2), //vertex1 //Face2 -(width/2),-(height/2),(depth/2), //vertex5 -(width/2),(height/2),(depth/2), //vertex6 (width/2),(height/2),(depth/2), //vertex7 (width/2),(height/2),(depth/2), //vertex7 (width/2),-(height/2),(depth/2), //vertex8 -(width/2),-(height/2),(depth/2), //vertex5 //Face3 -(width/2),(height/2),(depth/2), //vertex6 -(width/2),(height/2),-(depth/2), //vertex2 -(width/2),-(height/2),(depth/2), //vertex5 -(width/2),-(height/2),(depth/2), //vertex5 -(width/2),-(height/2),-(depth/2), //vertex1 -(width/2),(height/2),-(depth/2), //vertex2 //Face4 (width/2),(height/2),(depth/2), //vertex7 (width/2),-(height/2),(depth/2), //vertex8 (width/2),(height/2),-(depth/2), //vertex3 (width/2),(height/2),-(depth/2), //vertex3 (width/2),-(height/2),-(depth/2), //vertex4 (width/2),-(height/2),(depth/2), //vertex8 //Face5 -(width/2),(height/2),(depth/2), //vertex6 -(width/2),(height/2),-(depth/2), //vertex2 (width/2),(height/2),(depth/2), //vertex7 (width/2),(height/2),(depth/2), //vertex7 (width/2),(height/2),-(depth/2), //vertex3 -(width/2),(height/2),-(depth/2), //vertex2 //Face6 -(width/2),-(height/2),(depth/2), //vertex5 -(width/2),-(height/2),-(depth/2), //vertex1 (width/2),-(height/2),(depth/2), //vertex8 (width/2),-(height/2),(depth/2), //vertex8 (width/2),-(height/2),-(depth/2), //vertex4 -(width/2),-(height/2),-(depth/2) //vertex1 }; GLfloat colorBufferData [] = { //Face 1 away.r,away.g,away.b, //vertex1 away.r,away.g,away.b, //vertex2 away.r,away.g,away.b, //vertex3 away.r,away.g,away.b, //vertex3 away.r,away.g,away.b, //vertex4 away.r,away.g,away.b, //vertex1 //Face 2 close.r,close.g,close.b, //vertex5 close.r,close.g,close.b, //vertex6 close.r,close.g,close.b, //vertex7 close.r,close.g,close.b, //vertex7 close.r,close.g,close.b, //vertex8 close.r,close.g,close.b, //vertex5 //Face3 left.r,left.g,left.b, //vertex6 left.r,left.g,left.b, //vertex2 left.r,left.g,left.b, //vertex5 left.r,left.g,left.b, //vertex5 left.r,left.g,left.b, //vertex1 left.r,left.g,left.b, //vertex2 //Face4 right.r,right.g,right.b, //vertex7 right.r,right.g,right.b, //vertex8 right.r,right.g,right.b, //vertex3 right.r,right.g,right.b, //vertex3 right.r,right.g,right.b, //vertex4 right.r,right.g,right.b, //vertex8 //Face5 top.r,top.g,top.b, //vertex6 top.r,top.g,top.b, //vertex2 top.r,top.g,top.b, //vertex7 top.r,top.g,top.b, //vertex7 top.r,top.g,top.b, //vertex3 top.r,top.g,top.b, //vertex2 //Face6 bottom.r,bottom.g,bottom.b, //vertex5 bottom.r,bottom.g,bottom.b, //vertex1 bottom.r,bottom.g,bottom.b, //vertex8 bottom.r,bottom.g,bottom.b, //vertex8 bottom.r,bottom.g,bottom.b, //vertex4 bottom.r,bottom.g,bottom.b //vertex1 }; VAO *cube = create3DObject(GL_TRIANGLES,36,vertexBufferData,colorBufferData,GL_FILL); Sprite sprite = {}; sprite.colour = top; sprite.name = name; sprite.object = cube; sprite.x=x; sprite.y=y; sprite.z=z; sprite.height=height; sprite.width=width; sprite.depth=depth; sprite.status=1; sprite.x_change=x; sprite.y_change=y; sprite.z_change=z; sprite.fixed=0; sprite.flag=0; if(part=="tiles") tiles[name]=sprite; else if(part=="weakTiles") weakTiles[name]=sprite; else if(part=="block") block[name]=sprite; } void makeRectangle(string name, COLOUR c1, COLOUR c2, COLOUR c3, COLOUR c4, float x, float y, float height, float width, string part){ // GL3 accepts only Triangles. Quads are not supported float w=width/2,h=height/2; GLfloat vertexBufferData [] = { -w,-h,0, // vertex1 -w,h,0, // vertex2 w,h,0, // vertex3 w,h,0, // vertex3 w,-h,0, // vertex4 -w,-h,0 // vertex1 }; GLfloat colorBufferData [] = { c1.r,c1.g,c1.b, // colour1 c2.r,c2.g,c2.b, // colour2 c3.r,c3.g,c3.b, // colour3 c3.r,c3.g,c3.b, // colour4 c4.r,c4.g,c4.b, // colour5 c1.r,c1.g,c1.b // colour6 }; // create3DObject creates and returns a handle to a VAO that can be used later VAO *rectangle = create3DObject(GL_TRIANGLES, 6, vertexBufferData, colorBufferData, GL_FILL); Sprite sprite = {}; sprite.colour = c1; sprite.name = name; sprite.object = rectangle; sprite.x=x; sprite.y=y; sprite.height=height; sprite.width=width; sprite.status=1; sprite.fixed=0; sprite.angle=launch_angle; sprite.radius=(sqrt(height*height+width*width))/2; sprite.flag=0; if(part=="block") block[name]=sprite; else if(part=="point1") point1[name]=sprite; else if(part=="point2") point2[name]=sprite; else if(part=="point3") point3[name]=sprite; else if(part=="s1") s1[name]=sprite; else if(part=="s2") s2[name]=sprite; else if(part=="m1") m1[name]=sprite; else if(part=="m2") m2[name]=sprite; else if(part=="label") label[name]=sprite; } void createCircle (string name, COLOUR colour, float x,float y,float z, float r, int NoOfSegments, string part, int fill){ int segments = NoOfSegments; float radius = r; GLfloat vertexBufferData[segments*9]; GLfloat colorBufferData[segments*9]; int i,j; float angle=(2*M_PI/segments); float current_angle = 0; for(i=0;i<segments;i++){ for(j=0;j<3;j++){ colorBufferData[i*9+j*3]=colour.r; colorBufferData[i*9+j*3+1]=colour.g; colorBufferData[i*9+j*3+2]=colour.b; } vertexBufferData[i*9]=0; vertexBufferData[i*9+1]=1; vertexBufferData[i*9+2]=0; vertexBufferData[i*9+3]=radius*cos(current_angle); vertexBufferData[i*9+4]=1; vertexBufferData[i*9+5]=radius*sin(current_angle); vertexBufferData[i*9+6]=radius*cos(current_angle+angle); vertexBufferData[i*9+7]=1; vertexBufferData[i*9+8]=radius*sin(current_angle+angle); current_angle+=angle; } VAO* circle; if(fill==1) circle = create3DObject(GL_TRIANGLES, (segments*9)/3, vertexBufferData, colorBufferData, GL_FILL); else circle = create3DObject(GL_TRIANGLES, (segments*9)/3, vertexBufferData, colorBufferData, GL_LINE); Sprite sprite = {}; sprite.colour = colour; sprite.name = name; sprite.object = circle; sprite.x=x; sprite.y=y; sprite.z=z; sprite.height=2*r; //Height of the sprite is 2*r sprite.width=2*r; //Width of the sprite is 2*r sprite.status=1; sprite.radius=r; sprite.fixed=0; if(part=="switch") switches[name]=sprite; } // Render the scene with openGL float angle=0; float xpos; float ypos = 2720; int num = 1; int flag =0; int gir1 =0; int gir2 =0; int score =0; int gameover=0; int count=0; float downfall =.1; float downtile = 0; int tileflag =0; float tileX; float tileZ; int switch1 =0; int switch2 =0; int sig=0; void draw (GLFWwindow* window, int width, int height) { if(gameover ==1) return; if(tKeyPressed == 1){ xEye = block["block"].x_change; yEye = 1300; zEye = block["block"].z_change; xTarget = block["block"].x_change; yTarget = 0; zTarget = block["block"].z_change - 10; } else if(fKeyPressed ==1){ xEye = block["block"].x_change ; yEye = block["block"].y_change +300; zEye = block["block"].z_change +300; xTarget = block["block"].x_change; yTarget = block["block"].y_change; zTarget = block["block"].z_change; } else if(bKeyPressed ==1){ xEye = block["block"].x_change; yEye = block["block"].y_change + 300; zEye = block["block"].z_change + 50; xTarget = block["block"].x_change; yTarget = block["block"].y_change; zTarget = block["block"].z_change - 200; } glClearColor(184.0f/255.0f, 213.0f/255.0f, 238.0f/255.0f, 1.0f);//set background colour glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram (programID); glm::vec3 eye ( xEye ,yEye, zEye ); glm::vec3 target (xTarget,yTarget, zTarget); glm::vec3 up (0, 1, 0); Matrices.view = glm::lookAt(eye, target, up); for(map<string,Sprite>::iterator it=point1.begin();it!=point1.end();it++){ point1[it->first].status=0; } for(map<string,Sprite>::iterator it=point2.begin();it!=point2.end();it++){ point2[it->first].status=0; } for(map<string,Sprite>::iterator it=point3.begin();it!=point3.end();it++){ point3[it->first].status=0; } for(map<string,Sprite>::iterator it=s1.begin();it!=s1.end();it++){ s1[it->first].status=0; } for(map<string,Sprite>::iterator it=s2.begin();it!=s2.end();it++){ s2[it->first].status=0; } for(map<string,Sprite>::iterator it=m1.begin();it!=m1.end();it++){ m1[it->first].status=0; } for(map<string,Sprite>::iterator it=m2.begin();it!=m2.end();it++){ m2[it->first].status=0; } int time = abs(seconds % 60); int t; t = time%10; if(t == 0 || t == 2 ||t == 3 ||t == 5 ||t == 6 ||t == 7 ||t == 8 ||t == 9){ s1["seg1"].status=1; } if(t == 0 || t == 1 ||t == 2 ||t == 3 ||t == 4 ||t == 7 ||t == 8 ||t == 9){ s1["seg2"].status=1; } if(t == 0 || t == 1 ||t == 3 ||t == 4 ||t == 5 ||t == 6 ||t == 7 ||t == 8 ||t == 9){ s1["seg3"].status=1; } if(t == 0 || t == 2 ||t == 3 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s1["seg4"].status=1; } if(t == 0 || t == 2 ||t == 6 ||t == 8){ s1["seg5"].status=1; } if(t == 0 || t == 4 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s1["seg6"].status=1; } if(t == 2 ||t == 3 ||t == 4 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s1["seg7"].status=1; } time = time/10; t = time%10; if(t == 0 || t == 2 ||t == 3 ||t == 5 ||t == 6 ||t == 7 ||t == 8 ||t == 9){ s2["seg1"].status=1; } if(t == 0 || t == 1 ||t == 2 ||t == 3 ||t == 4 ||t == 7 ||t == 8 ||t == 9){ s2["seg2"].status=1; } if(t == 0 || t == 1 ||t == 3 ||t == 4 ||t == 5 ||t == 6 ||t == 7 ||t == 8 ||t == 9){ s2["seg3"].status=1; } if(t == 0 || t == 2 ||t == 3 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s2["seg4"].status=1; } if(t == 0 || t == 2 ||t == 6 ||t == 8){ s2["seg5"].status=1; } if(t == 0 || t == 4 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s2["seg6"].status=1; } if(t == 2 ||t == 3 ||t == 4 ||t == 5 ||t == 6 ||t == 8 ||t == 9){ s2["seg7"].status=1; } for(map<string,Sprite>::iterator it=s1.begin();it!=s1.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; if(s1[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(s1[current].x,s1[current].y, 0.0f)); ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(s1[current].object); } for(map<string,Sprite>::iterator it=s2.begin();it!=s2.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; if(s2[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(s2[current].x,s2[current].y, 0.0f)); ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(s2[current].object); } int time1 = abs(seconds/60); int t1 = time1%10; if(t1 == 0 || t1 == 2 ||t1 == 3 ||t1 == 5 ||t1 == 6 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m1["seg1"].status=1; } if(t1 == 0 || t1 == 1 ||t1 == 2 ||t1 == 3 ||t1 == 4 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m1["seg2"].status=1; } if(t1 == 0 || t1 == 1 ||t1 == 3 ||t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m1["seg3"].status=1; } if(t1 == 0 || t1 == 2 ||t1 == 3 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m1["seg4"].status=1; } if(t1 == 0 || t1 == 2 ||t1 == 6 ||t1 == 8){ m1["seg5"].status=1; } if(t1 == 0 || t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m1["seg6"].status=1; } if(t1 == 2 ||t1 == 3 ||t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m1["seg7"].status=1; } time1 = time1/10; t1=time1%10; if(t1 == 0 || t1 == 2 ||t1 == 3 ||t1 == 5 ||t1 == 6 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m2["seg1"].status=1; } if(t1 == 0 || t1 == 1 ||t1 == 2 ||t1 == 3 ||t1 == 4 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m2["seg2"].status=1; } if(t1 == 0 || t1 == 1 ||t1 == 3 ||t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 7 ||t1 == 8 ||t1 == 9){ m2["seg3"].status=1; } if(t1 == 0 || t1 == 2 ||t1 == 3 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m2["seg4"].status=1; } if(t1 == 0 || t1 == 2 ||t1 == 6 ||t1 == 8){ m2["seg5"].status=1; } if(t1 == 0 || t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m2["seg6"].status=1; } if(t1 == 2 ||t1 == 3 ||t1 == 4 ||t1 == 5 ||t1 == 6 ||t1 == 8 ||t1 == 9){ m2["seg7"].status=1; } for(map<string,Sprite>::iterator it=m1.begin();it!=m1.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; if(m1[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(m1[current].x,m1[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(m1[current].object); } for(map<string,Sprite>::iterator it=m2.begin();it!=m2.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; if(m2[current].status==0) continue; Matrices.model = glm::mat4(1.0f); /* Render your scene */ glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(m2[current].x,m2[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(m2[current].object); } for(map<string,Sprite>::iterator it=label.begin();it!=label.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(label[current].x,label[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(label[current].object); } int point = abs(moves); int p; p = point%10; if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point3["seg1"].status=1; } if(p == 0 || p == 1 ||p == 2 ||p == 3 ||p == 4 ||p == 7 ||p == 8 ||p == 9){ point3["seg2"].status=1; } if(p == 0 || p == 1 ||p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point3["seg3"].status=1; } if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point3["seg4"].status=1; } if(p == 0 || p == 2 ||p == 6 ||p == 8){ point3["seg5"].status=1; } if(p == 0 || p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point3["seg6"].status=1; } if(p == 2 ||p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point3["seg7"].status=1; } point =point/10; p =point%10; if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point2["seg1"].status=1; } if(p == 0 || p == 1 ||p == 2 ||p == 3 ||p == 4 ||p == 7 ||p == 8 ||p == 9){ point2["seg2"].status=1; } if(p == 0 || p == 1 ||p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point2["seg3"].status=1; } if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point2["seg4"].status=1; } if(p == 0 || p == 2 ||p == 6 ||p == 8){ point2["seg5"].status=1; } if(p == 0 || p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point2["seg6"].status=1; } if(p == 2 || p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point2["seg7"].status=1; } point =point/10; p =point%10; if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point1["seg1"].status=1; } if(p == 0 || p == 1 ||p == 2 ||p == 3 ||p == 4 ||p == 7 ||p == 8 ||p == 9){ point1["seg2"].status=1; } if(p == 0 || p == 1 ||p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 7 ||p == 8 ||p == 9){ point1["seg3"].status=1; } if(p == 0 || p == 2 ||p == 3 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point1["seg4"].status=1; } if(p == 0 || p == 2 ||p == 6 ||p == 8){ point1["seg5"].status=1; } if(p == 0 || p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point1["seg6"].status=1; } if(p == 2 || p == 3 ||p == 4 ||p == 5 ||p == 6 ||p == 8 ||p == 9){ point1["seg7"].status=1; } for(map<string,Sprite>::iterator it=point1.begin();it!=point1.end();it++){ string current = it->first; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; glm::mat4 MVP; if(point1[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(point1[current].x,point1[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(point1[current].object); } for(map<string,Sprite>::iterator it=point2.begin();it!=point2.end();it++){ string current = it->first; glm::mat4 MVP; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; if(point2[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(point2[current].x,point2[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(point2[current].object); } for(map<string,Sprite>::iterator it=point3.begin();it!=point3.end();it++){ string current = it->first; glm::mat4 MVP; glm::vec3 eye ( 0 ,0, 5 ); glm::vec3 target (0,0, 0); glm::vec3 up (0, 1, 0); Matrices1.view = glm::lookAt(eye, target, up); Matrices1.projection = glm::ortho((float)(-400.0f), (float)(400.0f), (float)(-300.0f), (float)(300.0f), 0.1f, 500.0f); glm::mat4 VP = Matrices1.projection * Matrices1.view; if(point3[current].status==0) continue; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(point3[current].x,point3[current].y, 0.0f)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(point3[current].object); } GLfloat fov = M_PI/4; Matrices.projection = glm::perspective(fov, (GLfloat) width / (GLfloat) height, 0.1f, 50000.0f); glm::mat4 VP = Matrices.projection * Matrices.view; glm::mat4 MVP; // MVP = Projection * View * Model // Load identity to model matrix Matrices.model = glm::mat4(1.0f); if(upKeyPressed ==1 && flag ==0)//handling the translation of the object { if(block["block"].direction ==0){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change - 30))); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change -30)); rotateblock = translateObject1*rotate*translateObject*rotateblock; block["block"].x_change += 0; block["block"].z_change -= 90.0; block["block"].y_change -= 30.0; block["block"].direction =2; } else if(block["block"].direction==1){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change - 30))); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change -30)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].z_change -= 60.0; } else if(block["block"].direction==2){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change - 60))); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change -60)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].y_change += 30.0; block["block"].z_change -= 90.0; block["block"].direction =0; } if(switches["switch1"].x == block["block"].x_change && switches["switch1"].z == block["block"].z_change){ if(switch1==1) switch1=0; else switch1 =1; } if(switches["switch3"].x == block["block"].x_change && switches["switch3"].z == block["block"].z_change){ if(switch2==1) switch2=0; else switch2 =1; } upKeyPressed =0; } if(downKeyPressed ==1 && flag ==0)//handling the translation of the object { if(block["block"].direction ==0){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change + 30))); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change +30)); rotateblock = translateObject1*rotate*translateObject*rotateblock; block["block"].x_change += 0; block["block"].z_change += 90.0; block["block"].y_change -= 30.0; block["block"].direction =2; } else if(block["block"].direction==1){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change + 30))); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change +30)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].z_change += 60.0; } else if(block["block"].direction==2){ glm::mat4 translateObject = glm::translate (glm::vec3(0,0,-(block["block"].z_change + 60))); glm::mat4 rotate = glm::rotate((float)((+90.0)*M_PI/180.0f), glm::vec3(1,0,0)); glm::mat4 translateObject1 = glm::translate (glm::vec3(0,0,block["block"].z_change +60)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].y_change += 30.0; block["block"].z_change += 90.0; block["block"].direction =0; } downKeyPressed =0; } if(rightKeyPressed ==1 && flag==0)//handling the translation of the object { if(block["block"].direction ==0){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change + 30.0),0,0)); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change + 30.0,0,0)); rotateblock = translateObject1*rotate*translateObject*rotateblock; block["block"].x_change += 90.0; block["block"].y_change -= 30.0; block["block"].direction =1; } else if(block["block"].direction==1){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change + 60),0,0)); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change + 60,0,0)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].x_change += 90.0; block["block"].y_change += 30.0; block["block"].direction = 0; } else if(block["block"].direction==2){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change + 30.0),0,0)); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change + 30.0,0,0)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].x_change += 60.0; block["block"].direction = 2; } rightKeyPressed =0; } if(leftKeyPressed ==1 && flag==0)//handling the translation of the object { if(block["block"].direction ==0){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change - 30.0),0,0)); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change - 30.0,0,0)); rotateblock = translateObject1*rotate*translateObject*rotateblock; block["block"].x_change -= 90.0; block["block"].y_change -= 30.0; block["block"].direction =1; } else if(block["block"].direction==1){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change - 60),0,0)); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change - 60,0,0)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].x_change -= 90.0; block["block"].y_change += 30.0; block["block"].direction = 0; } else if(block["block"].direction==2){ glm::mat4 translateObject = glm::translate (glm::vec3(-(block["block"].x_change - 30.0),0,0)); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translateObject1 = glm::translate (glm::vec3(block["block"].x_change - 30.0,0,0)); rotateblock = translateObject1 * rotate * translateObject * rotateblock; block["block"].x_change -= 60.0; block["block"].direction = 2; } leftKeyPressed =0; } if(level==0)//second level { flag =1; gir1=0; gir2=0; for(map<string,Sprite>::iterator it=weakTiles.begin();it!=weakTiles.end();it++){ string current = it->first; float XX = block["block"].x_change; float ZZ = block["block"].z_change; if(block["block"].direction == 0){ if(weakTiles[current].x == XX && weakTiles[current].z == ZZ){ flag =0 ; break; } if(XX == -380 && ZZ == -120){ sig=1; break; } } if(block["block"].direction == 1){ if(weakTiles[current].z == ZZ){ if(weakTiles[current].x + 30.0 == XX || weakTiles[current].x - 30.0 == XX ||( XX<=-320 && XX>= -440 && ZZ ==-120)){ if(gir1 ==1) gir2 =1; else gir1 =1; } if(gir1 == 1 && gir2 ==1){ flag =0 ; break; } } } if(block["block"].direction == 2){ if(weakTiles[current].x == XX){ if(weakTiles[current].z + 30.0 == ZZ || weakTiles[current].z - 30.0 == ZZ || ( ZZ<= -60 && ZZ>= -180 && XX ==-380)){ if(gir1 ==1) gir2 =1; else gir1 =1; } if(gir1 == 1 && gir2 ==1){ flag =0 ; break; } } } } } if(level==1)//first level { flag =1; gir1=0; gir2=0; for(map<string,Sprite>::iterator it=tiles.begin();it!=tiles.end();it++){ string current = it->first; float XX = block["block"].x_change; float ZZ = block["block"].z_change; if(block["block"].direction == 0){ if(tiles[current].x == XX && tiles[current].z == ZZ){ if(current[0] == 'o'){ tileflag =1; tileX = tiles[current].x; tileZ = tiles[current].z; break; } else{ flag =0 ; break; } } if(XX == -380 && ZZ == -120){ moves=0; seconds=0; } } if(block["block"].direction == 1){ if(tiles[current].z == ZZ){ if(tiles[current].x + 30.0 == XX || tiles[current].x - 30.0 == XX ||( XX<=-320 && XX>= -440 && ZZ ==-120)){ if(gir1 ==1) gir2 =1; else gir1 =1; } if(gir1 == 1 && gir2 ==1){ flag =0 ; break; } } } if(block["block"].direction == 2){ if(tiles[current].x == XX){ if(tiles[current].z + 30.0 == ZZ || tiles[current].z - 30.0 == ZZ || ( ZZ<= -60 && ZZ>= -180 && XX ==-380)){ if(gir1 ==1) gir2 =1; else gir1 =1; } if(gir1 == 1 && gir2 ==1){ flag =0 ; break; } } } } if(switch1==0)//handling switches { float XX = block["block"].x_change; float ZZ = block["block"].z_change; if( XX >= -80 && XX <= -50 && ZZ <=210 && ZZ >= 180) flag =1; } if(switch2==0)//handling switches { if(block["block"].z_change ==0 && block["block"].x_change >= -50 && block["block"].x_change <= 70) flag =1; } } glm::mat4 rotatetile1 = glm::mat4(1.0f); glm::mat4 rotatetile2 = glm::mat4(1.0f); glm::mat4 rotatetile3 = glm::mat4(1.0f); if(switch1==0)//Handle switches { glm::mat4 translatetile = glm::translate (glm::vec3(-(tiles["tile31"].x_change - 30.0),12,0)); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translatetile1 = glm::translate (glm::vec3(tiles["tile31"].x_change - 30.0,-12,0)); rotatetile3 = translatetile1 * rotate * translatetile; } if(switch2==0)//Handle switches { glm::mat4 translatetile = glm::translate (glm::vec3(-(tiles["tile5"].x_change - 30.0),12,0)); glm::mat4 rotate = glm::rotate((float)((-90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translatetile1 = glm::translate (glm::vec3(tiles["tile5"].x_change - 30.0,-12,0)); rotatetile1 = translatetile1 * rotate * translatetile; } if(switch2==0)//Handle switches { glm::mat4 translatetile = glm::translate (glm::vec3(-(tiles["tile6"].x_change + 30.0),12,0)); glm::mat4 rotate = glm::rotate((float)((90.0)*M_PI/180.0f), glm::vec3(0,0,1)); glm::mat4 translatetile1 = glm::translate (glm::vec3(tiles["tile6"].x_change + 30.0,-12,0)); rotatetile2 = translatetile1 * rotate * translatetile; } // Render your scene if(level==1){ glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(block["block"].x, block["block"].y,block["block"].z)); glm::mat4 translateblock = glm::translate (glm::vec3(0,-downfall,0)); if(flag ==1){ ObjectTransform= translateblock * rotateblock * translateObject ; block["block"].y_change -= 3; downfall += 3.0; } else ObjectTransform= rotateblock * translateObject ; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(block["block"].object); if(block["block"].y_change <= -200){ block["block"].x_change =block["block"].x; block["block"].y_change =block["block"].y; block["block"].z_change =block["block"].z; rotateblock = glm::mat4(1.0f); downfall =0; flag =0; block["block"].direction =0; tileflag =0; downtile =0; switch1=0; switch2=0; } } if(level==1){ for(map<string,Sprite>::iterator it=tiles.begin();it!=tiles.end();it++){ string current = it->first; glm::mat4 MVP; Matrices.model = glm::mat4(1.0f); /* Render your scene */ glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(tiles[current].x, tiles[current].y,tiles[current].z)); // glTranslatef glm::mat4 translatetile = glm::translate (glm::vec3(0,-downtile,0)); // glTranslatef if(tileflag ==1 && tiles[current].x==tileX && tiles[current].z==tileZ){ ObjectTransform = translatetile * translateObject; downtile += 5; } else{ if(current=="tile5"){ ObjectTransform = rotatetile1 * translateObject; } else if(current=="tile6"){ ObjectTransform = rotatetile2 * translateObject; } else if(current =="tile31"){ ObjectTransform = rotatetile3 * translateObject; } else ObjectTransform=translateObject; } Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(tiles[current].object); } for(map<string,Sprite>::iterator it=switches.begin();it!=switches.end();it++){ string current = it->first; glm::mat4 MVP; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(switches[current].x,switches[current].y,switches[current].z)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(switches[current].object); } } if(level==0){ for(map<string,Sprite>::iterator it=weakTiles.begin();it!=weakTiles.end();it++){ string current = it->first; glm::mat4 MVP; Matrices.model = glm::mat4(1.0f); // Render your scene glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(weakTiles[current].x, weakTiles[current].y,weakTiles[current].z)); // glTranslatef ObjectTransform=translateObject; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(weakTiles[current].object); } glm::mat4 ObjectTransform; glm::mat4 translateObject = glm::translate (glm::vec3(160.0,60.0,300.0)); // glTranslatef Matrices.model = glm::mat4(1.0f); glm::mat4 translateblock = glm::translate (glm::vec3(0,-downfall,0)); // glTranslatef if(flag ==1){ ObjectTransform= translateblock * rotateblock * translateObject ; block["block"].y_change -= 3; downfall += 3.0; } else ObjectTransform= rotateblock * translateObject ; Matrices.model *= ObjectTransform; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(block["block"].object); if(block["block"].y_change <= -200){ if(sig==1) level=1; else{ block["block"].x_change =160; block["block"].y_change =60; block["block"].z_change =300; } rotateblock = glm::mat4(1.0f); downfall =0; flag =0; block["block"].direction =0; } } } // Initialise glfw window, I/O callbacks and the renderer GLFWwindow* initGLFW (int width, int height) { GLFWwindow* window; // window desciptor/handle glfwSetErrorCallback(errorHandling); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(width ,height, "My openGL game", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval( 1 ); //registering callbacks with GLFW glfwSetFramebufferSizeCallback(window, reshapeWindow); glfwSetWindowSizeCallback(window, reshapeWindow); glfwSetWindowCloseCallback(window, quitGame); glfwSetKeyCallback(window, keyPress); // general keyboard input glfwSetScrollCallback(window, mousescroll); // mouse scroll return window; } //models created void initGL (GLFWwindow* window, int width, int height) { // Create the models COLOUR green = {0/255.0,255/255.0,0/255.0}; COLOUR ForestGreen = { 35/255.0,142/255.0,35/255.0}; COLOUR LimeGreen = {50/255.0,204/255.0, 50/255.0}; COLOUR orange = {204/255.0,50/255.0,50/255.0}; COLOUR DarkOrchid = {153/255.0,50/255.0,204/255.0}; COLOUR DimGrey = {84/255.0,84/255.0,84/255.0}; COLOUR Gold = {204/255.0,127/255.0,50/255.0}; COLOUR Goldenrod = {219/255.0,219/255.0,112/255.0}; COLOUR red = {255.0/255.0,2.0/255.0,0.0/255.0}; COLOUR MediumForestGreen = {107/255.0,142/255.0,35/255.0}; COLOUR black = {0/255.0,0/255.0,0/255.0}; COLOUR blue = { 0/255.0,0/255.0,255/255.0}; COLOUR Maroon = {142/255.0,35/255.0,107/255.0}; COLOUR lightbrown = {95/255.0,63/255.0,32/255.0}; COLOUR IndianRed = {79/255.0,47/255.0,47/255.0}; COLOUR cratebrown = {153/255.0,102/255.0,0/255.0}; COLOUR cratebrown1 = {121/255.0,85/255.0,0/255.0}; COLOUR cratebrown2 = {102/255.0,68/255.0,0/255.0}; COLOUR MidnightBlue = {47/255.0,47/255.0,79/255.0}; COLOUR NavyBlue = {35/255.0,35/255.0,142/255.0}; COLOUR SkyBlue = {50/255.0,153/255.0,204/255.0}; COLOUR Violet = {79/255.0,47/255.0,79/255.0}; COLOUR BlueViolet = {159/255.0,95/255.0,159/255.0}; COLOUR Pink = {188/255.0,143/255.0,143/255.0}; COLOUR darkpink = {255/255.0,51/255.0,119/255.0}; COLOUR White = {252/255.0,252/255.0,252/255.0}; COLOUR points = {117/255.0,78/255.0,40/255.0}; makeCube("block",green,green,ForestGreen,ForestGreen,LimeGreen,LimeGreen,-500,60,60,60.0,120.0,60.0,"block"); block["block"].direction = 0; makeCube("otile1",orange,Gold,points,DimGrey,Goldenrod,black,-200,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile2",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-140,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile3",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-200,-6,60,60.0,12.0,60.0,"tiles"); makeCube("tile4",blue,Gold,points,DimGrey,Goldenrod,black,-80,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile5",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-20,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile6",blue,Gold,points,DimGrey,Goldenrod,black,40,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile7",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile8",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,0,60.0,12.0,60.0,"tiles"); makeCube("tile10",blue,Gold,points,DimGrey,Goldenrod,black,100,-6,-60,60.0,12.0,60.0,"tiles"); makeCube("tile11",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,-60,60.0,12.0,60.0,"tiles"); makeCube("tile17",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,240,60.0,12.0,60.0,"tiles"); makeCube("tile18",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile19",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,240,60.0,12.0,60.0,"tiles"); createCircle("switch3",Goldenrod,100,0,240,25,200,"switch",1); createCircle("switch4",IndianRed,100,1,240,12,200,"switch",1); makeCube("tile20",blue,Gold,points,DimGrey,Goldenrod,black,100,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile21",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile22",SkyBlue,Gold,points,DimGrey,Goldenrod,black,40,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile23",blue,Gold,points,DimGrey,Goldenrod,black,40,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile24",blue,Gold,points,DimGrey,Goldenrod,black,-20,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile25",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-20,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile26",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-80,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile27",blue,Gold,points,DimGrey,Goldenrod,black,-80,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile28",blue,Gold,points,DimGrey,Goldenrod,black,-140,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile29",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-140,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile30",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-140,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile31",red,Gold,points,DimGrey,Goldenrod,black,-80,-6,240,60.0,12.0,60.0,"tiles"); makeCube("tile31",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-80,-6,180,60.0,12.0,60.0,"tiles"); makeCube("otile32",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-200,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile33",red,Gold,points,DimGrey,Goldenrod,IndianRed,-200,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile34",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-260,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile35",red,Gold,points,DimGrey,Goldenrod,IndianRed,-260,-6,240,60.0,12.0,60.0,"tiles"); makeCube("tile36",SkyBlue,Gold,points,DimGrey,Goldenrod,DarkOrchid,-320,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile37",red,Gold,points,DimGrey,Goldenrod,IndianRed,-320,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile38",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-380,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile39",red,Gold,points,DimGrey,Goldenrod,IndianRed,-380,-6,240,60.0,12.0,60.0,"tiles"); makeCube("tile40",SkyBlue,Gold,points,DimGrey,Goldenrod,DarkOrchid,-440,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile41",red,Gold,points,DimGrey,Goldenrod,IndianRed,-440,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile42",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-500,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile43",red,Gold,points,DimGrey,Goldenrod,IndianRed,-500,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile44",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-560,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile45",red,Gold,points,DimGrey,Goldenrod,IndianRed,-560,-6,300,60.0,12.0,60.0,"tiles"); makeCube("tile46",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-620,-6,300,60.0,12.0,60.0,"tiles"); makeCube("otile47",red,Gold,points,DimGrey,Goldenrod,IndianRed,-620,-6,240,60.0,12.0,60.0,"tiles"); makeCube("otile48",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-560,-6,360,60.0,12.0,60.0,"tiles"); makeCube("tile49",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-500,-6,360,60.0,12.0,60.0,"tiles"); makeCube("otile50",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-440,-6,360,60.0,12.0,60.0,"tiles"); makeCube("otile51",red,Gold,points,DimGrey,Goldenrod,IndianRed,-380,-6,360,60.0,12.0,60.0,"tiles"); makeCube("otile52",orange,Gold,points,DimGrey,Goldenrod,DarkOrchid,-320,-6,360,60.0,12.0,60.0,"tiles"); makeCube("otile53",orange,Gold,points,DimGrey,Goldenrod,IndianRed,-620,-6,180,60.0,12.0,60.0,"tiles"); makeCube("otile54",red,Gold,points,DimGrey,Goldenrod,IndianRed,-560,-6,180,60.0,12.0,60.0,"tiles"); makeCube("otile55",orange,Gold,points,DimGrey,Goldenrod,IndianRed,-500,-6,180,60.0,12.0,60.0,"tiles"); makeCube("otile56",red,Gold,points,DimGrey,Goldenrod,IndianRed,-440,-6,180,60.0,12.0,60.0,"tiles"); makeCube("tile57",SkyBlue,Gold,points,DimGrey,Goldenrod,IndianRed,-560,-6,120,60.0,12.0,60.0,"tiles"); createCircle("switch1",Goldenrod,-560,0,120,25,200,"switch",1); createCircle("switch2",IndianRed,-560,1,120,12,200,"switch",1); makeCube("tile58",blue,Gold,points,DimGrey,Goldenrod,IndianRed,-500,-6,120,60.0,12.0,60.0,"tiles"); makeCube("tile59",SkyBlue,Gold,points,DimGrey,Goldenrod,IndianRed,-440,-6,120,60.0,12.0,60.0,"tiles"); makeCube("tile60",SkyBlue,Gold,points,DimGrey,Goldenrod,IndianRed,-500,-6,60,60.0,12.0,60.0,"tiles"); makeCube("tile61",blue,Gold,points,DimGrey,Goldenrod,black,-200,-6,120,60.0,12.0,60.0,"tiles"); makeCube("otile62",red,Gold,points,DimGrey,Goldenrod,black,-200,-6,180,60.0,12.0,60.0,"tiles"); makeCube("otile63",orange,Gold,points,DimGrey,Goldenrod,black,-140,-6,60,60.0,12.0,60.0,"tiles"); makeCube("otile64",red,Gold,points,DimGrey,Goldenrod,black,-140,-6,120,60.0,12.0,60.0,"tiles"); makeCube("tile65",blue,Gold,points,DimGrey,Goldenrod,black,-140,-6,180,60.0,12.0,60.0,"tiles"); makeCube("tile66",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,-120,60.0,12.0,60.0,"tiles"); makeCube("tile67",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,-120,60.0,12.0,60.0,"tiles"); makeCube("tile68",blue,Gold,points,DimGrey,Goldenrod,black,100,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile69",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile70",SkyBlue,Gold,points,DimGrey,Goldenrod,black,40,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile71",blue,Gold,points,DimGrey,Goldenrod,black,-20,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("otile72",red,Gold,points,DimGrey,Goldenrod,black,-80,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("otile73",orange,Gold,points,DimGrey,Goldenrod,black,-140,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile74",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-200,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile75",blue,Gold,points,DimGrey,Goldenrod,black,-260,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile76",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-260,-6,-120,60.0,12.0,60.0,"tiles"); makeCube("tile77",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile78",blue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-120,60.0,12.0,60.0,"tiles"); makeCube("tile79",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-60,60.0,12.0,60.0,"tiles"); makeCube("tile80",blue,Gold,points,DimGrey,Goldenrod,black,-380,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile81",blue,Gold,points,DimGrey,Goldenrod,black,-380,-6,-60,60.0,12.0,60.0,"tiles"); makeCube("tile82",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-180,60.0,12.0,60.0,"tiles"); makeCube("tile83",blue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-120,60.0,12.0,60.0,"tiles"); makeCube("tile84",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-60,60.0,12.0,60.0,"tiles"); makeRectangle("seg1",points,points,points,points,325,285,2,10,"point1"); makeRectangle("seg2",points,points,points,points,330,280,10,2,"point1"); makeRectangle("seg3",points,points,points,points,330,270,10,2,"point1"); makeRectangle("seg4",points,points,points,points,325,265,2,10,"point1"); makeRectangle("seg5",points,points,points,points,320,270,10,2,"point1"); makeRectangle("seg6",points,points,points,points,320,280,10,2,"point1"); makeRectangle("seg7",points,points,points,points,325,275,2,10,"point1"); point1["seg7"].status=0; makeRectangle("seg1",points,points,points,points,340,285,2,10,"point2"); makeRectangle("seg2",points,points,points,points,345,280,10,2,"point2"); makeRectangle("seg3",points,points,points,points,345,270,10,2,"point2"); makeRectangle("seg4",points,points,points,points,340,265,2,10,"point2"); makeRectangle("seg5",points,points,points,points,335,270,10,2,"point2"); makeRectangle("seg6",points,points,points,points,335,280,10,2,"point2"); makeRectangle("seg7",points,points,points,points,340,275,2,10,"point2"); point2["seg7"].status=0; makeRectangle("seg1",points,points,points,points,355,285,2,10,"point3"); makeRectangle("seg2",points,points,points,points,360,280,10,2,"point3"); makeRectangle("seg3",points,points,points,points,360,270,10,2,"point3"); makeRectangle("seg4",points,points,points,points,355,265,2,10,"point3"); makeRectangle("seg5",points,points,points,points,350,270,10,2,"point3"); makeRectangle("seg6",points,points,points,points,350,280,10,2,"point3"); makeRectangle("seg7",points,points,points,points,355,275,2,10,"point3"); point3["seg7"].status=0; makeRectangle("seg1",points,points,points,points,355,255,2,10,"s1"); makeRectangle("seg2",points,points,points,points,360,250,10,2,"s1"); makeRectangle("seg3",points,points,points,points,360,240,10,2,"s1"); makeRectangle("seg4",points,points,points,points,355,235,2,10,"s1"); makeRectangle("seg5",points,points,points,points,350,240,10,2,"s1"); makeRectangle("seg6",points,points,points,points,350,250,10,2,"s1"); makeRectangle("seg7",points,points,points,points,355,245,2,10,"s1"); s1["seg7"].status=0; makeRectangle("seg1",points,points,points,points,340,255,2,10,"s2"); makeRectangle("seg2",points,points,points,points,345,250,10,2,"s2"); makeRectangle("seg3",points,points,points,points,345,240,10,2,"s2"); makeRectangle("seg4",points,points,points,points,340,235,2,10,"s2"); makeRectangle("seg5",points,points,points,points,335,240,10,2,"s2"); makeRectangle("seg6",points,points,points,points,335,250,10,2,"s2"); makeRectangle("seg7",points,points,points,points,340,245,2,10,"s2"); s2["seg7"].status=0; makeRectangle("l1",points,points,points,points,330,250,3,3,"label"); makeRectangle("l2",points,points,points,points,330,240,3,3,"label"); makeRectangle("seg1",points,points,points,points,320,255,2,10,"m1"); makeRectangle("seg2",points,points,points,points,325,250,10,2,"m1"); makeRectangle("seg3",points,points,points,points,325,240,10,2,"m1"); makeRectangle("seg4",points,points,points,points,320,235,2,10,"m1"); makeRectangle("seg5",points,points,points,points,315,240,10,2,"m1"); makeRectangle("seg6",points,points,points,points,315,250,10,2,"m1"); makeRectangle("seg7",points,points,points,points,320,245,2,10,"m1"); m1["seg7"].status=0; makeRectangle("seg1",points,points,points,points,305,255,2,10,"m2"); makeRectangle("seg2",points,points,points,points,310,250,10,2,"m2"); makeRectangle("seg3",points,points,points,points,310,240,10,2,"m2"); makeRectangle("seg4",points,points,points,points,305,235,2,10,"m2"); makeRectangle("seg5",points,points,points,points,300,240,10,2,"m2"); makeRectangle("seg6",points,points,points,points,300,250,10,2,"m2"); makeRectangle("seg7",points,points,points,points,305,245,2,10,"m2"); m2["seg7"].status=0; /*level 1*/ makeCube("tile7",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,0,60.0,12.0,60.0,"weakTiles"); makeCube("tile8",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,0,60.0,12.0,60.0,"weakTiles"); makeCube("tile9",SkyBlue,Gold,points,DimGrey,Goldenrod,black,220,-6,0,60.0,12.0,60.0,"weakTiles"); makeCube("tile10",blue,Gold,points,DimGrey,Goldenrod,black,100,-6,-60,60.0,12.0,60.0,"weakTiles"); makeCube("tile11",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,-60,60.0,12.0,60.0,"weakTiles"); makeCube("tile12",blue,Gold,points,DimGrey,Goldenrod,black,220,-6,-60,60.0,12.0,60.0,"weakTiles"); makeCube("tile13",blue,Gold,points,DimGrey,Goldenrod,black,220,-6,60,60.0,12.0,60.0,"weakTiles"); makeCube("tile14",SkyBlue,Gold,points,DimGrey,Goldenrod,black,220,-6,120,60.0,12.0,60.0,"weakTiles"); makeCube("tile15",blue,Gold,points,DimGrey,Goldenrod,black,220,-6,180,60.0,12.0,60.0,"weakTiles"); makeCube("tile16",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,180,60.0,12.0,60.0,"weakTiles"); makeCube("tile17",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,240,60.0,12.0,60.0,"weakTiles"); makeCube("tile18",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,300,60.0,12.0,60.0,"weakTiles"); makeCube("tile19",SkyBlue,Gold,points,DimGrey,Goldenrod,black,220,-6,240,60.0,12.0,60.0,"weakTiles"); makeCube("tile66",SkyBlue,Gold,points,DimGrey,Goldenrod,black,100,-6,-120,60.0,12.0,60.0,"weakTiles"); makeCube("tile67",blue,Gold,points,DimGrey,Goldenrod,black,160,-6,-120,60.0,12.0,60.0,"weakTiles"); makeCube("tile68",blue,Gold,points,DimGrey,Goldenrod,black,100,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile69",SkyBlue,Gold,points,DimGrey,Goldenrod,black,160,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile70",SkyBlue,Gold,points,DimGrey,Goldenrod,black,40,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile71",blue,Gold,points,DimGrey,Goldenrod,black,-20,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile72",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-80,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile73",blue,Gold,points,DimGrey,Goldenrod,black,-140,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile74",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-200,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile75",blue,Gold,points,DimGrey,Goldenrod,black,-260,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile76",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-260,-6,-120,60.0,12.0,60.0,"weakTiles"); makeCube("tile77",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile78",blue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-120,60.0,12.0,60.0,"weakTiles"); makeCube("tile79",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-320,-6,-60,60.0,12.0,60.0,"weakTiles"); makeCube("tile80",blue,Gold,points,DimGrey,Goldenrod,black,-380,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile81",blue,Gold,points,DimGrey,Goldenrod,black,-380,-6,-60,60.0,12.0,60.0,"weakTiles"); makeCube("tile82",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-180,60.0,12.0,60.0,"weakTiles"); makeCube("tile83",blue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-120,60.0,12.0,60.0,"weakTiles"); makeCube("tile84",SkyBlue,Gold,points,DimGrey,Goldenrod,black,-440,-6,-60,60.0,12.0,60.0,"weakTiles"); block["block"].x_change =160.0; block["block"].y_change= 60.0; block["block"].z_change= 300.0; programID = LoadShaders( "vertexShader.vert", "fragmentShader.frag" ); // Get a handle for our "MVP" uniform Matrices.MatrixID = glGetUniformLocation(programID, "MVP"); reshapeWindow (window, width, height); // Background colour of the scene glClearColor (0.3f, 0.3f, 0.3f, 0.0f); // R, G, B, A glClearDepth (1.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); cout << "VENDOR: " << glGetString(GL_VENDOR) << endl; cout << "RENDERER: " << glGetString(GL_RENDERER) << endl; cout << "VERSION: " << glGetString(GL_VERSION) << endl; cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } int main (int argc, char** argv) { int width = 1200; int height = 900; GLFWwindow* window = initGLFW(width, height); initGL (window, width, height); initializeAudio(); double last_update_time = glfwGetTime(), current_time; // Draw in loop while (!glfwWindowShouldClose(window)) { playAudio(); // OpenGL Draw commands draw(window, width, height); // Swap Frame Buffer in double buffering glfwSwapBuffers(window); // Poll for Keyboard and mouse events glfwPollEvents(); // Control based on time current_time = glfwGetTime(); // Time in seconds if ((current_time - last_update_time) >= 1){ // atleast 0.5s elapsed since last frame seconds ++; last_update_time = current_time; } } clearAudio(); glfwTerminate(); exit(EXIT_SUCCESS); }
[ "abhishek3ic@gmail.com" ]
abhishek3ic@gmail.com
39ca42dc59409ef7d847463aa69e3da582023c47
598cea31abe28eb3af3816449af7f824e577a527
/XOSSRC/LIBC/w_cpp_c.cpp
bb3479444ebf3f3f19dc652f6f9085076fcb5524
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
public-domain/openxos
8e2b5d1c494edb15cb1a8983e653e338fb6e8d7a
d44ad07e99bb9ecf3d8e4ae3898b43a6e339502d
refs/heads/master
2021-02-09T01:16:59.383983
2020-03-01T20:49:03
2020-03-01T20:49:03
244,221,383
4
1
null
null
null
null
UTF-8
C++
false
false
6,434
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> // // Debug level // 0 None // 1 Log fatal errors/potential problems... // 2 Log warnings // ... // 7 Log all - Verbose // #define CFG_DEBUG 1 #if (CFG_DEBUG > 0) # pragma off (unreferenced); extern "C" FILE * g_fileLog; #endif #define MAX_NEW 1000 int g_fNewInit = 0; void * g_anew[MAX_NEW]; // // // void ** _findNew( void * pVoid ) { int n; for( n = 0; n < MAX_NEW; n++ ) { if( pVoid == g_anew[n] ) return( &g_anew[n] ); } return( 0 ); } // // // void _addNew( void * pVoid ) { if( !g_fNewInit ) { memset( g_anew, 0x00, sizeof(g_anew) ); g_fNewInit = 1; } // // Check if already exists // void ** pp = _findNew( pVoid ); if( pp ) { #if (CFG_DEBUG >= 2) fprintf( g_fileLog, "? _addNew(%08X) exists!\n", (int)pVoid ); #endif return; } // // Find a free slot // pp = _findNew( 0 ); if( !pp ) { #if (CFG_DEBUG >= 2) fprintf( g_fileLog, "? _addNew(%08X) table full\n", (int)pVoid ); #endif return; } *pp = pVoid; } // // // int _delNew( void * pVoid ) { if( !pVoid ) { // // Null pointer passed // #if (CFG_DEBUG >= 2) fprintf( g_fileLog, "?? _delNew(%08X) NULL PTR! @@@@@@\n", pVoid ); fflush( g_fileLog ); #endif return -1; } void ** pp = _findNew( pVoid ); if( !pp ) { #if (CFG_DEBUG >= 2) fprintf( g_fileLog, "?? _delNew(%08X) not found @@@@@@\n", pVoid ); fflush( g_fileLog ); #endif return -2; } *pp = 0; return 0; } // // // extern "C" void ** _malloc_mhead; extern "C" void ** _malloc_mtail; extern "C" long _malloc_amount; extern "C" void _dumpHeap( ); //@@@ extern "C" void _dumpMem ( void * pMem, long nMax ); void _dumpMem( void * pMem, long nMax ) { uchar * p = (uchar *)pMem; int ixc; if( nMax < 1 ) nMax = 1; if( nMax > 1024 ) nMax = 1024; for( int ix = 0; ix < nMax; ix += 16 ) { int nSize = nMax - ix; if( nSize > 16 ) nSize = 16; for( ixc = 0; ixc < nSize; ixc++ ) { fprintf( g_fileLog, " %02X", p[ix+ixc] ); } while( ixc < 16 ) { fprintf( g_fileLog, " " ); ixc++; } fprintf( g_fileLog, "[ " ); for( ixc = 0; ixc < nSize; ixc++ ) { if( p[ix+ixc] >= 0x20 && p[ix+ixc] < 0x7F ) fprintf( g_fileLog, "%c", p[ix+ixc] ); else fprintf( g_fileLog, "." ); } fprintf( g_fileLog, " ]\n" ); } fprintf( g_fileLog, "\n" ); } void _dumpHeap( ) { #if 0 int n; int nMax; long dwCnt = 0; long dwSize = 0; #endif #if (CFG_DEBUG >= 1) fprintf( g_fileLog, "****** _malloc_mhead = %08X _mtail = %08X ******\n" , (int)(_malloc_mhead) , (int)(_malloc_mtail) ); void ** pp = _malloc_mhead; void ** p_mnext; void ** p_mprev; void ** p_fnext; void ** p_fprev; long dwSize; long dwData; while( pp ) { dwData = (long )(pp[ 0]); // 1st 4 bytes of user data dwSize = (long )(pp[-1]); // Size, # bytes allocated p_fnext = (void **)(pp[-2]); // Get mb_fnext (Free) p_fprev = (void **)(pp[-3]); // Get mb_fprev p_mnext = (void **)(pp[-4]); // Get mb_mnext p_mprev = (void **)(pp[-5]); // Get mb_mprev fprintf( g_fileLog, " [%08X]: size=%8d mnext=%08X mprev=%08X fnext=%08X fprev=%08X data=%08X\n" , (int)pp , dwSize , (int)(p_mnext) , (int)(p_mprev) , (int)(p_fnext) , (int)(p_fprev) , dwData ); _dumpMem( pp, (dwSize > 64) ? 64 : dwSize ); fflush( g_fileLog ); if( (int)p_mnext == -1 ) break; //??? pp = p_mnext; } if( _malloc_mtail ) fprintf( g_fileLog, "\n *mtail = %08X ???\n", (int)(*_malloc_mtail) ); fprintf( g_fileLog, " amount = %8u\n", _malloc_amount ); #endif } // // // void _dumpNew( ) { #if (CFG_DEBUG > 0) int n; int nMax; long dwCnt = 0; long dwSize = 0; for( n = 0; n < MAX_NEW; n++ ) { if( g_anew[n] ) { unsigned char * p = (unsigned char *)g_anew[n]; long * pdwLen = (long *)(p - 4); dwCnt++; dwSize += *pdwLen; fprintf( g_fileLog, "@@@ _dumpNew: mem[%3d]=%08X Len=%5d\n" , n, (int)(g_anew[n]), *pdwLen ); nMax = *pdwLen; #if 0 if( nMax < 1 ) nMax = 1; if( nMax > 1024 ) nMax = 1024; for( int ix = 0; ix < nMax; ix++ ) { fprintf( g_fileLog, " %02X", p[ix] ); if( (ix & 0x0F) == 0x0F ) fprintf( g_fileLog, "\n" ); } fprintf( g_fileLog, "\n\n" ); #endif _dumpMem( p, nMax ); } } fprintf( g_fileLog, "****** %u Bytes in %u blocks NOT deleted\n" , dwSize, dwCnt ); _dumpHeap( ); #endif } // // Desc: // This replaces the default 'global' operator new. This is required // for native XOS projects. This should eventually be moved to a system // library... // void * operator new( size_t nSize ) { if( nSize == 0 ) { // // Allocating 0 bytes!!! // // Allocate at least (nnn 1?) // nSize++; } void * pVoid = (void *)malloc(nSize); //@@@ Check for allocation errors. //@@@ See new_handler( ) definition in C++ manual. #if 1 if( pVoid ) { //# memset( pVoid, 0xEE, nSize ); //@@@ Debugging memset( pVoid, 0x00, nSize ); //@@@ Debugging } #endif #if (CFG_DEBUG > 1) fprintf( g_fileLog, " *** new (%5d) -> %08X ***\n", nSize, (int)pVoid ); #endif _addNew( pVoid ); return pVoid; } // // // void * operator new( size_t nSize, void * pVoid ) { #if (CFG_DEBUG > 1) fprintf( g_fileLog, " *** new@ (%5d) -> %08X ***\n", nSize, (int)pVoid ); #endif return( pVoid ); } // // // void * operator new []( int unsigned nSize ) { #if (CFG_DEBUG > 1) fprintf( g_fileLog, " *** new[](%d) ***\n", nSize ); #endif return operator new( nSize ); } // // // void operator delete( void * pVoid ) { long dwSize = pVoid ? ((long *)pVoid)[-1] : -2; #if (CFG_DEBUG > 1) fprintf( g_fileLog, " *** delete (%08X) size=%8d ***\n", (int)pVoid, dwSize ); #endif if( _delNew( pVoid ) == 0 ) free( pVoid ); } #if (CFG_DEBUG >= 7) extern "C" void breakpnt( void ); //@@@ Create a debug module for LIBC... void breakpnt( void ) { } #endif void operator delete []( void * pVoid ) { fprintf( g_fileLog, " *** delete[](%08X) ***\n", (int)pVoid ); if( _delNew( pVoid ) == 0 ) free( pVoid ); #if (CFG_DEBUG >= 7) breakpnt( ); #endif }
[ "jean-marc.lienher@bluewin.ch" ]
jean-marc.lienher@bluewin.ch
03a375ec4690c6057ea4066739777c994af71048
1a9cb0f26cd23c424f3c17490b3d140171b945b8
/src/compat/strnlen.cpp
f58598cbcb8893008d56569336901d5140b259e4
[ "MIT" ]
permissive
bitcointokenbtct/Bitcoin-Token-Core
511bf393d61d8b806b6a1569dae39deb4d01c1d8
299e4d8d6665f9b182f37cb0f05f3bca996bf311
refs/heads/master
2022-03-03T12:59:47.410391
2022-02-05T02:20:02
2022-02-05T02:20:02
217,643,469
10
16
MIT
2021-12-14T04:50:33
2019-10-26T02:13:07
C++
UTF-8
C++
false
false
509
cpp
// Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/btct-config.h" #endif #include <cstring> #if HAVE_DECL_STRNLEN == 0 size_t strnlen( const char *start, size_t max_len) { const char *end = (const char *)memchr(start, '\0', max_len); return end ? (size_t)(end - start) : max_len; } #endif // HAVE_DECL_STRNLEN
[ "cryptojoehodler@gmail.com" ]
cryptojoehodler@gmail.com
47eaa75b0db5658295c916f664b236ad32ec2556
88606208382741033f54781fdc52f534014a7383
/NetVSF/app/testVSFClient/testVSFClient/libJpeg.h
9605ab9ee3cdcf26b3dcc3c9f9b78759e20631e0
[]
no_license
noahliaoavlink/NetVSF
693f9379908d3e4d485edb885e0650194c2e9d71
a549bcfd35aa7f64275d401e27d5ad0a74b89912
refs/heads/master
2021-01-07T18:16:27.024068
2020-02-20T03:58:00
2020-02-20T03:58:00
241,779,496
0
0
null
null
null
null
UTF-8
C++
false
false
599
h
#pragma once #ifndef _libJpeg_H_ #define _libJpeg_H_ #include "..\\..\\..\\lib\\jpegsr9c\jpeg-9c\\jpeglib.h" class libJpeg { protected: public: libJpeg(); ~libJpeg(); int Encode(unsigned char* pInBuf, unsigned char** pOutBuf, int iWidth, int iHeight, int iQuality); int Decode(unsigned char* pInBuf, unsigned char* pOutBuf, int iInLen,int* w, int* h, int* iOutLen); int WriteJPEGFile(char* szOutFileName, int iQuality, unsigned char* pInputBuf, int iWidth, int iHeight); int ReadJPEGFile(char* szInFileName, unsigned char* pOutBuf, int* w, int* h, int* iBytes); void Test(); }; #endif
[ "noah.liao@cctch.com.tw" ]
noah.liao@cctch.com.tw
83c0f0ff281283e70ba23f98c0cb8e45b402638d
b45b27637c8e28e82e95111d3dbf455aa772d7b3
/bin/Reapr_1.0.18/third_party/cmake/Source/cmTest.cxx
502c1740d2d508b06489da14165e552dba9cc3f9
[ "BSD-3-Clause", "GPL-3.0-only" ]
permissive
Fu-Yilei/VALET
caa5e1cad5188cbb94418ad843ea32791e50974b
8741d984056d499af2fd3585467067d1729c73c4
refs/heads/master
2020-08-09T12:17:34.989915
2019-10-10T05:10:12
2019-10-10T05:10:12
214,085,217
1
0
MIT
2019-10-10T04:18:34
2019-10-10T04:18:34
null
UTF-8
C++
false
false
7,411
cxx
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "cmTest.h" #include "cmSystemTools.h" #include "cmake.h" #include "cmMakefile.h" //---------------------------------------------------------------------------- cmTest::cmTest(cmMakefile* mf) { this->Makefile = mf; this->OldStyle = true; this->Properties.SetCMakeInstance(mf->GetCMakeInstance()); this->Backtrace = new cmListFileBacktrace; this->Makefile->GetBacktrace(*this->Backtrace); } //---------------------------------------------------------------------------- cmTest::~cmTest() { delete this->Backtrace; } //---------------------------------------------------------------------------- cmListFileBacktrace const& cmTest::GetBacktrace() const { return *this->Backtrace; } //---------------------------------------------------------------------------- void cmTest::SetName(const char* name) { if ( !name ) { name = ""; } this->Name = name; } //---------------------------------------------------------------------------- void cmTest::SetCommand(std::vector<std::string> const& command) { this->Command = command; } //---------------------------------------------------------------------------- const char *cmTest::GetProperty(const char* prop) const { bool chain = false; const char *retVal = this->Properties.GetPropertyValue(prop, cmProperty::TEST, chain); if (chain) { return this->Makefile->GetProperty(prop,cmProperty::TEST); } return retVal; } //---------------------------------------------------------------------------- bool cmTest::GetPropertyAsBool(const char* prop) const { return cmSystemTools::IsOn(this->GetProperty(prop)); } //---------------------------------------------------------------------------- void cmTest::SetProperty(const char* prop, const char* value) { if (!prop) { return; } this->Properties.SetProperty(prop, value, cmProperty::TEST); } //---------------------------------------------------------------------------- void cmTest::AppendProperty(const char* prop, const char* value, bool asString) { if (!prop) { return; } this->Properties.AppendProperty(prop, value, cmProperty::TEST, asString); } //---------------------------------------------------------------------------- void cmTest::DefineProperties(cmake *cm) { cm->DefineProperty ("ATTACHED_FILES", cmProperty::TEST, "Attach a list of files to a dashboard submission.", "Set this property to a list of files that will be encoded and " "submitted to the dashboard as an addition to the test result."); cm->DefineProperty ("ATTACHED_FILES_ON_FAIL", cmProperty::TEST, "Attach a list of files to a dashboard submission if the test fails.", "Same as ATTACHED_FILES, but these files will only be included if the " "test does not pass."); cm->DefineProperty ("COST", cmProperty::TEST, "Set this to a floating point value. Tests in a test set will be " "run in descending order of cost.", "This property describes the cost " "of a test. You can explicitly set this value; tests with higher COST " "values will run first."); cm->DefineProperty ("DEPENDS", cmProperty::TEST, "Specifies that this test should only be run after the specified " "list of tests.", "Set this to a list of tests that must finish before this test is run."); cm->DefineProperty ("ENVIRONMENT", cmProperty::TEST, "Specify environment variables that should be defined for running " "a test.", "If set to a list of environment variables and values of the form " "MYVAR=value those environment variables will be defined while " "running the test. The environment is restored to its previous state " "after the test is done."); cm->DefineProperty ("FAIL_REGULAR_EXPRESSION", cmProperty::TEST, "If the output matches this regular expression the test will fail.", "If set, if the output matches one of " "specified regular expressions, the test will fail." "For example: PASS_REGULAR_EXPRESSION \"[^a-z]Error;ERROR;Failed\""); cm->DefineProperty ("LABELS", cmProperty::TEST, "Specify a list of text labels associated with a test.", "The list is reported in dashboard submissions."); cm->DefineProperty ("RESOURCE_LOCK", cmProperty::TEST, "Specify a list of resources that are locked by this test.", "If multiple tests specify the same resource lock, they are guaranteed " "not to run concurrently."); cm->DefineProperty ("MEASUREMENT", cmProperty::TEST, "Specify a CDASH measurement and value to be reported for a test.", "If set to a name then that name will be reported to CDASH as a " "named measurement with a value of 1. You may also specify a value " "by setting MEASUREMENT to \"measurement=value\"."); cm->DefineProperty ("PASS_REGULAR_EXPRESSION", cmProperty::TEST, "The output must match this regular expression for the test to pass.", "If set, the test output will be checked " "against the specified regular expressions and at least one of the" " regular expressions has to match, otherwise the test will fail."); cm->DefineProperty ("PROCESSORS", cmProperty::TEST, "How many process slots this test requires", "Denotes the number of processors that this test will require. This is " "typically used for MPI tests, and should be used in conjunction with " "the ctest_test PARALLEL_LEVEL option."); cm->DefineProperty ("REQUIRED_FILES", cmProperty::TEST, "List of files required to run the test.", "If set to a list of files, the test will not be run unless all of the " "files exist."); cm->DefineProperty ("RUN_SERIAL", cmProperty::TEST, "Do not run this test in parallel with any other test.", "Use this option in conjunction with the ctest_test PARALLEL_LEVEL " "option to specify that this test should not be run in parallel with " "any other tests."); cm->DefineProperty ("TIMEOUT", cmProperty::TEST, "How many seconds to allow for this test.", "This property if set will limit a test to not take more than " "the specified number of seconds to run. If it exceeds that the " "test process will be killed and ctest will move to the next test. " "This setting takes precedence over " "CTEST_TESTING_TIMEOUT."); cm->DefineProperty ("WILL_FAIL", cmProperty::TEST, "If set to true, this will invert the pass/fail flag of the test.", "This property can be used for tests that are expected to fail and " "return a non zero return code."); cm->DefineProperty ("WORKING_DIRECTORY", cmProperty::TEST, "The directory from which the test executable will be called.", "If this is not set it is called from the directory the test executable " "is located in."); }
[ "yf20@gho.cs.rice.edu" ]
yf20@gho.cs.rice.edu
2fa8472b300448a8b100959854128fd363f2b932
1eef2f3fcdb5995041a23164b0e1fa7e7af632f4
/src/smt/theory_array_bapa.cpp
7b7f93f026124bc064adb16f45ef9501711270ce
[ "MIT" ]
permissive
mtrberzi/z3
d4a80fae4542b69a85b540677aeeabe84d78ce55
b658934bd8bd87f8e6dc9c117d9fda061dad2fd9
refs/heads/master
2021-07-18T16:48:56.368810
2021-04-20T17:16:44
2021-04-20T17:16:44
41,640,176
1
6
NOASSERTION
2021-03-02T18:01:53
2015-08-30T19:20:55
C++
UTF-8
C++
false
false
24,048
cpp
/*++ Copyright (c) 2019 Microsoft Corporation Module Name: theory_array_bapa.cpp Abstract: Saturation procedure for BAPA predicates. Assume there is a predicate Size(S, n) for S : Array(T, Bool) and n : Int The predicate is true if S is a set of size n. Size(S, n), Size(T, m) S, T are intersecting. n != m or S != T D --------------------------------------------------------- Size(S, n) => Size(S\T, k1), Size(S n T, k2), n = k1 + k2 Size(T, m) => Size(T\S, k3), SIze(S n T, k2), m = k2 + k3 Size(S, n) P -------------------- Size(S, n) => n >= 0 Size(S, n), is infinite domain B ------------------------------ Size(S, n) => default(S) = false Size(S, n), Size(S, m) F -------------------------------- Size(S, n), Size(S, m) => n = m Fixing values during final check: Size(S, n) V ------------------- assume value(n) = n Size(S, n), S[i1], ..., S[ik] O ------------------------------- ~distinct(i1, ... ik) or n >= k Size(S,n) Ak -------------------------------------------------- S[i1] & .. & S[ik] & distinct(i1, .., ik) or n < k Q: Is this sufficient? Axiom A1 could be adjusted to add new elements i' until there are k witnesses for Size(S, k). This is quite bad when k is very large. Instead rely on stably infiniteness or other domain properties of the theories. When A is finite domain, or there are quantifiers there could be constraints that force domain sizes so domain sizes may have to be enforced. A succinct way would be through domain comprehension assertions. Finite domains: Size(S, n), is finite domain ---------------------------- S <= |A| Size(S, n), !S[i1], .... !S[ik], S is finite domain ---------------------------------------------------------- default(S) = false or ~distinct(i1,..,ik) or |A| - k <= n ~Size(S, m) is negative on all occurrences, S is finite domain --------------------------------------------------------------- Size(S, n) n fresh. Model construction for infinite domains when all Size(S, m) are negative for S. Author: Nikolaj Bjorner 2019-04-13 Revision History: */ #include "ast/ast_util.h" #include "ast/ast_pp.h" #include "ast/rewriter/array_rewriter.h" #include "smt/smt_context.h" #include "smt/smt_arith_value.h" #include "smt/theory_array_full.h" #include "smt/theory_array_bapa.h" #if 0 - set of native select terms that are true - set of auxiliary select terms. - n1, n2, n3, n4. - a1, a2, a3, a4, a5. - - add select terms, such that first #endif namespace smt { class theory_array_bapa::imp { struct sz_info { bool m_is_leaf; // has it been split into disjoint subsets already? rational m_size; // set to >= integer if fixed in final check, otherwise -1 obj_map<enode, expr*> m_selects; sz_info(): m_is_leaf(true), m_size(rational::minus_one()) {} }; typedef std::pair<func_decl*, func_decl*> func_decls; ast_manager& m; theory_array_full& th; arith_util m_arith; array_util m_autil; th_rewriter m_rw; arith_value m_arith_value; ast_ref_vector m_pinned; obj_map<app, sz_info*> m_sizeof; obj_map<expr, rational> m_size_limit; obj_map<sort, func_decls> m_index_skolems; obj_map<sort, func_decl*> m_size_limit_sort2skolems; unsigned m_max_set_enumeration; context& ctx() { return th.get_context(); } void reset() { for (auto& kv : m_sizeof) { dealloc(kv.m_value); } } bool is_true(expr* e) { return is_true(ctx().get_literal(e)); } bool is_true(enode* e) { return is_true(e->get_expr()); } bool is_true(literal l) { return ctx().is_relevant(l) && ctx().get_assignment(l) == l_true; } bool is_leaf(sz_info& i) const { return i.m_is_leaf; } bool is_leaf(sz_info* i) const { return is_leaf(*i); } enode* get_root(expr* e) { return ctx().get_enode(e)->get_root(); } bool is_select(enode* n) { return th.is_select(n); } app_ref mk_select(expr* a, expr* i) { expr* args[2] = { a, i }; return app_ref(m_autil.mk_select(2, args), m); } literal get_literal(expr* e) { return ctx().get_literal(e); } literal mk_literal(expr* e) { expr_ref _e(e, m); if (!ctx().e_internalized(e)) ctx().internalize(e, false); literal lit = get_literal(e); ctx().mark_as_relevant(lit); return lit; } literal mk_eq(expr* a, expr* b) { expr_ref _a(a, m), _b(b, m); literal lit = th.mk_eq(a, b, false); ctx().mark_as_relevant(lit); return lit; } void mk_th_axiom(literal l1, literal l2) { literal lits[2] = { l1, l2 }; mk_th_axiom(2, lits); } void mk_th_axiom(literal l1, literal l2, literal l3) { literal lits[3] = { l1, l2, l3 }; mk_th_axiom(3, lits); } void mk_th_axiom(unsigned n, literal* lits) { TRACE("card", ctx().display_literals_verbose(tout, n, lits) << "\n";); IF_VERBOSE(10, ctx().display_literals_verbose(verbose_stream(), n, lits) << "\n"); ctx().mk_th_axiom(th.get_id(), n, lits); } void update_indices() { for (auto const& kv : m_sizeof) { app* k = kv.m_key; sz_info& v = *kv.m_value; v.m_selects.reset(); if (is_true(k) && is_leaf(v)) { enode* set = get_root(k->get_arg(0)); for (enode* parent : enode::parents(set)) { if (is_select(parent) && parent->get_arg(0)->get_root() == set) { if (is_true(parent)) { v.m_selects.insert(parent->get_arg(1)->get_root(), parent->get_expr()); } } } } } } /** F: Size(S, k1) & Size(S, k2) => k1 = k2 */ lbool ensure_functional() { lbool result = l_true; obj_map<enode, app*> parents; for (auto const& kv : m_sizeof) { app* sz1 = kv.m_key; if (!is_true(sz1)) { continue; } enode* r = get_root(sz1->get_arg(0)); app* sz2 = nullptr; if (parents.find(r, sz2)) { expr* k1 = sz1->get_arg(1); expr* k2 = sz2->get_arg(1); if (get_root(k1) != get_root(k2)) { mk_th_axiom(~get_literal(sz1), ~get_literal(sz2), mk_eq(k1, k2)); result = l_false; } } else { parents.insert(r, sz1); } } return result; } /** Enforce D */ lbool ensure_disjoint() { auto i = m_sizeof.begin(), end = m_sizeof.end(); for (; i != end; ++i) { auto& kv = *i; if (!kv.m_value->m_is_leaf) { continue; } for (auto j = i; ++j != end; ) { if (j->m_value->m_is_leaf && !ensure_disjoint(i->m_key, j->m_key)) { return l_false; } } } return l_true; } bool ensure_disjoint(app* sz1, app* sz2) { sz_info& i1 = *m_sizeof[sz1]; sz_info& i2 = *m_sizeof[sz2]; SASSERT(i1.m_is_leaf); SASSERT(i2.m_is_leaf); expr* s = sz1->get_arg(0); expr* t = sz2->get_arg(0); if (s->get_sort() != t->get_sort()) { return true; } enode* r1 = get_root(s); enode* r2 = get_root(t); if (r1 == r2) { return true; } if (!ctx().is_diseq(r1, r2) && ctx().assume_eq(r1, r2)) { return false; } if (do_intersect(i1.m_selects, i2.m_selects)) { add_disjoint(sz1, sz2); return false; } return true; } bool do_intersect(obj_map<enode, expr*> const& s, obj_map<enode, expr*> const& t) const { if (s.size() > t.size()) { return do_intersect(t, s); } for (auto const& idx : s) if (t.contains(idx.m_key)) return true; return false; } void add_disjoint(app* sz1, app* sz2) { sz_info& i1 = *m_sizeof[sz1]; sz_info& i2 = *m_sizeof[sz2]; SASSERT(i1.m_is_leaf); SASSERT(i2.m_is_leaf); expr* t = sz1->get_arg(0); expr* s = sz2->get_arg(0); expr_ref tms = mk_subtract(t, s); expr_ref smt = mk_subtract(s, t); expr_ref tns = mk_intersect(t, s); #if 0 std::cout << tms << "\n"; std::cout << smt << "\n"; std::cout << tns << "\n"; #endif if (tns == sz1) { std::cout << "SEEN " << tms << "\n"; } if (tns == sz2) { std::cout << "SEEN " << smt << "\n"; } ctx().push_trail(value_trail<bool>(i1.m_is_leaf, false)); ctx().push_trail(value_trail<bool>(i2.m_is_leaf, false)); expr_ref k1(m), k2(m), k3(m); expr_ref sz_tms(m), sz_tns(m), sz_smt(m); k1 = m_autil.mk_card(tms); k2 = m_autil.mk_card(tns); k3 = m_autil.mk_card(smt); sz_tms = m_autil.mk_has_size(tms, k1); sz_tns = m_autil.mk_has_size(tns, k2); sz_smt = m_autil.mk_has_size(smt, k3); propagate(sz1, sz_tms); propagate(sz1, sz_tns); propagate(sz2, sz_smt); propagate(sz2, sz_tns); propagate(sz1, mk_eq(k1 + k2, sz1->get_arg(1))); propagate(sz2, mk_eq(k3 + k2, sz2->get_arg(1))); } expr_ref mk_subtract(expr* t, expr* s) { expr_ref d(m_autil.mk_setminus(t, s), m); m_rw(d); return d; } expr_ref mk_intersect(expr* t, expr* s) { expr_ref i(m_autil.mk_intersection(t, s), m); m_rw(i); return i; } void propagate(expr* assumption, expr* conseq) { propagate(assumption, mk_literal(conseq)); } void propagate(expr* assumption, literal conseq) { mk_th_axiom(~mk_literal(assumption), conseq); } /** Enforce V */ lbool ensure_values_assigned() { lbool result = l_true; for (auto const& kv : m_sizeof) { app* k = kv.m_key; sz_info& i = *kv.m_value; if (is_leaf(&i)) { rational value; expr* sz = k->get_arg(1); if (!m_arith_value.get_value(sz, value)) { return l_undef; } literal lit = mk_eq(sz, m_arith.mk_int(value)); if (lit != true_literal && is_true(lit)) { ctx().push_trail(value_trail<rational>(i.m_size, value)); continue; } ctx().set_true_first_flag(lit.var()); result = l_false; } } return result; } /** Enforce Ak, */ lbool ensure_non_empty() { for (auto const& kv : m_sizeof) { sz_info& i = *kv.m_value; app* set_sz = kv.m_key; if (is_true(set_sz) && is_leaf(i) && i.m_selects.size() < i.m_size) { expr* set = set_sz->get_arg(0); expr_ref le(m_arith.mk_le(set_sz->get_arg(1), m_arith.mk_int(0)), m); literal le_lit = mk_literal(le); literal sz_lit = mk_literal(set_sz); for (unsigned k = i.m_selects.size(); rational(k) < i.m_size; ++k) { expr_ref idx = mk_index_skolem(set_sz, set, k); app_ref sel(mk_select(set, idx), m); mk_th_axiom(~sz_lit, le_lit, mk_literal(sel)); TRACE("card", tout << idx << " " << sel << " " << i.m_size << "\n";); } return l_false; } } return l_true; } // create skolem function that is injective on integers (ensures uniqueness). expr_ref mk_index_skolem(app* sz, expr* a, unsigned n) { func_decls fg; sort* s = a->get_sort(); if (!m_index_skolems.find(s, fg)) { sort* idx_sort = get_array_domain(s, 0); sort* dom1[2] = { s, m_arith.mk_int() }; sort* dom2[1] = { idx_sort }; func_decl* f = m.mk_fresh_func_decl("to-index", "", 2, dom1, idx_sort); func_decl* g = m.mk_fresh_func_decl("from-index", "", 1, dom2, m_arith.mk_int()); fg = std::make_pair(f, g); m_index_skolems.insert(s, fg); m_pinned.push_back(f); m_pinned.push_back(g); m_pinned.push_back(s); } expr_ref nV(m_arith.mk_int(n), m); expr_ref result(m.mk_app(fg.first, a, nV), m); expr_ref le(m_arith.mk_le(sz->get_arg(1), nV), m); expr_ref fr(m.mk_app(fg.second, result), m); // set-has-size(a, k) => k <= n or g(f(a,n)) = n mk_th_axiom(~mk_literal(sz), mk_literal(le), mk_eq(nV, fr)); return result; } /** Enforce O */ lbool ensure_no_overflow() { for (auto const& kv : m_sizeof) { if (is_true(kv.m_key) && is_leaf(kv.m_value)) { lbool r = ensure_no_overflow(kv.m_key, *kv.m_value); if (r != l_true) return r; } } return l_true; } lbool ensure_no_overflow(app* sz, sz_info& info) { SASSERT(!info.m_size.is_neg()); if (info.m_size < info.m_selects.size()) { for (auto i = info.m_selects.begin(), e = info.m_selects.end(); i != e; ++i) { for (auto j = i; ++j != e; ) { if (ctx().assume_eq(i->m_key, j->m_key)) { return l_false; } } } // if all is exhausted, then add axiom: set-has-size(s, n) & s[indices] & all-diff(indices) => n >= |indices| literal_vector lits; lits.push_back(~mk_literal(sz)); for (auto const& kv : info.m_selects) { lits.push_back(~mk_literal(kv.m_value)); } if (info.m_selects.size() > 1) { ptr_vector<expr> args; for (auto const& kv : info.m_selects) { args.push_back(kv.m_key->get_expr()); } if (info.m_selects.size() == 2) { lits.push_back(mk_eq(args[0], args[1])); } else { expr_ref diff(m.mk_distinct_expanded(args.size(), args.data()), m); lits.push_back(~mk_literal(diff)); } } expr_ref ge(m_arith.mk_ge(sz->get_arg(1), m_arith.mk_int(info.m_selects.size())), m); lits.push_back(mk_literal(ge)); mk_th_axiom(lits.size(), lits.data()); return l_false; } return l_true; } class remove_sz : public trail { ast_manager& m; obj_map<app, sz_info*> & m_table; app* m_obj; public: remove_sz(ast_manager& m, obj_map<app, sz_info*>& tab, app* t): m(m), m_table(tab), m_obj(t) { } ~remove_sz() override {} void undo() override { m.dec_ref(m_obj); dealloc(m_table[m_obj]); m_table.remove(m_obj); } }; std::ostream& display(std::ostream& out) { for (auto const& kv : m_sizeof) { display(out << mk_pp(kv.m_key, m) << ": ", *kv.m_value); } return out; } std::ostream& display(std::ostream& out, sz_info& sz) { return out << (sz.m_is_leaf ? "leaf": "") << " size: " << sz.m_size << " selects: " << sz.m_selects.size() << "\n"; } public: imp(theory_array_full& th): m(th.get_manager()), th(th), m_arith(m), m_autil(m), m_rw(m), m_arith_value(m), m_pinned(m) { context& ctx = th.get_context(); m_arith_value.init(&ctx); m_max_set_enumeration = 4; } ~imp() { reset(); } void internalize_term(app* term) { if (th.is_set_has_size(term)) { internalize_size(term); } else if (th.is_set_card(term)) { internalize_card(term); } } /** * Size(S, n) => n >= 0, default(S) = false */ void internalize_size(app* term) { SASSERT(ctx().e_internalized(term)); literal lit = mk_literal(term); expr* s = term->get_arg(0); expr* n = term->get_arg(1); mk_th_axiom(~lit, mk_literal(m_arith.mk_ge(n, m_arith.mk_int(0)))); sort_size const& sz = s->get_sort()->get_num_elements(); if (sz.is_infinite()) { mk_th_axiom(~lit, mk_eq(th.mk_default(s), m.mk_false())); } else { warning_msg("correct handling of finite domains is TBD"); // add upper bound on size of set. // add case where default(S) = true, and add negative elements. } m_sizeof.insert(term, alloc(sz_info)); m_size_limit.insert(s, rational(2)); assert_size_limit(s, n); m.inc_ref(term); ctx().push_trail(remove_sz(m, m_sizeof, term)); } /** \brief whenever there is a cardinality function, it includes an axiom that entails the set is finite. */ void internalize_card(app* term) { SASSERT(ctx().e_internalized(term)); app_ref has_size(m_autil.mk_has_size(term->get_arg(0), term), m); literal lit = mk_literal(has_size); ctx().assign(lit, nullptr); } lbool trace_call(char const* msg, lbool r) { if (r != l_true) { IF_VERBOSE(2, verbose_stream() << msg << "\n"); } return r; } final_check_status final_check() { final_check_status st = m_arith_value.final_check(); if (st != FC_DONE) return st; lbool r = trace_call("ensure_functional", ensure_functional()); if (r == l_true) update_indices(); if (r == l_true) r = trace_call("ensure_disjoint", ensure_disjoint()); if (r == l_true) r = trace_call("ensure_values_assigned", ensure_values_assigned()); if (r == l_true) r = trace_call("ensure_non_empty", ensure_non_empty()); if (r == l_true) r = trace_call("ensure_no_overflow", ensure_no_overflow()); CTRACE("card", r != l_true, display(tout);); switch (r) { case l_true: return FC_DONE; case l_false: return FC_CONTINUE; case l_undef: return FC_GIVEUP; } return FC_GIVEUP; } void init_model() { for (auto const& kv : m_sizeof) { sz_info& i = *kv.m_value; app* sz = kv.m_key; if (is_true(sz) && is_leaf(i) && rational(i.m_selects.size()) != i.m_size) { warning_msg("models for BAPA is TBD"); break; } } } bool should_research(expr_ref_vector & unsat_core) { expr* set, *sz; for (auto & e : unsat_core) { if (is_app(e) && is_size_limit(to_app(e), set, sz)) { inc_size_limit(set, sz); return true; } } return false; } void inc_size_limit(expr* set, expr* sz) { IF_VERBOSE(2, verbose_stream() << "inc value " << mk_pp(set, m) << "\n"); m_size_limit[set] *= rational(2); assert_size_limit(set, sz); } bool is_size_limit(app* e, expr*& set, expr*& sz) { func_decl* d = nullptr; if (e->get_num_args() > 0 && m_size_limit_sort2skolems.find(e->get_arg(0)->get_sort(), d) && d == e->get_decl()) { set = e->get_arg(0); sz = e->get_arg(1); return true; } else { return false; } } // has-size(s,n) & size-limit(s, n, k) => n <= k app_ref mk_size_limit(expr* set, expr* sz) { func_decl* sk = nullptr; sort* s = set->get_sort(); if (!m_size_limit_sort2skolems.find(s, sk)) { sort* dom[3] = { s, m_arith.mk_int(), m_arith.mk_int() }; sk = m.mk_fresh_func_decl("value-limit", "", 3, dom, m.mk_bool_sort()); m_pinned.push_back(sk); m_size_limit_sort2skolems.insert(s, sk); } return app_ref(m.mk_app(sk, set, sz, m_arith.mk_int(m_size_limit[set])), m); } void assert_size_limit(expr* set, expr* sz) { app_ref set_sz(m_autil.mk_has_size(set, sz), m); app_ref lim(m_arith.mk_int(m_size_limit[set]), m); app_ref size_limit = mk_size_limit(set, sz); mk_th_axiom(~mk_literal(set_sz), ~mk_literal(size_limit), mk_literal(m_arith.mk_le(sz, lim))); } void add_theory_assumptions(expr_ref_vector & assumptions) { for (auto const& kv : m_sizeof) { expr* set = kv.m_key->get_arg(0); expr* sz = kv.m_key->get_arg(1); assumptions.push_back(mk_size_limit(set, sz)); } TRACE("card", tout << "ASSUMPTIONS: " << assumptions << "\n";); } }; theory_array_bapa::theory_array_bapa(theory_array_full& th) { m_imp = alloc(imp, th); } theory_array_bapa::~theory_array_bapa() { dealloc(m_imp); } void theory_array_bapa::internalize_term(app* term) { m_imp->internalize_term(term); } final_check_status theory_array_bapa::final_check() { return m_imp->final_check(); } void theory_array_bapa::init_model() { m_imp->init_model(); } bool theory_array_bapa::should_research(expr_ref_vector & unsat_core) { return m_imp->should_research(unsat_core); } void theory_array_bapa::add_theory_assumptions(expr_ref_vector & assumptions) { m_imp->add_theory_assumptions(assumptions); } }
[ "nbjorner@microsoft.com" ]
nbjorner@microsoft.com
b052fec1320e0b312353c2838f4519a2d156c270
78267853bdf554ef7b890b5517a31f0b44605943
/examples/boris/particle_util_impl.hpp
fcff20a298a8c820b14405259f68201042b03acd
[ "MIT", "BSD-2-Clause" ]
permissive
ruthschoebel/PFASST
02128a1a5d6bebce5c4ca8ca8d2f490e5894a873
07cf14071bd753f3d2b70d102a62020c1bff7bc5
refs/heads/development
2020-12-27T21:17:01.459018
2016-02-24T16:16:13
2016-02-24T16:16:13
54,196,139
0
0
null
2016-03-18T11:23:06
2016-03-18T11:23:06
null
UTF-8
C++
false
false
15,671
hpp
#include "particle_util.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <functional> #include <type_traits> using namespace std; #include <pfasst/globals.hpp> #include <pfasst/logging.hpp> namespace pfasst { namespace examples { namespace boris { template<typename precision> inline static vector<precision> cloud_component_factory(const size_t num_particles, const size_t dim) { vector<precision> out(num_particles * dim, precision(0.0)); return out; } template<typename precision> inline static void zero(vector<precision>& data) { std::fill(data.begin(), data.end(), precision(0.0)); } template<typename precision> inline static void zero(shared_ptr<vector<precision>>& data) { zero(*data.get()); } template<typename precision> inline static vector<precision> cross_prod(const vector<precision>& first, const vector<precision>& second) { if (first.size() == 3 && first.size() == second.size()) { vector<precision> result(3, precision(0.0)); cross_prod_1part<precision>(first.cbegin(), second.cbegin(), result.begin()); return result; } else { return cross_prod_npart(first, second); } } template<typename precision> inline static void cross_prod_1part(typename vector<precision>::const_iterator __first, typename vector<precision>::const_iterator __second, typename vector<precision>::iterator __result) { __result[0] = __first[1] * __second[2] - __first[2] * __second[1]; __result[1] = __first[2] * __second[0] - __first[0] * __second[2]; __result[2] = __first[0] * __second[1] - __first[1] * __second[0]; } template<typename precision> inline static vector<precision> cross_prod_npart(const vector<precision>& first, const vector<precision>& second) { assert(first.size() % 3 == 0 && second.size() % 3 == 0); // make sure the particles have 3 spacial dimensions assert(first.size() == second.size() || second.size() == 3); const size_t npart = first.size() / 3; vector<precision> dest(first.size(), precision(0.0)); if (first.size() == second.size()) { for (size_t p = 0; p < npart; ++p) { cross_prod_1part<precision>(first.cbegin() + (p * 3), second.cbegin() + (p * 3), dest.begin() + (p * 3)); } } else if (second.size() == 3) { for (size_t p = 0; p < npart; ++p) { cross_prod_1part<precision>(first.cbegin() + (p * 3), second.cbegin(), dest.begin() + (p * 3)); } } return dest; } template<typename precision> inline static vector<precision> kronecker(const vector<precision>& first, const vector<precision>& second) { const size_t npart = first.size(); const size_t ndim = second.size(); vector<precision> result(npart * ndim, precision(0.0)); for (size_t p = 0; p < npart; ++p) { for (size_t d = 0; d < ndim; ++d) { result[p * ndim + d] = first[p] * second[d]; } } return result; } template<typename precision> inline static vector<precision> cmp_wise_mul(const vector<precision>& first, const vector<precision>& second) { assert(first.size() == second.size()); vector<precision> out(first.size(), precision(0.0)); transform(first.cbegin(), first.cend(), second.cbegin(), out.begin(), std::multiplies<precision>()); return out; } template<typename precision> inline static vector<precision> cmp_wise_div(const vector<precision>& first, const vector<precision>& second) { assert(first.size() == second.size()); vector<precision> out(first.size(), precision(0.0)); transform(first.cbegin(), first.cend(), second.cbegin(), out.begin(), std::divides<precision>()); return out; } template<typename precision> inline static precision max(const vector<precision>& data) { return *max_element(data.cbegin(), data.cend()); } template<typename precision> inline static precision max_abs(const vector<precision>& data) { return fabs(*max_element(data.cbegin(), data.cend(), [](const precision& a, const precision& b) { return fabs(a) < fabs(b); })); } template<typename precision> inline static precision norm_sq(const vector<precision>& data) { auto norm = norm_sq<precision>(data.cbegin(), data.cend()); return norm; } template<typename precision> inline static precision norm_sq(typename vector<precision>::const_iterator __first, typename vector<precision>::const_iterator __second) { return inner_product(__first, __second, __first, precision(0.0)); } template<typename precision> inline static vector<precision> norm_sq_npart(const vector<precision>& data, const size_t npart) { assert(data.size() % npart == 0); const size_t dim = data.size() / npart; vector<precision> norm(npart, precision(0.0)); for (size_t p = 0; p < npart; ++p) { norm[p] = norm_sq<precision>(data.cbegin() + (p * dim), data.cbegin() + ((p+1) * dim)); } return norm; } template<typename precision> inline static precision norm0(const vector<precision>& data) { return norm0<precision>(data.cbegin(), data.cend()); } template<typename precision> inline static precision norm0(typename vector<precision>::const_iterator __first, typename vector<precision>::const_iterator __second) { return sqrt(inner_product(__first, __second, __first, precision(0.0))); } template<typename precision> inline static vector<precision> norm0_npart(const vector<precision>& data, const size_t npart) { assert(data.size() % npart == 0); const size_t dim = data.size() / npart; vector<precision> norm(npart, precision(0.0)); for (size_t p = 0; p < npart; ++p) { norm[p] = norm0<precision>(data.cbegin() + (p * dim), data.cend() + ((p+1) * dim)); } return norm; } //// // OPERATORS: ADD template<typename precision> inline vector<precision> operator+(const vector<precision>& first, const vector<precision>& second) { vector<precision> dest; if (first.size() == second.size()) { dest.resize(first.size()); std::transform(first.cbegin(), first.cend(), second.cbegin(), dest.begin(), std::plus<precision>()); } else if (first.size() % 3 == 0 && second.size() == 3) { dest.resize(first.size()); for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin() + (p * 3), first.cbegin() + ((p+1) * 3), second.cbegin(), dest.begin() + (p * 3), std::plus<precision>()); } } else { // try other way round // ATTENTION! recursion ML_LOG(WARNING, "Commutativity of addition primaly implemented other way round." << " You should switch to avoid unneccessary function calls."); dest = second + first; } return dest; } template<typename precision, typename ValueT> inline vector<precision> operator+(const vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); vector<precision> dest(vec); dest += value; return dest; } template<typename precision, typename ValueT> inline vector<precision> operator+(const ValueT& value, const vector<precision>& vec) { static_assert(is_arithmetic<ValueT>::value, ""); ML_LOG(WARNING, "Commutativity of addition primaly implemented other way round." << " You should switch to avoid unneccessary function calls."); return vec + value; } // OPERATORS: ADD //// //// // OPERATORS: INPLACE-ADD template<typename precision> inline vector<precision>& operator+=(vector<precision>& first, const vector<precision>& second) { if (first.size() == second.size()) { transform(first.cbegin(), first.cend(), second.cbegin(), first.begin(), std::plus<precision>()); } else if (first.size() % 3 == 0 && second.size() == 3) { for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin() + (p * 3), first.cbegin() + ((p+1) * 3), second.cbegin(), first.begin() + (p * 3), std::plus<precision>()); } } else if (first.size() == 3 && second.size() % 3 == 0) { for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin(), first.cend(), second.cbegin() + (p * 3), first.begin(), std::plus<precision>()); } } return first; } template<typename precision, typename ValueT> inline vector<precision>& operator+=(vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); for (auto&& elem : vec) { elem += value; } return vec; } // OPERATORS: INPLACE-ADD //// //// // OPERATORS: MINUS template<typename precision> inline vector<precision> operator-(const vector<precision>& first, const vector<precision>& second) { vector<precision> dest; if (first.size() == second.size()) { dest.resize(first.size()); std::transform(first.cbegin(), first.cend(), second.cbegin(), dest.begin(), std::minus<precision>()); } else if (first.size() % 3 == 0 && second.size() == 3) { dest.resize(first.size()); for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin() + (p * 3), first.cbegin() + ((p+1) * 3), second.cbegin(), dest.begin() + (p * 3), std::minus<precision>()); } } else if (first.size() == 3 && second.size() % 3 == 0) { dest.resize(first.size()); for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin(), first.cend(), second.cbegin() + (p * 3), dest.begin() + (p * 3), std::minus<precision>()); } } return dest; } template<typename precision, typename ValueT> inline vector<precision> operator-(const vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); vector<precision> dest(vec); dest -= value; return dest; } // OPERATORS: MINUS //// //// // OPERATORS: INPLACE-MINUS template<typename precision> inline vector<precision>& operator-=(vector<precision>& first, const vector<precision>& second) { if (first.size() == second.size()) { transform(first.cbegin(), first.cend(), second.cbegin(), first.begin(), std::minus<precision>()); } else if (first.size() % 3 == 0 && second.size() == 3) { for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin() + (p * 3), first.cbegin() + ((p+1) * 3), second.cbegin(), first.begin() + (p * 3), std::minus<precision>()); } } else if (first.size() == 3 && second.size() % 3 == 0) { for (size_t p = 0; p < first.size() / 3; ++p) { std::transform(first.cbegin(), first.cend(), second.cbegin() + (p * 3), first.begin(), std::minus<precision>()); } } return first; } template<typename precision, typename ValueT> inline vector<precision>& operator-=(vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); for (auto&& elem : vec) { elem -= value; } return vec; } // OPERATORS: INPLACE-MINUS //// //// // OPERATORS: MUL template<typename precision, typename ValueT> inline vector<precision> operator*(const vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); vector<precision> dest(vec); dest *= value; return dest; } template<typename precision, typename ValueT> inline vector<precision> operator*(const ValueT& value, const vector<precision>& vec) { static_assert(is_arithmetic<ValueT>::value, ""); ML_LOG(WARNING, "Commutativity of multiplication primaly implemented other way round." << " You should switch to avoid unneccessary function calls."); return vec * value; } template<typename precision> inline vector<precision> operator* (const vector<precision>& vec, const vector<precision>& values) { assert(vec.size() % 3 == 0 && vec.size() / 3 == values.size()); vector<precision> dest(vec.size(), precision(0.0)); for (size_t p = 0; p < values.size(); ++p) { std::transform(vec.cbegin() + (p * 3), vec.cbegin() + ((p+1) * 3), dest.begin() + (p * 3), [&](const precision& v) { return v * values[p]; }); } return dest; } // OPERATORS: MUL //// //// // OPERATORS: INPLACE-MUL template<typename precision, typename ValueT> inline vector<precision>& operator*=(vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); for (auto&& elem : vec) { elem *= value; } return vec; } // OPERATORS: INPLACE-MUL //// //// // OPERATORS: DIV template<typename precision, typename ValueT> inline vector<precision> operator/(const vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); vector<precision> dest(vec); dest /= value; return dest; } template<typename precision> inline vector<precision> operator/ (const vector<precision>& vec, const vector<precision>& values) { assert(vec.size() % 3 == 0 && vec.size() / 3 == values.size()); vector<precision> dest(vec.size(), precision(0.0)); for (size_t p = 0; p < values.size(); ++p) { std::transform(vec.cbegin() + (p * 3), vec.cbegin() + ((p+1) * 3), dest.begin() + (p * 3), [&](const precision& v) { return v / values[p]; }); } return dest; } // OPERATORS: DIV //// //// // OPERATORS: INPLACE-DIV template<typename precision, typename ValueT> inline vector<precision>& operator/=(vector<precision>& vec, const ValueT& value) { static_assert(is_arithmetic<ValueT>::value, ""); for (auto&& elem : vec) { elem /= value; } return vec; } // OPERATORS: INPLACE-DIV //// } // ::pfasst::examples::boris } // ::pfasst::examples } // ::pfasst
[ "t.klatt@fz-juelich.de" ]
t.klatt@fz-juelich.de
2c71f7cbad8c15eade68970cb81b2e38c8473387
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive/29ef16c4a22714b59e634a7d472bef61-f674c1a6d04c632b71a62362c0ccfc51/main.cpp
15374bd1fa7c73c9109a87abf37ce896b9449779
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
#include <stdio.h> #include <stdlib.h> int main (int argc, char** argv, char** envp) { // Affichage. printf("entier %d\n", 2); printf("float/double %.1f\n", 10.532); printf("entier %c\n", 'c'); printf("entier %s\n", "texte"); // Valeur de retour. return EXIT_SUCCESS; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
0ffbeecb9be9ac4a42de621a76cc5fc889821096
4b7096aa2447f227ba3e58a52b383c99c17cad9c
/LDE.cpp
4116c16cf9484f170983fc03f416c37263cc4238
[]
no_license
Rubens-Mendes/Estruturas-de-Dados
cd3ccef81c48032aaf695b5d108c66d5a9fd01c8
fcacc7c146bc2498a2f02c4a5c621d6934827bfa
refs/heads/master
2022-12-30T08:26:30.562393
2020-10-17T06:00:20
2020-10-17T06:00:20
258,989,118
2
0
null
null
null
null
UTF-8
C++
false
false
3,392
cpp
#include <iostream> using namespace std; /** * Uma lista dinâmica encadeada trata-se de uma lista onde os itens * não estão alocados em sequência na memória, mas sim, vários blocos em vários * lugares diferentes da memória. * Portanto, cada item, terá o número e o endereço (duas informações) para o próximo item. * o problema desse tipo de estrutura é o tempo para percorrer as informações, dado que, * para ir à um item específico, será necessário acessar todos anteriores antes dele. */ class No{//Classe nó public: No(int valor){ //Método construtor. this->valor = valor; this->prox = NULL; } int valor; //O valor a ser armazenado a cada item. No* prox; //O endereço do próximo item. }; class LDE{ public: /** * A Classe LDE possuirá somente o endereço do primeiro nó. */ No* primeiro; //Ponteiro para o primeiro nó de toda a lista. int n; //Variavel de controle referente ao tamanho. LDE(){ primeiro = NULL; //Ao iniciar a lista, não existe nenhum item, logo não há apontamento. n = 0; } bool insere(int valor){ No* novo = new No(valor); //Cria um ponteiro para um novo Nó com o determinado valor. :) if(!novo) return false; /** * Nessas linhas define-se o movimento dos endereços. */ No* anterior = NULL; No* proximo = primeiro; while(proximo != NULL && proximo->valor < valor){ anterior = proximo; //Anterior terá o endereço do próximo, mantendo o passo. proximo = proximo->prox; //O próximo campo do item inserido. } //Caso já haja um nó na estrutura, o próximo dele vira o nó novo if(anterior) anterior->prox = novo; //Senão o novo nó é o primeiro. else{ primeiro = novo; } novo->prox = proximo; n++; return true; } //Função para imprimir todos os números da estrutura, inicia o loop pelo primeiro nó void imprime(){ No* temp = primeiro; for(int i=0; i < n; i++){ cout << temp->valor << " "; temp = temp->prox; } } //Função de busca que recebe um inteiro int busca(int valor){ No* temp = primeiro; for(int i=0; i < n; i++) { if (temp->valor == valor) return i; temp = temp->prox; } return -1; } //A remoção é feita recebendo um valor inteiro, após achar o nó, são refeitos os devidos apontamentos bool remove(int valor){ No* proximo = primeiro; No* anterior = NULL; for(int i=0; i < n && proximo->valor != valor; i++) { anterior = proximo; proximo = proximo->prox; } if(!proximo || proximo->valor != valor){ return false; } if(anterior){ anterior->prox = proximo->prox; } else{ primeiro = proximo->prox; } delete[]proximo; n--; return true; } }; int main() { /* Testes cout << "INICIO" << endl; LDE x; x.insere(10); x.insere(3); x.insere(45); x.insere(6); int a = x.busca(45); cout << a << endl; if(x.remove(6)) { x.imprime(); } */ return 0; }
[ "rubens_mendes_87@hotmail.com" ]
rubens_mendes_87@hotmail.com
e6ce30ba70d3a45bee23ee82eb91a7a923dfa56a
e75a30dda2cca5f48dfcf5cc2cb225d5ce657faa
/83_反向投影/83_calcBackProject.cpp
b0c0f16781c5528cbf12c75f4fc3ef74d3d3e261
[]
no_license
justIllusions/easyproject
e2332ffd99436f352a63dbafe61f5f87e6ee0aa7
0c24e62a4822cdd7564b3114614ef10d9d92bbb1
refs/heads/master
2020-03-17T22:50:55.144418
2018-05-19T02:56:11
2018-05-19T02:56:11
134,020,468
0
0
null
null
null
null
GB18030
C++
false
false
5,145
cpp
//--------------------------------------【程序说明】------------------------------------------- // 程序说明:《OpenCV3编程入门》OpenCV2版书本配套示例程序83 // 程序描述:反向投影示例程序 // 开发测试所用操作系统: Windows 7 64bit // 开发测试所用IDE版本:Visual Studio 2010 // 开发测试所用OpenCV版本: 3.0 beta // 2014年11月 Created by @浅墨_毛星云 // 2014年12月 Revised by @浅墨_毛星云 //------------------------------------------------------------------------------------------------ //---------------------------------【头文件、命名空间包含部分】---------------------------- // 描述:包含程序所使用的头文件和命名空间 //------------------------------------------------------------------------------------------------ #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" using namespace cv; //-----------------------------------【宏定义部分】-------------------------------------------- // 描述:定义一些辅助宏 //------------------------------------------------------------------------------------------------ #define WINDOW_NAME1 "【原始图】" //为窗口标题定义的宏 //-----------------------------------【全局变量声明部分】-------------------------------------- // 描述:全局变量声明 //----------------------------------------------------------------------------------------------- Mat g_srcImage; Mat g_hsvImage; Mat g_hueImage; int g_bins = 30;//直方图组距 //-----------------------------------【全局函数声明部分】-------------------------------------- // 描述:全局函数声明 //----------------------------------------------------------------------------------------------- static void ShowHelpText(); void on_BinChange(int, void* ); //--------------------------------------【main( )函数】----------------------------------------- // 描述:控制台应用程序的入口函数,我们的程序从这里开始执行 //----------------------------------------------------------------------------------------------- int main( ) { //【0】改变console字体颜色 //system("color 6F"); //【0】显示帮助文字 //ShowHelpText(); //【1】读取源图像,并转换到 HSV 空间 g_srcImage = imread( "1.jpg", 1 ); //if(!g_srcImage.data ) { printf("读取图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return false; } cvtColor( g_srcImage, g_hsvImage, COLOR_BGR2HSV ); //【2】分离 Hue 色调通道 g_hueImage.create( g_hsvImage.size(), g_hsvImage.depth() ); int ch[ ] = { 0, 0 }; mixChannels( &g_hsvImage, 1, &g_hueImage, 1, ch, 1 ); //【3】创建 Trackbar 来输入bin的数目 namedWindow( WINDOW_NAME1 , WINDOW_AUTOSIZE ); createTrackbar("色调组距 ", WINDOW_NAME1 , &g_bins, 180, on_BinChange ); on_BinChange(0, 0);//进行一次初始化 //【4】显示效果图 imshow( WINDOW_NAME1 , g_srcImage ); // 等待用户按键 waitKey(0); return 0; } //-----------------------------------【on_HoughLines( )函数】-------------------------------- // 描述:响应滑动条移动消息的回调函数 //--------------------------------------------------------------------------------------------- void on_BinChange(int, void* ) { //【1】参数准备 MatND hist; int histSize = MAX( g_bins, 2 ); float hue_range[] = { 0, 180 }; const float* ranges = { hue_range }; //【2】计算直方图并归一化 calcHist( &g_hueImage, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false ); normalize( hist, hist, 0, 255, NORM_MINMAX, -1, Mat() ); //【3】计算反向投影 MatND backproj; calcBackProject( &g_hueImage, 1, 0, hist, backproj, &ranges, 1, true ); //【4】显示反向投影 imshow( "反向投影图", backproj ); //【5】绘制直方图的参数准备 int w = 400; int h = 400; int bin_w = cvRound( (double) w / histSize ); Mat histImg = Mat::zeros( w, h, CV_8UC3 ); imshow("21",histImg); //【6】绘制直方图 for( int i = 0; i < g_bins; i ++ ) { rectangle( histImg, Point( i*bin_w, h ), Point( (i+1)*bin_w, h - cvRound( hist.at<float>(i)*h/255.0 ) ), Scalar( 100, 123, 255 ), -1 ); } //【7】显示直方图窗口 imshow( "直方图", histImg ); } //-----------------------------------【ShowHelpText( )函数】---------------------------------- // 描述:输出一些帮助信息 //---------------------------------------------------------------------------------------------- static void ShowHelpText() { //输出欢迎信息和OpenCV版本 printf("\n\n\t\t\t非常感谢购买《OpenCV3编程入门》一书!\n"); printf("\n\n\t\t\t此为本书OpenCV3版的第83个配套示例程序\n"); printf("\n\n\t\t\t 当前使用的OpenCV版本为:" CV_VERSION ); printf("\n\n ----------------------------------------------------------------------------\n"); //输出一些帮助信息 printf("\n\n\t欢迎来到【反向投影】示例程序\n\n"); printf("\n\t请调整滑动条观察图像效果\n\n"); }
[ "18056515108@163.com" ]
18056515108@163.com
d2c254a237eec825cf11d94a58b7dcbe0bf3fa8a
d2fd75604ee17e188e8684555156fe3bed2b38e3
/mainwindow.h
bcbfae2be16d6f0538ab668eea8a6c2fa01e66f6
[]
no_license
k3nny512/MaeDN
d7d20606d0b1985bba3aecef3864713c661148fe
57e33898cd1f38370185752eff51eea8d949ad67
refs/heads/master
2020-04-12T20:45:35.857900
2018-12-22T17:50:34
2018-12-22T17:50:34
162,746,101
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "controller.h" #include <QMainWindow> #include <QApplication> #include <QCoreApplication> #include <QThread> #include <QKeyEvent> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); Controller controller; private slots: void on_BTConnect_clicked(); void on_BTClose_clicked(); void on_BTRight_clicked(); void on_BTLeft_clicked(); void on_BTMoveTo_clicked(); void on_BTOut_clicked(); void on_BTIn_clicked(); void on_BTUp_clicked(); void on_BTDown_clicked(); void on_BTMagnetClicked_clicked(); void on_BTMagnetOn_clicked(); void on_BTMagnetOff_clicked(); void keyPressEvent(QKeyEvent *event); private: Ui::MainWindow *ui; void TurnCW(uint16_t steps, int16_t speed); void TurnCCW(uint16_t steps, int16_t speed); void rOut(uint16_t steps, int16_t speed); void rIn(uint16_t steps, int16_t speed); void heightUp(uint16_t steps, int16_t speed); void heightDown(uint16_t steps, int16_t speed); void magClick(uint16_t steps, int16_t speed); void magGrab(uint16_t steps, int16_t speed); }; #endif // MAINWINDOW_H
[ "nikolas.boe@googlemail.com" ]
nikolas.boe@googlemail.com
aa617e8929a906e8f03e58692c8d424842c56beb
267c60869063707bbfd3c0d21461668a6e772223
/src/Logger.cpp
8b16e8747785a5a0b6f8c86dc737e379ba09565b
[]
no_license
alexey-dev/cpp_unit_tests_learning
8ff2e791dba656bb8030307578c0cdf99800ca68
0d0a515a90d94a7cafe29a1e24b45232fc3fd5ce
refs/heads/master
2020-08-11T21:09:52.945802
2019-11-04T20:45:18
2019-11-04T20:45:18
214,627,767
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
// // Logger.cpp // TestMockStub // // Created by Alex Usachov on 11/3/19. // Copyright © 2019 Alex Usachov. All rights reserved. // #include "Logger.hpp" void cFileLogger::Message(const std::string & _msg) { //TODO: finish later. }
[ "usachov.alexey.dev@gmail.com" ]
usachov.alexey.dev@gmail.com
a2354822cb05265ed62c6427e8bf39b3e94bb909
e5918111f65b0551261533573b89b80310f800aa
/src/multipanel.h
03bd614750c0eedb2fa56f6ead47f1fc3dc57dfa
[]
no_license
skiselkov/xsaitekpanels
1396f7be1513dc8ad0e5681927be34187492bf15
0af43e84abfed7d2d9a622d2efcc72141cf5e47a
refs/heads/master
2020-04-05T23:03:40.394699
2016-12-05T03:01:13
2016-12-05T03:01:13
67,690,510
3
2
null
2016-09-08T09:49:04
2016-09-08T09:49:02
null
UTF-8
C++
false
false
5,036
h
#ifndef _MULTIPANEL_H_ #define _MULTIPANEL_H_ #include <stdlib.h> #if IBM #include <windows.h> #else /* !IBM */ #include <pthread.h> #endif /* !IBM */ #include <stdint.h> #include "XPLMUtilities.h" #include "XPLMDataAccess.h" #include "hidapi.h" #include "Dataref.h" #include "Command.h" namespace xsaitekpanels { /* * See Multipanel::process_button_common for info on how these button * types behave. */ enum button_type_t { MomentaryPushButton, OneShotButton, ToggleButton, MomentaryPushUpHoldDownButton }; enum button_light_type_t { NoLight = 0, OnOffFlashLight, OnOffFlashLight_dup, OnOffFlash3StateLight }; enum { AP_BTN_INFO = 0, HDG_BTN_INFO, NAV_BTN_INFO, LNAV_BTN_INFO, IAS_BTN_INFO, IAS_CHANGEOVER_BTN_INFO, ALT_BTN_INFO, VS_BTN_INFO, APR_BTN_INFO, REV_BTN_INFO, FLAPS_UP_BTN_INFO, FLAPS_DN_BTN_INFO, NUM_BTN_INFOS }; enum { ALT_SW_INFO = 0, VS_SW_INFO, IAS_SW_INFO, IAS_MACH_SW_INFO, HDG_SW_INFO, CRS_SW_INFO, CRS2_SW_INFO, NUM_SW_INFOS }; enum { STATUS_BITS = 24 }; struct button_info_t { bool press_state; uint64_t press_time, release_time; uint64_t n_fired; button_type_t type; Command *cmd, *rev_cmd; Dataref *dr; double on_value, off_value; double max_value, min_value; }; struct button_light_info_t { button_light_type_t type; Dataref *dr, *flash_dr; }; struct switch_info_t { Dataref *dr; Command *up_cmd, *dn_cmd; double maxval, minval, step; double max_accel, accel; bool loop; }; void *multipanel_reader_thread(void *arg); class Multipanel { unsigned panel_num; hid_device *handle; int display_readout; uint8_t adigits[5], bdigits[5]; int btnleds; double altitude, vs, airspeed, hdg, crs; uint64_t last_auto_update_time; bool knob_last_up, knob_last_dn; int accel_mult, knob_up_dampen, knob_dn_dampen; uint64_t knob_up_time, knob_dn_time; int knob_speed; bool athr_sw_enabled; double athr_sw_enabled_val, athr_sw_disabled_val; Dataref *athr_sw_dr; button_info_t button_info[NUM_BTN_INFOS]; switch_info_t switches[NUM_SW_INFOS]; button_light_info_t button_lights[NUM_BTN_INFOS]; Dataref *ias_is_mach_dr; Command *trim_up_cmd; int trim_wheel_up_dampen; uint64_t trim_up_last; double trim_up_accel, trim_up_max_accel; Command *trim_down_cmd; int trim_wheel_down_dampen; uint64_t trim_down_last; double trim_down_accel, trim_down_max_accel; bool flashon; bool process_light(const button_light_info_t *info, int bitn, bool flash_on); bool process_lights(); void process_switch_adjustment(int value, uint64_t *lastadj_time, Dataref *dr, Command *cmd, double maxval, double minval, double step, bool loop, double accel, int max_accel_mult); void process_switch(const switch_info_t *sw); void update_alt_vs_readout(); void enable_readout(int readout); void nav_light_set_hsi(); void multibuf_button(); void process_alt_switch(); void process_vs_switch(); void process_ias_switch(); void process_hdg_switch(); void process_crs_switch(); void process_autothrottle_switch(); void process_button_common(int button_id, button_info_t *info); void process_trim_wheel(); void process_multi_display(); void process_multi_flash(); void process_drs(); void sched_update_command(); /* this is a private copy of `buttons' used only by the main thread */ int buttons_main[STATUS_BITS]; #if IBM HANDLE mtx; HANDLE reader; #else pthread_mutex_t mtx; pthread_t reader; #endif /* * These are protected by the mutex above, as they're shared between * the main thread and the reader thread. */ uint8_t sendbuf[13]; int buttons[STATUS_BITS]; bool buttons_updated; bool send_cmd, reader_shutdown; void config_cleanup(); public: Multipanel(unsigned panel_number, const char *hidpath); ~Multipanel(); void reconfigure(); void process(); void shutdown(); void reader_main(); }; int get_num_multipanels(); void open_all_multipanels(); void close_all_multipanels(); void reconfigure_all_multipanels(); void process_all_multipanels(); void register_multipanel_drs(); void unregister_multipanel_drs(); } #endif /* _MULTIPANEL_H_ */
[ "skiselkov@gmail.com" ]
skiselkov@gmail.com
f89db21bbb2d765de12eac9db5a3f394ed5300f0
1af8b5589c8f42ac2546d2adffcff887f975a93c
/src/com/fiuba/resto/process/Attendant.h
93e26c96f8fbda40e69448d3ff19da71b4c6ae4f
[]
no_license
juanmanuelromeraferrio/resto-simulation-c-
18009a9cf869a6ac0505ac6e41a00a8d229940ab
a262e5d95442760ce2729e832d2a2c43928fe160
refs/heads/master
2021-01-12T12:52:23.190297
2016-10-20T20:18:30
2016-10-20T20:18:30
69,389,295
0
1
null
null
null
null
UTF-8
C++
false
false
536
h
/* * Attendant.h * * Created on: 24 sep. 2016 * Author: jferrio */ #ifndef ATTENDANT_H_ #define ATTENDANT_H_ #include "../utils/Semaphore.h" #include "../utils/SharedMemory.h" #include "../types/types.h" #include <strings.h> #include "../utils/Fifo.h" class Attendant { private: Fifo* dinersInLivingFifo; Semaphore* freeTableSemaphore; SharedMemory<restaurant_t> sharedMemory; Semaphore* memorySemaphore; void asignTable(); public: Attendant(); virtual ~Attendant(); void run(); }; #endif /* ATTENDANT_H_ */
[ "juanmanuel.romeraferrio@gmail.com" ]
juanmanuel.romeraferrio@gmail.com
533b7eff9eba1dc4a518012fbf7ef28eeff1fd2d
9bc2462106be4df51f31e44e28ea6a78b42a3deb
/2021_04_24/a/src.cpp
47d647e46bf7c8e91fc1296ff1ea5cf1b81fd5be
[]
no_license
ysuzuki19/atcoder
4c8128c8a7c7ed10fc5684b1157ab5513ba9c32e
0fbe0e41953144f24197b4dcd623ff04ef5bc4e4
refs/heads/master
2021-08-14T19:35:45.660024
2021-07-31T13:40:39
2021-07-31T13:40:39
178,597,227
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
cpp
#include <iostream> #include <string> #include <vector> #include <cmath> #include <list> #include <set> #include <map> #include <algorithm> using namespace std; #define debug(var) do{ std::cout << #var << " : "; view(var); }while(0) using ll = long long; using ld = long double; inline int num (const std::string& S, int idx) noexcept { return S.at(idx) - '0'; } inline int ctoi(char c) noexcept { return c - '0'; } inline bool isNumber(char c) noexcept { return ('0'<=c && c<='9'? true : false); } inline int safeCtoi(char c) { if(isNumber(c)) { return ctoi(c); } else { throw 1; } } inline char itoc(int i) noexcept { return i + '0'; } inline unsigned int bitMask(int i) noexcept { return (1 << i); } inline bool isTrue(unsigned int bit, int i) noexcept { return bit & bitMask(i); } inline bool isEven(int num) noexcept { return !num%2; } inline bool isOdd(int num) noexcept { return num%2; } template<typename T> inline short sgn(T num) noexcept { return (num==0? 0 : (num>0? 1 : -1) ); } template<typename T> inline bool isZero(T num) noexcept { return (num==0? true : false); } template<typename T> inline bool isPositive(T num) noexcept { return (num>0? true : false); } template<typename T> inline bool isNegative(T num) noexcept { return (num<0? true : false); } template<typename T> void view(T e) noexcept { cout << e << endl; } template<typename T> void view(std::vector<T> v) noexcept { for(const auto& e : v) cout << e << " "; cout << endl; } template<typename T> void view(std::vector<std::vector<T>> vv) noexcept { for(const auto& v : vv) view(v); } int main(){ cin.tie(0); ios::sync_with_stdio(false); int a, b, c; cin >> a >> b >> c; if (a*a + b*b < c*c) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }
[ "ysuzuki.cpp@gmail.com" ]
ysuzuki.cpp@gmail.com
3d4f8885554e80d3be7fbdd8aa582d98c32abf73
17216697080c5afdd5549aff14f42c39c420d33a
/src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/apps/JAWS/stress_testing/cp.h
bcf50ad2a55d54b588cbb627b05e924265055b7f
[ "MIT" ]
permissive
AI549654033/RDHelp
9c8b0cc196de98bcd81b2ccc4fc352bdc3783159
0f5f9c7d098635c7216713d7137c845c0d999226
refs/heads/master
2022-07-03T16:04:58.026641
2020-05-18T06:04:36
2020-05-18T06:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
260
h
// $Id: cp.h 80826 2008-03-04 14:51:23Z wotte $ #include "util.h" #include "stats.h" class Client_Parameters { public: Client_Parameters(int); URL *url; static Stats *stats; static int tcp_nodelay; static int sockbufsiz; int id; };
[ "jim_xie@trendmicro.com" ]
jim_xie@trendmicro.com
aae759c1e9b61875ffa37476d3371ec5f76eda4a
18bf86ce6c6181edbd5af76c6b6284f88d9d04ec
/src/effects/lineEffect.cpp
9d971948255d1d5150d5da6acb066772b42044ad
[]
no_license
Sleto/karmaMapper
5aa0a85272b7d61956350ce2a3c99e4d5dd8b5db
bc2c6d900423398dac7b20dbd2d2b95d68ecfd97
refs/heads/master
2020-04-08T19:39:47.537334
2015-03-20T21:26:47
2015-03-20T21:26:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,959
cpp
// // lineEffect.cpp // karmaMapper // // Created by Daan de Lange on 12/3/14. // // - - - - // // Parent class for all effects. // Implements some standard methods for overall usage. // #include "lineEffect.h" lineEffect::lineEffect(){ basicEffect::basicEffect(); // effectType must match the class name effectType = "lineEffect"; lines.clear(); /*for(int i=0; i<shapes.size()*5; i++){ lines.push_back( getRandomLine() ); }*/ ofAddListener(ofx::AbletonLiveSet::EventHandler::noteEvent, this, &lineEffect::noteEventListener); } lineEffect::~lineEffect(){ ofRemoveListener(ofx::AbletonLiveSet::EventHandler::noteEvent, this, &lineEffect::noteEventListener); } // update --> animation // overrule this function with your own bool lineEffect::render(){ if( shapes.size()==0 ) return; for(std::list<lineEffectLine>::iterator it=lines.begin(); it!= lines.end(); ++it){ (*it).render(); } } void lineEffect::update(){ // you can chose to do the default behaviour too or not by commenting this out basicEffect::update(); // add lines ? if(lines.size() < shapes.size()*50) lines.push_back( getRandomLine() ); // check for dead lines for(std::list<lineEffectLine>::reverse_iterator it=lines.rbegin(); it!= lines.rend(); it--){ lineEffectLine bla = *it; // replace dead one with new one if( !(*it).isAlive() ) { //*it = getRandomLine(); it++; it= std::list<lineEffectLine>::reverse_iterator( lines.erase( it.base() )); it--; } } } // resets all values // overrule this function with your own. void lineEffect::reset(){ // do everything the basicEffect does basicEffect::reset(); // do other stuff } /*bool lineEffect::grabSomeShapes(){ // clear shapes.clear(); shapes.resize(0); // we just want all vertex shapes //shapes = shapesHandler::getInstance().getShapesByType("vertexShape"); // then sort them by group //map<int, int> groups; // <index, count> //groups.clear(); shapeGroups.clear(); for(int i=0; i<shapes.size(); i++){ int group = shapes[i]->getGroupID(); // create map entry ? if( shapeGroups.find(group) == shapeGroups.end() ){ shapeGroups[group] = vector<int>(); } shapeGroups[group].push_back(i); } }*/ // returns a line from 1 shape vertex to another lineEffectLine lineEffect::getRandomLine( const bool onSameShape){ basicShape* fromShape = shapes[ round( ofRandom(shapes.size()-1) )]; basicShape* toShape; if( onSameShape ) toShape = fromShape; else toShape = shapes[ round( ofRandom(shapes.size()-1) )]; ofVec2f* from; ofVec2f* to; if( fromShape->isType("vertexShape") ){ from = ((vertexShape*) fromShape)->getRandomVertexPtr(); to = ((vertexShape*) toShape)->getRandomVertexPtr(); } else { from = fromShape->getPositionPtr(); to = toShape->getPositionPtr(); } return lineEffectLine( from, to ); } void lineEffect::noteEventListener(ofx::AbletonLiveSet::LSNoteEvent &noteEvent){ //lines.push_back(); }
[ "idaany@gmail.com" ]
idaany@gmail.com
441dc9cf8704e3d4d9bb9057848fbf110e307b7a
01752687e20be48e06a6b863a0036a2524cdf58d
/src/qt/test/test_main.cpp
c9a2e260cda1dd42f899835342468d2f569ea05b
[ "MIT" ]
permissive
BitcoinInterestOfficial/BitcoinInterest
8930042b26665f430ff1ae6e25c86c4998d1349c
9d4eeee6bef0b11ccc569c613daae90d23804b5d
refs/heads/master
2021-06-21T16:48:58.797426
2019-02-01T07:29:49
2019-02-01T07:29:49
115,038,373
30
20
MIT
2019-02-01T02:55:11
2017-12-21T19:10:21
C
UTF-8
C++
false
false
2,477
cpp
// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "chainparams.h" #include "rpcnestedtests.h" #include "util.h" #include "uritests.h" #include "compattests.h" #ifdef ENABLE_WALLET #include "paymentservertests.h" #include "wallettests.h" #endif #include <QApplication> #include <QObject> #include <QTest> #include <openssl/ssl.h> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) #else #if defined(QT_QPA_PLATFORM_MINIMAL) Q_IMPORT_PLUGIN(QMinimalIntegrationPlugin); #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif extern void noui_connect(); // This is all you need to run all the tests int main(int argc, char *argv[]) { SetupEnvironment(); SetupNetworking(); SelectParams(CBaseChainParams::MAIN); noui_connect(); bool fInvalid = false; // Prefer the "minimal" platform for the test instead of the normal default // platform ("xcb", "windows", or "cocoa") so tests can't unintentially // interfere with any background GUIs and don't require extra resources. #if defined(WIN32) _putenv_s("QT_QPA_PLATFORM", "minimal"); #else setenv("QT_QPA_PLATFORM", "minimal", 0); #endif // Don't remove this, it's needed to access // QApplication:: and QCoreApplication:: in the tests QApplication app(argc, argv); app.setApplicationName("BitcoinInterest-Qt-test"); SSL_library_init(); URITests test1; if (QTest::qExec(&test1) != 0) { fInvalid = true; } #ifdef ENABLE_WALLET PaymentServerTests test2; if (QTest::qExec(&test2) != 0) { fInvalid = true; } #endif RPCNestedTests test3; if (QTest::qExec(&test3) != 0) { fInvalid = true; } CompatTests test4; if (QTest::qExec(&test4) != 0) { fInvalid = true; } #ifdef ENABLE_WALLET WalletTests test5; if (QTest::qExec(&test5) != 0) { fInvalid = true; } #endif return fInvalid; }
[ "aaron.mathis@soferox.com" ]
aaron.mathis@soferox.com
3e0780150593d6b204ba2ac5891beb36bd737807
709a4361f04a438c9ae8c6222a439590fdaab606
/src/Classes/GrowthPush/GPJsonHelper.h
5f80e320c2e8224493d3f8fa461d560101eef26f
[ "Apache-2.0" ]
permissive
SIROK-archive/growthpush-cocos2dx
bcdd1adbd7a20731b67668d7f4f4179b6f22d61d
0c605fd49a95ffb25933c4654ffb90053f7cbbee
refs/heads/master
2021-01-17T06:20:30.807237
2015-10-20T05:44:07
2015-10-20T05:44:07
14,578,436
0
0
null
null
null
null
UTF-8
C++
false
false
6,571
h
// // GPJsonHelper.h // growthpush-cocos2dx // // Created by TSURUDA Ryo on 2013/12/11. // Copyright (c) 2013年 TSURUDA Ryo. All rights reserved. // #ifndef GROWTHPUSHPLUGIN_GPJSONHELPER_H_ #define GROWTHPUSHPLUGIN_GPJSONHELPER_H_ #include <string> #include "cocos2d.h" #include "picojson.h" #if 0x00020100 <= COCOS2D_VERSION #define GP_CAN_USE_NUMERIC_OBJECT 1 #endif class GPJsonHelper { public: /** Parse JSON string to CCObject(CCDictionary, CCArray, CCString, CCBool, CCDouble). @param json JSON string @return CCObject* object */ static cocos2d::CCObject *parseJson2CCObject(const char *json) { picojson::value v; std::string error; /* parse json */ picojson::parse(v, json, json + strlen(json), &error); if (!error.empty()) { CCLOGERROR("failed to parse json:%s", error.c_str()); return NULL; } return convertJson2CCObject(v); } /** Parse JSON string to CCDictionary. @param json JSON string @return CCDictionary* object */ static cocos2d::CCDictionary *parseJson2CCDictionary(const char *json) { return dynamic_cast<cocos2d::CCDictionary *>(parseJson2CCObject(json)); } /** Parse JSON string to CCArray. @param json JSON string @return CCArray* object */ static cocos2d::CCArray *parseJson2CCArray(const char *json) { return dynamic_cast<cocos2d::CCArray *>(parseJson2CCObject(json)); } /** Parse JSON string to CCString. @param json JSON string @return CCString* object */ static cocos2d::CCString *parseJson2CCString(const char *json) { return dynamic_cast<cocos2d::CCString *>(parseJson2CCObject(json)); } #ifdef GP_CAN_USE_NUMERIC_OBJECT /** Parse JSON string to CCDouble. @param json JSON string @return CCDouble* object */ static cocos2d::CCDouble *parseJson2CCDouble(const char *json) { return dynamic_cast<cocos2d::CCDouble *>(parseJson2CCObject(json)); } /** Parse JSON string to CCBool. @param json JSON string @return CCBool* object */ static cocos2d::CCBool *parseJson2CCBool(const char *json) { return dynamic_cast<cocos2d::CCBool *>(parseJson2CCObject(json)); } #endif private: /* Convert type picojson::value to CCObject. @param v value of picojson @return CCObject* object */ static cocos2d::CCObject *convertJson2CCObject(picojson::value v) { if (v.is<bool>()) { return convertJson2CCBool(v); // bool } else if (v.is<double>()) { return convertJson2CCDouble(v); // number } else if (v.is<std::string>()) { return convertJson2CCString(v); // string } else if (v.is<picojson::array>()) { return convertJson2CCArray(v); // array } else if (v.is<picojson::object>()) { return convertJson2CCDictionary(v); // object } else if (v.is<picojson::null>()) { return convertJson2Null(v); // null } CCLOGERROR("failed to convert: Unknown object"); return NULL; } /* Convert type picojson::value to CCDictionary. @param v value of picojson @return CCDictionry* object */ static cocos2d::CCObject *convertJson2CCDictionary(picojson::value v) { cocos2d::CCDictionary *pDictionary = new cocos2d::CCDictionary(); if (!pDictionary) { return NULL; } picojson::object obj = v.get<picojson::object>(); for (picojson::object::iterator it = obj.begin(); it != obj.end(); ++it) { cocos2d::CCObject *pObject = convertJson2CCObject(it->second); if (!pObject) { CC_SAFE_DELETE(pDictionary); return NULL; } pDictionary->setObject(pObject, it->first); } return pDictionary; } /* Convert type picojson::value to CCArray. @param v value of picojson @return CCArray* object */ static cocos2d::CCObject *convertJson2CCArray(picojson::value v) { cocos2d::CCArray *pArray = new cocos2d::CCArray(); if (!pArray || !pArray->init()) { CC_SAFE_DELETE(pArray); return NULL; } picojson::array arr = v.get<picojson::array>(); for (picojson::array::iterator it = arr.begin(); it != arr.end(); ++it) { cocos2d::CCObject *pObject = convertJson2CCObject(*it); if (!pObject) { CC_SAFE_DELETE(pArray); return NULL; } pArray->addObject(pObject); } return pArray; } /* Convert type picojson::value to CCString. @param v value of picojson @return CCString* object */ static cocos2d::CCObject *convertJson2CCString(picojson::value v) { std::string s = v.get<std::string>(); return new cocos2d::CCString(s); } /* Convert type picojson::value to CCDouble or CCString. @param v value of picojson @return CCDouble* or CCString* object */ static cocos2d::CCObject *convertJson2CCDouble(picojson::value v) { double d = v.get<double>(); #ifdef GP_CAN_USE_NUMERIC_OBJECT return new cocos2d::CCDouble(d); #else cocos2d::CCString *pString = new cocos2d::CCString(); if (!pString || !pString->initWithFormat("%lf", d)) { CC_SAFE_DELETE(pString); return NULL; } return pString; #endif } /* Convert type picojson::value to CCBool or CCString. @param v value of picojson @return CCBool* or CCString* object */ static cocos2d::CCObject *convertJson2CCBool(picojson::value v) { bool b = v.get<bool>(); #ifdef GP_CAN_USE_NUMERIC_OBJECT return new cocos2d::CCBool(b); #else return new cocos2d::CCString(b ? "true" : "false"); #endif } /* Convert type picojson::value to CCObject. (Because cannot use CCNull Object.) @param v value of picojson @return CCObject* object */ static cocos2d::CCObject *convertJson2Null(picojson::value v) { CC_UNUSED_PARAM(v); // ignore value return new cocos2d::CCObject(); } }; #endif // GROWTHPUSHPLUGIN_GPJSONHELPER_H_
[ "uqtimes@gmail.com" ]
uqtimes@gmail.com
273f05f7e1f3c573f862c76ce59620f6e9bdab6a
8962660c3c4358305337a6d48c7454dc6cab2745
/BackEnd/security/hash_generator.cpp
20b4a63baac310fc925cb308daaa7bf4fd9d4287
[]
no_license
stanley255/smartpot
09e07a1e0b4e7f92152bc0b7897b955f2bcf90a2
52fa779d3482f9da6f8401cdf7591d2ca8ac1ab3
refs/heads/master
2020-03-30T17:15:56.467944
2019-06-23T19:54:35
2019-06-23T19:54:35
151,448,524
3
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
#include <iostream> #include <string> #include <time.h> using namespace std; class Hash { public: string generated_hash; int hashLength, countNumbers, countUpperLetters, countLowerLetters, countSpecialChars; int countTypesOfParams = 4; // Konstanta urcujuca pocet typov argmunetov int getRandomNumber() { return rand() % (10); } char getRandomUppLett() { return rand() % (25) + 65; } char getRandomLowLett() { return rand() % (25) + 97; } char getRandomSpecChar() { return rand() % (14) + 34; } public: Hash(int countNums, int countUppLett, int countLowLett, int countSpecChars) { countNumbers = countNums; countUpperLetters = countUppLett; countLowerLetters = countLowLett; countSpecialChars = countSpecChars; hashLength = countNums + countUppLett + countLowLett + countSpecChars; } string getHash() { int initialLength = 0; int missCounter = 0; while (initialLength != hashLength) { int randomType = rand() % countTypesOfParams; switch (randomType) { case 0: if (countNumbers) { generated_hash += to_string(this->getRandomNumber()); countNumbers--; initialLength++; } break; case 1: if (countUpperLetters) { generated_hash += this->getRandomUppLett(); countUpperLetters--; initialLength++; } break; case 2: if (countLowerLetters) { generated_hash += this->getRandomLowLett(); countLowerLetters--; initialLength++; } break; case 3: if (countSpecialChars) { generated_hash += this->getRandomSpecChar(); countSpecialChars--; initialLength++; } break; default: missCounter++; } } return generated_hash; } }; int main() { srand(time(NULL)); Hash my_hash = Hash(8, 8, 8, 8); cout << my_hash.getHash() << endl; return 0; }
[ "spekarovic@gmail.com" ]
spekarovic@gmail.com
58a46db3237852650b4bc9487ec67fb2bf809a56
d5238c1900a11a9361596aa3da231eafc525f294
/services/ui/ws2/client_root.cc
aecdf32402de44d9af55f36dba0c70ec89787f62
[ "BSD-3-Clause" ]
permissive
hurray567/chromium
4b76415878448171ccdcad07de7ba8d35df2ec2e
b4306e0ec43ea67aa54fa044a6ddec5c28933f8b
refs/heads/master
2023-01-09T02:39:36.320824
2018-04-18T21:24:33
2018-04-18T21:24:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,022
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 "services/ui/ws2/client_root.h" #include "services/ui/ws2/window_data.h" #include "services/ui/ws2/window_service_client.h" #include "ui/aura/mus/client_surface_embedder.h" #include "ui/aura/window.h" #include "ui/compositor/dip_util.h" namespace ui { namespace ws2 { ClientRoot::ClientRoot(WindowServiceClient* window_service_client, aura::Window* window, bool is_top_level) : window_service_client_(window_service_client), window_(window), is_top_level_(is_top_level) { WindowData::GetMayBeNull(window)->set_embedded_window_service_client( window_service_client); window_->AddObserver(this); // TODO: wire up gfx::Insets() correctly below. See usage in // aura::ClientSurfaceEmbedder for details. Insets here are used for // guttering. // TODO: this may only be needed for top-level windows and any ClientRoots // created as the result of a direct call to create a WindowServiceClient by // code running in process (that is, not at the request of a client through // WindowServiceClient). client_surface_embedder_ = std::make_unique<aura::ClientSurfaceEmbedder>( window_, is_top_level, gfx::Insets()); } ClientRoot::~ClientRoot() { WindowData::GetMayBeNull(window_)->set_embedded_window_service_client( nullptr); window_->RemoveObserver(this); } void ClientRoot::FrameSinkIdChanged() { window_->SetEmbedFrameSinkId( WindowData::GetMayBeNull(window_)->frame_sink_id()); UpdatePrimarySurfaceId(); } const viz::LocalSurfaceId& ClientRoot::GetLocalSurfaceId() { gfx::Size size_in_pixels = ui::ConvertSizeToPixel(window_->layer(), window_->bounds().size()); // It's expected by cc code that any time the size changes a new // LocalSurfaceId is used. if (last_surface_size_in_pixels_ != size_in_pixels || !local_surface_id_.is_valid()) { local_surface_id_ = parent_local_surface_id_allocator_.GenerateId(); last_surface_size_in_pixels_ = size_in_pixels; } return local_surface_id_; } void ClientRoot::UpdatePrimarySurfaceId() { client_surface_embedder_->SetPrimarySurfaceId( viz::SurfaceId(window_->GetFrameSinkId(), GetLocalSurfaceId())); } void ClientRoot::OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) { UpdatePrimarySurfaceId(); client_surface_embedder_->UpdateSizeAndGutters(); base::Optional<viz::LocalSurfaceId> surface_id = local_surface_id_; window_service_client_->window_tree_client_->OnWindowBoundsChanged( window_service_client_->TransportIdForWindow(window), old_bounds, new_bounds, std::move(surface_id)); } } // namespace ws2 } // namespace ui
[ "sky@chromium.org" ]
sky@chromium.org
9ee85190c755bd5a5292274777c2d42f224a3ff8
bd226417f1cc508a6fdadf8c996552184e89b34e
/competitive_coding/contests/Codechef/MayLunchTime/B.cpp
30c84eba70572cfc13226a36882b9c0f778b629b
[ "MIT" ]
permissive
rupav/cp
5876a42f5d86df482426b523fdeddcd84843c373
0b4c20ef3504472c1b0a9bbf586bb2daae9631c5
refs/heads/main
2023-02-24T23:21:31.930979
2021-01-30T06:08:15
2021-01-30T06:08:15
334,339,922
0
0
null
null
null
null
UTF-8
C++
false
false
3,371
cpp
/* #include<bits/stdc++.h> using namespace std; #define watch(x) cout << (#x) << " is " << (x) << endl #define fr(i,n) for(int i=0; i<n; i++) #define rep(i, st, en) for(int i=st; i<=en; i++) #define repn(i, st, en) for(int i=st; i>=en; i--) #define sq(a) (a*a) typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; ll mod = 1e9+7; /// https://www.codechef.com/LTIME84A/problems/CONVSTR void solve(){ int n; // n = s.size(); cin>>n; string s, t; cin>>s>>t; int cnt = 0; bool f = true; vector<set<int>> p[2]; /// pos of characters fr(i, 2) p[i].resize(26); priority_queue<int> pq; map<char, bool> mp; fr(i, n){ if(!mp[t[i]]){ pq.push(t[i] - 'a'); mp[t[i]] = 1; } p[0][s[i] - 'a'].insert(i); p[1][t[i] - 'a'].insert(i); } vector<vector<int>> ops; while(pq.size()){ int x = pq.top(); pq.pop(); if(!p[0][x].size()){ f = false; break; } auto jit = p[0][x].begin(); vector<int> v; for(auto &it: p[1][x]){ if(s[it] - 'a' != x){ if(s[it] - 'a' < x) { f = false; break; } v.push_back(it); fr(i, 26){ if(p[0][i].size()) p[0][i].erase(it); } } } if(!f) break; if(v.size()){ cnt++; v.push_back(*jit); ops.push_back(v); } } if(!f){ cout<<-1<<endl; } else { assert(cnt <= 2); cout<<cnt<<endl; for(auto v: ops){ cout<<v.size()<<" "; sort(v.begin(), v.end()); for(auto it: v) cout<<it<<" "; cout<<endl; } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t = 1; cin>>t; while(t--){ solve(); } return 0; } */ #include <bits/stdc++.h> #define endl '\n' #define SZ(x) ((int)x.size()) #define ALL(V) V.begin(), V.end() #define L_B lower_bound #define U_B upper_bound #define pb push_back using namespace std; template<class T, class T1> int chkmin(T &x, const T1 &y) { return x > y ? x = y, 1 : 0; } template<class T, class T1> int chkmax(T &x, const T1 &y) { return x < y ? x = y, 1 : 0; } const int MAXN = (1 << 20); int n; string a; string b; void read() { cin >> n; cin >> a; cin >> b; } void solve() { vector<vector<int> > ans; for(int i = 0; i < n; i++) { if(a[i] < b[i]) { cout << -1 << endl; return; } } for(char c = 'z'; c >= 'a'; c--) { vector<int> pos; bool ok = 0; for(int i = 0; i < n; i++) { if(b[i] == c && a[i] != c) { pos.pb(i); } } if(!ok && !pos.empty()) { for(int i = 0; i < n; i++) { if(a[i] == c) { ok = 1; pos.pb(i); } } } if(!ok && !pos.empty()) { cout << -1 << endl; return; } if(!pos.empty()) ans.pb(pos); for(int i: pos) { a[i] = c; } } cout << SZ(ans) << endl; for(auto li: ans) { cout << SZ(li) << " "; for(int x: li) cout << x << " "; cout << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--) { read(); solve(); } return 0; }
[ "ruavwinchester@gmail.com" ]
ruavwinchester@gmail.com
5849fd2af2475be7f9a5ea727c8f7d7372e8c4aa
2edd4d0d97c232affb8c8e2f03a4efa00cbdc0f4
/src/imgproc/Contours.h
5d00bf941d094af85c04e9d812318edcf023e1dd
[ "MIT" ]
permissive
akshonesports/node-opencv
57d370e75ee8f19197f76a97b0b9e7674c07d1ce
fe42999e9ee529f193b53006c261c8411fce50a1
refs/heads/3.x
2021-01-19T16:02:48.514339
2018-01-13T11:20:58
2018-01-13T11:40:41
100,984,793
0
4
null
2017-10-31T16:47:01
2017-08-21T19:20:57
C++
UTF-8
C++
false
false
1,160
h
#ifndef __IMGPROC__CONTOURS_H__ #define __IMGPROC__CONTOURS_H__ #include "common.h" #define CONTOURS_FROM_ARGS(NAME, IND) \ Contours *NAME = nullptr; \ if (info.Length() > IND && Contours::HasInstance(info[IND])) { \ NAME = UNWRAP_OBJECT(Contours, info[IND]->ToObject()); \ } #define ASSERT_CONTOURS_FROM_ARGS(NAME, IND) \ CONTOURS_FROM_ARGS(NAME, IND) else { \ return THROW_INVALID_ARGUMENT_TYPE(IND, "an instance of Contours"); \ } class Contours : public Nan::ObjectWrap { private: static Nan::Persistent<FunctionTemplate> constructor; public: std::vector<std::vector<cv::Point>> contours; std::vector<cv::Vec4i> hierarchy; static void Init(Local<Object> target); static NAN_METHOD(New); Contours() {}; NEW_INSTANCE_DECL; static Local<Object> NewInstance(const std::vector<std::vector<cv::Point>> &contours, const std::vector<cv::Vec4i> &hierarchy); HAS_INSTANCE_DECL; static NAN_INDEX_GETTER(IndexGetter); static NAN_INDEX_SETTER(IndexSetter); static NAN_INDEX_QUERY(IndexQuery); static NAN_INDEX_ENUMERATOR(IndexEnumerator); static NAN_GETTER(LengthGetter); }; #endif // __IMGPROC__CONTOURS_H__
[ "slam@akshonesports.com" ]
slam@akshonesports.com
86749cf25c7351170d8cdbb8218600b9413f80b2
992aba2f1b0abab1ad015e9e88af7f486e9f46bc
/src/string17.lib/string17/byteCount.h
117e4eccc9f814de02c9c2b8f566f917e918b498
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
basicpp17/basicpp17
7f0b622ef03cd7d52304187c97a2cc9ac1707669
2f4a93774c6bf77b57544f4e0ed6909988c34537
refs/heads/develop
2021-07-17T21:03:45.876192
2020-05-31T15:23:13
2020-05-31T15:23:13
164,132,113
8
3
MIT
2020-04-08T12:03:16
2019-01-04T16:48:14
C++
UTF-8
C++
false
false
690
h
#pragma once #include "meta17/Type.h" #include "meta17/Value.h" #include <type_traits> namespace string17 { using meta17::Value; // ADL allows us to have all functions in scope struct ADL {}; constexpr auto adl = ADL{}; constexpr auto byteCount(ADL, const char* p) -> size_t { auto l = size_t{}; while ('\0' != p[l]) l++; return l; } template<class T> constexpr auto byteCount(ADL, const T& t) -> decltype(t.size()) { return t.size(); } constexpr auto byteCount(ADL, char) -> size_t { return 1; } template<auto f> constexpr auto byteCount(ADL, Value<f>) -> size_t { return byteCount(adl, Value<f>::v); } } // namespace string17
[ "andreas.reischuck@hicknhack-software.com" ]
andreas.reischuck@hicknhack-software.com
4f77e41d3672d66693283097ee1951b1c2bce471
46cbd8ca773c1481bb147b54765985c636627d29
/funf/menu.cpp
cb9585b3234daae64fc192822ce50996570d8fe8
[]
no_license
ator89/Cpp
e7ddb1ccd59ffa5083fced14c4d54403160f2ca7
9d6bd29e7d97022703548cbef78719536bc149fe
refs/heads/master
2021-06-01T13:14:27.508828
2020-10-21T05:15:52
2020-10-21T05:15:52
150,691,862
0
0
null
null
null
null
UTF-8
C++
false
false
233
cpp
#include <iostream> using std::cin; using std::coud; using std::endl; #include <string> using std::string; int menu(int); int main(){ cout << "Welcome" << endl; return 0; } int menu(int opcion){ return opcion; }
[ "ator89@outlook.com" ]
ator89@outlook.com
9dc02b06d7d549d634002bf179bc31bbaf2c7841
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/multimedia/danim/extinc/dxvector.h
f59b500a5fcae84d1d0fd27b755dc8ac068449d1
[]
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
34,750
h
/******************************************************************************* * DXVector.h * *------------* * Description: * This is the header file for the vector and matrix classes. *------------------------------------------------------------------------------- * Created By: Mike Arnstein Date: 04/11/97 * Copyright (C) 1997 Microsoft Corporation * All Rights Reserved * *------------------------------------------------------------------------------- * Revisions: * *******************************************************************************/ #ifndef DXVector_h #define DXVector_h #ifndef _INC_MATH #include <math.h> #endif #ifndef _INC_CRTDBG #include <crtdbg.h> #endif //=== Constants ==================================================== //=== Class, Enum, Struct and Union Declarations =================== class CDXMatrix4x4F; //=== Enumerated Set Definitions =================================== //=== Function Type Definitions ==================================== float det4x4( CDXMatrix4x4F *pIn ); float det3x3( float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3 ); float det2x2( float a, float b, float c, float d ); //=== Class, Struct and Union Definitions ========================== /*** CDXVec ************ * This template implements basic vector operations for each of the * union types */ #define CDXV_C CDXVec<TYPE, eBndType> #define CDXV_T ((TYPE*)u.D) #define CDXV_O( OtherVec ) ((TYPE*)OtherVec.u.D) template<class TYPE, DXBNDTYPE eBndType> class CDXVec : public DXVEC { /*=== Methods =======*/ public: /*--- Constructors ---*/ CDXVec() { eType = eBndType; ZeroVector(); } CDXVec(BOOL bInit) { eType = eBndType; if (bInit) ZeroVector(); } CDXVec( TYPE x, TYPE y, TYPE z, TYPE t ) { eType = eBndType; CDXV_T[DXB_X] = x; CDXV_T[DXB_Y] = y; CDXV_T[DXB_Z] = z; CDXV_T[DXB_T] = t; } CDXVec( const CDXVec& Other ) { memcpy( this, (void *)&Other, sizeof(DXVEC) ); } CDXVec( const DXVEC Other ) { memcpy( this, &Other, sizeof(DXVEC) ); } operator TYPE *() { return CDXV_T; } operator const TYPE *() { return CDXV_T; } /*--- operations ---*/ void ZeroVector( void ) { memset( u.D, 0, sizeof(TYPE) * 4); } /*--- operators ---*/ TYPE& operator[]( int index ) const { return CDXV_T[index]; } TYPE& operator[]( long index ) const { return CDXV_T[index]; } TYPE& operator[]( USHORT index ) const { return CDXV_T[index]; } TYPE& operator[]( DWORD index ) const { return CDXV_T[index]; } CDXV_C operator+(const CDXV_C& v); CDXV_C operator-(const CDXV_C& v); void operator=(const CDXV_C& srcVector); void operator+=(const CDXV_C& vOther); void operator-=(const CDXV_C& vOther); BOOL operator==(const CDXV_C& otherVector) const; BOOL operator!=(const CDXV_C& otherVector) const; }; template<class TYPE, DXBNDTYPE eBndType> CDXV_C CDXV_C::operator+( const CDXV_C& srcVector ) { CDXV_C Result( this ); CDXV_O( Result )[DXB_X] += CDXV_O( srcVector )[DXB_X]; CDXV_O( Result )[DXB_Y] += CDXV_O( srcVector )[DXB_Y]; CDXV_O( Result )[DXB_Z] += CDXV_O( srcVector )[DXB_Z]; CDXV_O( Result )[DXB_T] += CDXV_O( srcVector )[DXB_T]; return Result; } /* CDXVec::operator+ */ template<class TYPE, DXBNDTYPE eBndType> CDXV_C CDXV_C::operator-( const CDXV_C& srcVector ) { CDXV_C Result( this ); CDXV_O( Result )[DXB_X] -= CDXV_O( srcVector )[DXB_X]; CDXV_O( Result )[DXB_Y] -= CDXV_O( srcVector )[DXB_Y]; CDXV_O( Result )[DXB_Z] -= CDXV_O( srcVector )[DXB_Z]; CDXV_O( Result )[DXB_T] -= CDXV_O( srcVector )[DXB_T]; return Result; } /* CDXVec::operator- */ template<class TYPE, DXBNDTYPE eBndType> void CDXV_C::operator=( const CDXV_C& srcVector ) { memcpy( this, &srcVector, sizeof(CDXVec) ); } /* CDXVec::operator= */ template<class TYPE, DXBNDTYPE eBndType> BOOL CDXV_C::operator==(const CDXV_C& otherVector) const { return !memcmp( this, &otherVector, sizeof(otherVector) ); } /* CDXVec::operator== */ template<class TYPE, DXBNDTYPE eBndType> BOOL CDXV_C::operator!=(const CDXV_C& otherVector) const { return memcmp( this, &otherVector, sizeof(otherVector) ); } /* CDXVec::operator!= */ template<class TYPE, DXBNDTYPE eBndType> void CDXV_C::operator+=(const CDXV_C& vOther) { CDXV_T[DXB_X] += CDXV_O( vOther )[DXB_X]; CDXV_T[DXB_Y] += CDXV_O( vOther )[DXB_Y]; CDXV_T[DXB_Z] += CDXV_O( vOther )[DXB_Z]; CDXV_T[DXB_T] += CDXV_O( vOther )[DXB_T]; } /* CDXVec::operator+= */ template<class TYPE, DXBNDTYPE eBndType> void CDXV_C::operator-=(const CDXVec& vOther) { CDXV_T[DXB_X] -= CDXV_O( vOther )[DXB_X]; CDXV_T[DXB_Y] -= CDXV_O( vOther )[DXB_Y]; CDXV_T[DXB_Z] -= CDXV_O( vOther )[DXB_Z]; CDXV_T[DXB_T] -= CDXV_O( vOther )[DXB_T]; } /* CDXVec::operator-= */ typedef CDXVec<long, DXBT_DISCRETE> CDXDVec; typedef CDXVec<LONGLONG, DXBT_DISCRETE64> CDXDVec64; typedef CDXVec<float, DXBT_CONTINUOUS> CDXCVec; typedef CDXVec<double, DXBT_CONTINUOUS64> CDXCVec64; /*** CDX2DXForm ************ * This class implements basic matrix operation based on the GDI XFORM * structure. */ //const DX2DXFORM g_DX2DXFORMIdentity = { 1., 0., 0., 1., 0., 0., DX2DXO_IDENTITY }; class CDX2DXForm : public DX2DXFORM { /*=== Methods =======*/ public: /*--- Constructors ---*/ CDX2DXForm() { SetIdentity(); } CDX2DXForm( const CDX2DXForm& Other ) { memcpy( this, &Other, sizeof(*this) ); } CDX2DXForm( const DX2DXFORM& Other ) { memcpy( this, &Other, sizeof(*this) ); } /*--- methods ---*/ void DetermineOp( void ); void Set( const DX2DXFORM& Other ) { memcpy( this, &Other, sizeof(*this) ); DetermineOp(); } void ZeroMatrix( void ) { memset( this, 0, sizeof( *this ) ); } void SetIdentity( void ) { eM11 = 1.; eM12 = 0.; eM21 = 0.; eM22 = 1.; eDx = 0.; eDy = 0.; eOp = DX2DXO_IDENTITY; } BOOL IsIdentity() const { return eOp == DX2DXO_IDENTITY; } void Scale( float sx, float sy ); void Rotate( float Rotation ); void Translate( float dx, float dy ); BOOL Invert(); void TransformBounds( const DXBNDS& Bnds, DXBNDS& ResultBnds ) const; void TransformPoints( const DXFPOINT InPnts[], DXFPOINT OutPnts[], ULONG ulCount ) const; void GetMinMaxScales( float& MinScale, float& MaxScale ); /*--- operators ---*/ DXFPOINT operator*( const DXFPOINT& v ) const; CDX2DXForm operator*( const CDX2DXForm& Other ) const; }; //=== CDX2DXForm methods ============================================================== inline void CDX2DXForm::DetermineOp( void ) { if( ( eM12 == 0. ) && ( eM21 == 0. ) ) { if( ( eM11 == 1. ) && ( eM22 == 1. ) ) { eOp = ( ( eDx == 0 ) && ( eDy == 0 ) )?(DX2DXO_IDENTITY):(DX2DXO_TRANSLATE); } else { eOp = ( ( eDx == 0 ) && ( eDy == 0 ) )?(DX2DXO_SCALE):(DX2DXO_SCALE_AND_TRANS); } } else { eOp = ( ( eDx == 0 ) && ( eDy == 0 ) )?(DX2DXO_GENERAL):(DX2DXO_GENERAL_AND_TRANS); } } /* CDX2DXForm::DetermineOp */ inline float DXSq( float f ) { return f * f; } // This function computes the Min and Max scale that a matrix represents. // In other words, what is the maximum/minimum length that a line of length 1 // could get stretched/shrunk to if the line was transformed by this matrix. // // The function uses eigenvalues; and returns two float numbers. Both are // non-negative; and MaxScale >= MinScale. // inline void CDX2DXForm::GetMinMaxScales( float& MinScale, float& MaxScale ) { if( ( eM12 == 0. ) && ( eM21 == 0. ) ) { // Let MinScale = abs(eM11) if (eM11 < 0) MinScale = -eM11; else MinScale = eM11; // Let MaxScale = abs(eM22) if (eM22 < 0) MaxScale = -eM22; else MaxScale = eM22; // Swap Min/Max if necessary if (MinScale > MaxScale) { float flTemp = MinScale; MinScale = MaxScale; MaxScale = flTemp; } } else { float t1 = DXSq(eM11) + DXSq(eM12) + DXSq(eM21) + DXSq(eM22); if( t1 == 0. ) { MinScale = MaxScale = 0; } else { float t2 = (float)sqrt( (DXSq(eM12 + eM21) + DXSq(eM11 - eM22)) * (DXSq(eM12 - eM21) + DXSq(eM11 + eM22)) ); // Due to floating point error; t1 may end up less than t2; // but that would mean that the min scale was small (relative // to max scale) if (t1 <= t2) MinScale = 0; else MinScale = (float)sqrt( (t1 - t2) * .5f ); MaxScale = (float)sqrt( (t1 + t2) * .5f ); } } } /* CDX2DXForm::GetMinMaxScales */ inline void CDX2DXForm::Rotate( float Rotation ) { double Angle = Rotation * (3.1415926535/180.0); float CosZ = (float)cos( Angle ); float SinZ = (float)sin( Angle ); if (CosZ > 0.0F && CosZ < 0.0000005F) { CosZ = .0F; } if (SinZ > -0.0000005F && SinZ < .0F) { SinZ = .0F; } float M11 = ( CosZ * eM11 ) + ( SinZ * eM21 ); float M21 = (-SinZ * eM11 ) + ( CosZ * eM21 ); float M12 = ( CosZ * eM12 ) + ( SinZ * eM22 ); float M22 = (-SinZ * eM12 ) + ( CosZ * eM22 ); eM11 = M11; eM21 = M21; eM12 = M12; eM22 = M22; DetermineOp(); } /* CDX2DXForm::Rotate */ inline void CDX2DXForm::Scale( float sx, float sy ) { eM11 *= sx; eM12 *= sx; eDx *= sx; eM21 *= sy; eM22 *= sy; eDy *= sy; DetermineOp(); } /* CDX2DXForm::Scale */ inline void CDX2DXForm::Translate( float dx, float dy ) { eDx += dx; eDy += dy; DetermineOp(); } /* CDX2DXForm::Translate */ inline void CDX2DXForm::TransformBounds( const DXBNDS& Bnds, DXBNDS& ResultBnds ) const { ResultBnds = Bnds; if( eOp != DX2DXO_IDENTITY ) { ResultBnds.u.D[DXB_X].Min = (long)(( eM11 * Bnds.u.D[DXB_X].Min ) + ( eM12 * Bnds.u.D[DXB_Y].Min ) + eDx); ResultBnds.u.D[DXB_X].Max = (long)(( eM11 * Bnds.u.D[DXB_X].Max ) + ( eM12 * Bnds.u.D[DXB_Y].Max ) + eDx); ResultBnds.u.D[DXB_Y].Min = (long)(( eM21 * Bnds.u.D[DXB_X].Min ) + ( eM22 * Bnds.u.D[DXB_Y].Min ) + eDy); ResultBnds.u.D[DXB_Y].Max = (long)(( eM21 * Bnds.u.D[DXB_X].Max ) + ( eM22 * Bnds.u.D[DXB_Y].Max ) + eDy); } } /* CDX2DXForm::TransformBounds */ inline void CDX2DXForm::TransformPoints( const DXFPOINT InPnts[], DXFPOINT OutPnts[], ULONG ulCount ) const { ULONG i; switch( eOp ) { case DX2DXO_IDENTITY: memcpy( OutPnts, InPnts, ulCount * sizeof( DXFPOINT ) ); break; case DX2DXO_TRANSLATE: for( i = 0; i < ulCount; ++i ) { OutPnts[i].x = InPnts[i].x + eDx; OutPnts[i].y = InPnts[i].y + eDy; } break; case DX2DXO_SCALE: for( i = 0; i < ulCount; ++i ) { OutPnts[i].x = InPnts[i].x * eM11; OutPnts[i].y = InPnts[i].y * eM22; } break; case DX2DXO_SCALE_AND_TRANS: for( i = 0; i < ulCount; ++i ) { OutPnts[i].x = (InPnts[i].x * eM11) + eDx; OutPnts[i].y = (InPnts[i].y * eM22) + eDy; } break; case DX2DXO_GENERAL: for( i = 0; i < ulCount; ++i ) { OutPnts[i].x = ( InPnts[i].x * eM11 ) + ( InPnts[i].y * eM12 ); OutPnts[i].y = ( InPnts[i].x * eM21 ) + ( InPnts[i].y * eM22 ); } break; case DX2DXO_GENERAL_AND_TRANS: for( i = 0; i < ulCount; ++i ) { OutPnts[i].x = ( InPnts[i].x * eM11 ) + ( InPnts[i].y * eM12 ) + eDx; OutPnts[i].y = ( InPnts[i].x * eM21 ) + ( InPnts[i].y * eM22 ) + eDy; } break; default: _ASSERT( 0 ); // invalid operation id } } /* CDX2DXForm::TransformPoints */ inline DXFPOINT CDX2DXForm::operator*( const DXFPOINT& v ) const { DXFPOINT NewPnt; NewPnt.x = ( v.x * eM11 ) + ( v.y * eM12 ) + eDx; NewPnt.y = ( v.x * eM21 ) + ( v.y * eM22 ) + eDy; return NewPnt; } /* CDX2DXForm::operator* */ inline CDX2DXForm CDX2DXForm::operator*( const CDX2DXForm& Other ) const { DX2DXFORM x; x.eM11 = ( eM11 * Other.eM11 ) + ( eM12 * Other.eM21 ); x.eM12 = ( eM11 * Other.eM12 ) + ( eM12 * Other.eM22 ); x.eDx = ( eM11 * Other.eDx ) + ( eM12 * Other.eDy ) + eDx; x.eM21 = ( eM21 * Other.eM11 ) + ( eM22 * Other.eM21 ); x.eM22 = ( eM21 * Other.eM12 ) + ( eM22 * Other.eM22 ); x.eDy = ( eM21 * Other.eDx ) + ( eM22 * Other.eDy ) + eDy; return x; } /* CDX2DXForm::operator*= */ inline BOOL CDX2DXForm::Invert() { switch( eOp ) { case DX2DXO_IDENTITY: break; case DX2DXO_TRANSLATE: eDx = -eDx; eDy = -eDy; break; case DX2DXO_SCALE: if (eM11 == 0.0 || eM22 == 0.0) return false; eM11 = 1.0f / eM11; eM22 = 1.0f / eM22; break; case DX2DXO_SCALE_AND_TRANS: { if (eM11 == 0.0f || eM22 == 0.0f) return false; // Our old equation was F = aG + b // The inverse is G = F/a - b/a where a is eM11 and b is eDx float flOneOverA = 1.0f / eM11; eDx = -eDx * flOneOverA; eM11 = flOneOverA; // Our old equation was F = aG + b // The inverse is G = F/a - b/a where a is eM22 and b is eDy flOneOverA = 1.0f / eM22; eDy = -eDy * flOneOverA; eM22 = flOneOverA; break; } case DX2DXO_GENERAL: case DX2DXO_GENERAL_AND_TRANS: { // The inverse of A= |a b| is | d -c|*(1/Det) where Det is the determinant of A // |c d| |-b a| // Det(A) = ad - bc // Compute determininant float flDet = (eM11 * eM22 - eM12 * eM21); if (flDet == 0.0f) return FALSE; float flCoef = 1.0f / flDet; // Remember old value of eM11 float flM11Original = eM11; eM11 = flCoef * eM22; eM12 = -flCoef * eM12; eM21 = -flCoef * eM21; eM22 = flCoef * flM11Original; // If we have a translation; then we need to // compute new values for that translation if (eOp == DX2DXO_GENERAL_AND_TRANS) { // Remember original value of eDx float eDxOriginal = eDx; eDx = -eM11 * eDx - eM12 * eDy; eDy = -eM21 * eDxOriginal - eM22 * eDy; } } break; default: _ASSERT( 0 ); // invalid operation id } // We don't need to call DetermineOp here // because the op doesn't change when inverted // i.e. a scale remains a scale, etc. return true; } /* CDX2DXForm::Invert */ /*** CDXMatrix4x4F ************ * This class implements basic matrix operation based on a 4x4 array. */ //const float g_DXMat4X4Identity[4][4] = //{ // { 1.0, 0. , 0. , 0. }, // { 0. , 1.0, 0. , 0. }, // { 0. , 0. , 1.0, 0. }, // { 0. , 0. , 0. , 1.0 } //}; class CDXMatrix4x4F { public: /*=== Member Data ===*/ float m_Coeff[4][4]; /*=== Methods =======*/ public: /*--- Constructors ---*/ CDXMatrix4x4F() { SetIdentity(); } CDXMatrix4x4F( const CDXMatrix4x4F& Other ) { CopyMemory( (void *)&m_Coeff, (void *)&Other.m_Coeff, sizeof(m_Coeff) ); } CDXMatrix4x4F( DX2DXFORM& XForm ); /*--- operations ---*/ void ZeroMatrix( void ) { memset( m_Coeff, 0, sizeof( m_Coeff ) ); } void SetIdentity( void ) { memset( m_Coeff, 0, sizeof( m_Coeff ) ); m_Coeff[0][0] = m_Coeff[1][1] = m_Coeff[2][2] = m_Coeff[3][3] = 1.0; } void SetCoefficients( float Coeff[4][4] ) { memcpy( m_Coeff, Coeff, sizeof( m_Coeff )); } void GetCoefficients( float Coeff[4][4] ) { memcpy( Coeff, m_Coeff, sizeof( m_Coeff )); } //BOOL IsIdentity(); void Scale( float sx, float sy, float sz ); void Rotate( float rx, float ry, float rz ); void Translate( float dx, float dy, float dz ); BOOL Invert(); BOOL GetInverse( CDXMatrix4x4F *pIn ); void Transpose(); void GetTranspose( CDXMatrix4x4F *pIn ); void GetAdjoint( CDXMatrix4x4F *pIn ); HRESULT InitFromSafeArray( SAFEARRAY *psa ); HRESULT GetSafeArray( SAFEARRAY **ppsa ) const; void TransformBounds( DXBNDS& Bnds, DXBNDS& ResultBnds ); /*--- operators ---*/ CDXDVec operator*( CDXDVec& v) const; CDXCVec operator*( CDXCVec& v) const; CDXMatrix4x4F operator*(CDXMatrix4x4F Matrix) const; void operator*=(CDXMatrix4x4F Matrix) const; void CDXMatrix4x4F::operator=(const CDXMatrix4x4F srcMatrix); void CDXMatrix4x4F::operator+=(const CDXMatrix4x4F otherMatrix); void CDXMatrix4x4F::operator-=(const CDXMatrix4x4F otherMatrix); BOOL CDXMatrix4x4F::operator==(const CDXMatrix4x4F otherMatrix) const; BOOL CDXMatrix4x4F::operator!=(const CDXMatrix4x4F otherMatrix) const; }; inline CDXMatrix4x4F::CDXMatrix4x4F( DX2DXFORM& XForm ) { SetIdentity(); m_Coeff[0][0] = XForm.eM11; m_Coeff[0][1] = XForm.eM12; m_Coeff[1][0] = XForm.eM21; m_Coeff[1][1] = XForm.eM22; m_Coeff[0][3] = XForm.eDx; m_Coeff[1][3] = XForm.eDy; } // Additional Operations inline void CDXMatrix4x4F::operator=(const CDXMatrix4x4F srcMatrix) { CopyMemory( (void *)m_Coeff, (const void *)srcMatrix.m_Coeff, sizeof(srcMatrix.m_Coeff) ); } /* CDXMatrix4x4F::operator= */ inline BOOL CDXMatrix4x4F::operator==(const CDXMatrix4x4F otherMatrix) const { return !memcmp( (void *)m_Coeff, (const void *)otherMatrix.m_Coeff, sizeof(otherMatrix.m_Coeff) ); } /* CDXMatrix4x4F::operator== */ inline BOOL CDXMatrix4x4F::operator!=(const CDXMatrix4x4F otherMatrix) const { return memcmp( (void *)m_Coeff, (const void *)otherMatrix.m_Coeff, sizeof(otherMatrix.m_Coeff) ); } /* CDXMatrix4x4F::operator!= */ inline void CDXMatrix4x4F::operator+=(const CDXMatrix4x4F otherMatrix) { for( int i = 0; i < 4; i++ ) for( int j = 0; j < 4; j++ ) m_Coeff[i][j] += otherMatrix.m_Coeff[i][j]; } /* CDXMatrix4x4F::operator+= */ inline void CDXMatrix4x4F::operator-=(const CDXMatrix4x4F otherMatrix) { for( int i = 0; i < 4; i++ ) for( int j = 0; j < 4; j++ ) m_Coeff[i][j] -= otherMatrix.m_Coeff[i][j]; } /* CDXMatrix4x4F::operator-= */ inline CDXDVec CDXMatrix4x4F::operator*(CDXDVec& v) const { CDXDVec t; float temp; temp = v[0]*m_Coeff[0][0]+v[1]*m_Coeff[1][0]+v[2]*m_Coeff[2][0]+v[3]*m_Coeff[3][0]; t[0] = (long)((temp < 0) ? temp -= .5 : temp += .5); temp = v[0]*m_Coeff[0][1]+v[1]*m_Coeff[1][1]+v[2]*m_Coeff[2][1]+v[3]*m_Coeff[3][1]; t[1] = (long)((temp < 0) ? temp -= .5 : temp += .5); temp = v[0]*m_Coeff[0][2]+v[1]*m_Coeff[1][2]+v[2]*m_Coeff[2][2]+v[3]*m_Coeff[3][2]; t[2] = (long)((temp < 0) ? temp -= .5 : temp += .5); temp = v[0]*m_Coeff[0][3]+v[1]*m_Coeff[1][3]+v[2]*m_Coeff[2][3]+v[3]*m_Coeff[3][3]; t[3] = (long)((temp < 0) ? temp -= .5 : temp += .5); return t; } /* CDXMatrix4x4F::operator*(DXDVEC) */ inline CDXCVec CDXMatrix4x4F::operator*(CDXCVec& v) const { CDXCVec t; t[0] = v[0]*m_Coeff[0][0]+v[1]*m_Coeff[1][0]+v[2]*m_Coeff[2][0]+v[3]*m_Coeff[3][0]; t[1] = v[0]*m_Coeff[0][1]+v[1]*m_Coeff[1][1]+v[2]*m_Coeff[2][1]+v[3]*m_Coeff[3][1]; t[2] = v[0]*m_Coeff[0][2]+v[1]*m_Coeff[1][2]+v[2]*m_Coeff[2][2]+v[3]*m_Coeff[3][2]; t[3] = v[0]*m_Coeff[0][3]+v[1]*m_Coeff[1][3]+v[2]*m_Coeff[2][3]+v[3]*m_Coeff[3][3]; return t; } /* CDXMatrix4x4F::operator*(DXCVEC) */ inline CDXMatrix4x4F CDXMatrix4x4F::operator*(CDXMatrix4x4F Mx) const { CDXMatrix4x4F t; int i, j; for( i = 0; i < 4; i++ ) { for( j = 0; j < 4; j++ ) { t.m_Coeff[i][j] = m_Coeff[i][0] * Mx.m_Coeff[0][j] + m_Coeff[i][1] * Mx.m_Coeff[1][j] + m_Coeff[i][2] * Mx.m_Coeff[2][j] + m_Coeff[i][3] * Mx.m_Coeff[3][j]; } } return t; } /* CDXMatrix4x4F::operator*(CDXMatrix4x4F) */ inline void CDXMatrix4x4F::operator*=(CDXMatrix4x4F Mx) const { CDXMatrix4x4F t; int i, j; for( i = 0; i < 4; i++ ) { for( j = 0; j < 4; j++ ) { t.m_Coeff[i][j] = m_Coeff[i][0] * Mx.m_Coeff[0][j] + m_Coeff[i][1] * Mx.m_Coeff[1][j] + m_Coeff[i][2] * Mx.m_Coeff[2][j] + m_Coeff[i][3] * Mx.m_Coeff[3][j]; } } CopyMemory( (void *)m_Coeff, (void *)t.m_Coeff, sizeof(m_Coeff) ); } /* CDXMatrix4x4F::operator*=(CDXMatrix4x4F) */ inline void CDXMatrix4x4F::Scale( float sx, float sy, float sz ) { if( sx != 1. ) { m_Coeff[0][0] *= sx; m_Coeff[0][1] *= sx; m_Coeff[0][2] *= sx; m_Coeff[0][3] *= sx; } if( sy != 1. ) { m_Coeff[1][0] *= sy; m_Coeff[1][1] *= sy; m_Coeff[1][2] *= sy; m_Coeff[1][3] *= sy; } if( sz != 1. ) { m_Coeff[2][0] *= sz; m_Coeff[2][1] *= sz; m_Coeff[2][2] *= sz; m_Coeff[2][3] *= sz; } } /* CDXMatrix4x4F::Scale */ inline void CDXMatrix4x4F::Translate( float dx, float dy, float dz ) { float a, b, c, d; a = b = c = d = 0; if( dx != 0. ) { a += m_Coeff[0][0]*dx; b += m_Coeff[0][1]*dx; c += m_Coeff[0][2]*dx; d += m_Coeff[0][3]*dx; } if( dy != 0. ) { a += m_Coeff[1][0]*dy; b += m_Coeff[1][1]*dy; c += m_Coeff[1][2]*dy; d += m_Coeff[1][3]*dy; } if( dz != 0. ) { a += m_Coeff[2][0]*dz; b += m_Coeff[2][1]*dz; c += m_Coeff[2][2]*dz; d += m_Coeff[2][3]*dz; } m_Coeff[3][0] += a; m_Coeff[3][1] += b; m_Coeff[3][2] += c; m_Coeff[3][3] += d; } /* CDXMatrix4x4F::Translate */ inline void CDXMatrix4x4F::Rotate( float rx, float ry, float rz ) { const float l_dfCte = (const float)(3.1415926535/180.0); float lAngleY = 0.0; float lAngleX = 0.0; float lAngleZ = 0.0; float lCosX = 1.0; float lSinX = 0.0; float lCosY = 1.0; float lSinY = 0.0; float lCosZ = 1.0; float lSinZ = 0.0; // calculate rotation angle sines and cosines if( rx != 0 ) { lAngleX = rx * l_dfCte; lCosX = (float)cos(lAngleX); lSinX = (float)sin(lAngleX); if (lCosX > 0.0F && lCosX < 0.0000005F) { lCosX = .0F; } if (lSinX > -0.0000005F && lSinX < .0F) { lSinX = .0F; } } if( ry != 0 ) { lAngleY = ry * l_dfCte; lCosY = (float)cos(lAngleY); lSinY = (float)sin(lAngleY); if (lCosY > 0.0F && lCosY < 0.0000005F) { lCosY = .0F; } if (lSinY > -0.0000005F && lSinY < .0F) { lSinY = .0F; } } if( rz != 0 ) { lAngleZ = rz * l_dfCte; lCosZ = (float)cos(lAngleZ); lSinZ = (float)sin(lAngleZ); if (lCosZ > 0.0F && lCosZ < 0.0000005F) { lCosZ = .0F; } if (lSinZ > -0.0000005F && lSinZ < .0F) { lSinZ = .0F; } } float u, v; int i; //--- X Rotation for( i = 0; i < 4; i++ ) { u = m_Coeff[1][i]; v = m_Coeff[2][i]; m_Coeff[1][i] = lCosX*u+lSinX*v; m_Coeff[2][i] = -lSinX*u+lCosX*v; } //--- Y Rotation for( i = 0; i < 4; i++ ) { u = m_Coeff[0][i]; v = m_Coeff[2][i]; m_Coeff[0][i] = lCosY*u-lSinY*v; m_Coeff[2][i] = lSinY*u+lCosY*v; } //--- Z Rotation for( i = 0; i < 4; i++ ) { u = m_Coeff[0][i]; v = m_Coeff[1][i]; m_Coeff[0][i] = lCosZ*u+lSinZ*v; m_Coeff[1][i] = -lSinZ*u+lCosZ*v; } } /* inline BOOL CDXMatrix4x4F::IsIdentity() { return !memcmp( m_Coeff, g_DXMat4X4Identity, sizeof(g_DXMat4X4Identity) ); } /* CDXMatrix4x4F::IsIdentity */ /* Uses Gaussian elimination to invert the 4 x 4 non-linear matrix in t and return the result in Mx. The matrix t is destroyed in the process. */ inline BOOL CDXMatrix4x4F::Invert() { int i,j,k,Pivot; float PValue; CDXMatrix4x4F Mx; Mx.SetIdentity(); /* Find pivot element. Use partial pivoting by row */ for( i = 0;i < 4; i++ ) { Pivot = 0; for( j = 0; j < 4; j++ ) { if( fabs(m_Coeff[i][j]) > fabs(m_Coeff[i][Pivot]) ) Pivot = j; } if( m_Coeff[i][Pivot] == 0.0 ) { ZeroMatrix(); /* Singular Matrix */ return FALSE; } /* Normalize */ PValue = m_Coeff[i][Pivot]; for( j = 0; j < 4; j++ ) { m_Coeff[i][j] /= PValue; Mx.m_Coeff[i][j] /= PValue; } /* Zeroing */ for( j = 0; j < 4; j++ ) { if( j != i ) { PValue = m_Coeff[j][Pivot]; for( k = 0; k < 4; k++ ) { m_Coeff[j][k] -= PValue*m_Coeff[i][k]; Mx.m_Coeff[j][k] -= PValue*Mx.m_Coeff[i][k]; } } } } /* Reorder rows */ for( i = 0; i < 4; i++ ) { if( m_Coeff[i][i] != 1.0 ) { for( j = i + 1; j < 4; j++ ) if( m_Coeff[j][i] == 1.0 ) break; if( j >= 4 ) { ZeroMatrix(); return FALSE; } //--- swap rows i and j of original for( k = 0; k < 4; k++ ) { m_Coeff[i][k] += m_Coeff[j][k]; m_Coeff[j][k] = m_Coeff[i][k] - m_Coeff[j][k]; m_Coeff[i][k] -= m_Coeff[j][k]; } //--- swap rows i and j of result for( k = 0; k < 4; k++ ) { Mx.m_Coeff[i][k] += Mx.m_Coeff[j][k]; Mx.m_Coeff[j][k] = Mx.m_Coeff[i][k] - Mx.m_Coeff[j][k]; Mx.m_Coeff[i][k] -= Mx.m_Coeff[j][k]; } } } *this = Mx; return TRUE; } /* CDXMatrix4x4F::Invert */ inline void CDXMatrix4x4F::Transpose() { float temp; temp = m_Coeff[0][1]; m_Coeff[0][1] = m_Coeff[1][0]; m_Coeff[1][0] = temp; temp = m_Coeff[0][2]; m_Coeff[0][2] = m_Coeff[2][0]; m_Coeff[2][0] = temp; temp = m_Coeff[0][3]; m_Coeff[0][3] = m_Coeff[3][0]; m_Coeff[3][0] = temp; temp = m_Coeff[1][2]; m_Coeff[1][2] = m_Coeff[2][1]; m_Coeff[2][1] = temp; temp = m_Coeff[1][3]; m_Coeff[1][3] = m_Coeff[3][1]; m_Coeff[3][1] = temp; temp = m_Coeff[2][3]; m_Coeff[2][3] = m_Coeff[3][2]; m_Coeff[3][2] = temp; } /* CDXMatrix4x4F::Transpose */ inline void CDXMatrix4x4F::GetTranspose( CDXMatrix4x4F *m ) { float temp; (*this) = *m; temp = m_Coeff[0][1]; m_Coeff[0][1] = m_Coeff[1][0]; m_Coeff[1][0] = temp; temp = m_Coeff[0][2]; m_Coeff[0][2] = m_Coeff[2][0]; m_Coeff[2][0] = temp; temp = m_Coeff[0][3]; m_Coeff[0][3] = m_Coeff[3][0]; m_Coeff[3][0] = temp; temp = m_Coeff[1][2]; m_Coeff[1][2] = m_Coeff[2][1]; m_Coeff[2][1] = temp; temp = m_Coeff[1][3]; m_Coeff[1][3] = m_Coeff[3][1]; m_Coeff[3][1] = temp; temp = m_Coeff[2][3]; m_Coeff[2][3] = m_Coeff[3][2]; m_Coeff[3][2] = temp; } /* CDXMatrix4x4F::Transpose */ /* Matrix Inversion by Richard Carling from "Graphics Gems", Academic Press, 1990 */ #define SMALL_NUMBER 1.e-8 /* * inverse( original_matrix, inverse_matrix ) * * calculate the inverse of a 4x4 matrix * * -1 * A = ___1__ adjoint A * det A */ inline BOOL CDXMatrix4x4F::GetInverse( CDXMatrix4x4F *pIn ) { int i, j; float det; /* calculate the adjoint matrix */ GetAdjoint( pIn ); /* calculate the 4x4 determinant * if the determinant is zero, * then the inverse matrix is not unique. */ det = det4x4( pIn ); if( fabs( det ) < SMALL_NUMBER ) { // Non-singular matrix, no inverse! return FALSE;; } /* scale the adjoint matrix to get the inverse */ for( i = 0; i < 4; i++ ) for( j = 0; j < 4; j++ ) m_Coeff[i][j] = m_Coeff[i][j] / det; return TRUE; } /* * adjoint( original_matrix, inverse_matrix ) * * calculate the adjoint of a 4x4 matrix * * Let a denote the minor determinant of matrix A obtained by * ij * * deleting the ith row and jth column from A. * * i+j * Let b = (-1) a * ij ji * * The matrix B = (b ) is the adjoint of A * ij */ inline void CDXMatrix4x4F::GetAdjoint( CDXMatrix4x4F *pIn ) { float a1, a2, a3, a4, b1, b2, b3, b4; float c1, c2, c3, c4, d1, d2, d3, d4; /* assign to individual variable names to aid */ /* selecting correct values */ a1 = pIn->m_Coeff[0][0]; b1 = pIn->m_Coeff[0][1]; c1 = pIn->m_Coeff[0][2]; d1 = pIn->m_Coeff[0][3]; a2 = pIn->m_Coeff[1][0]; b2 = pIn->m_Coeff[1][1]; c2 = pIn->m_Coeff[1][2]; d2 = pIn->m_Coeff[1][3]; a3 = pIn->m_Coeff[2][0]; b3 = pIn->m_Coeff[2][1]; c3 = pIn->m_Coeff[2][2]; d3 = pIn->m_Coeff[2][3]; a4 = pIn->m_Coeff[3][0]; b4 = pIn->m_Coeff[3][1]; c4 = pIn->m_Coeff[3][2]; d4 = pIn->m_Coeff[3][3]; /* row column labeling reversed since we transpose rows & columns */ m_Coeff[0][0] = det3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4); m_Coeff[1][0] = - det3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4); m_Coeff[2][0] = det3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4); m_Coeff[3][0] = - det3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4); m_Coeff[0][1] = - det3x3( b1, b3, b4, c1, c3, c4, d1, d3, d4); m_Coeff[1][1] = det3x3( a1, a3, a4, c1, c3, c4, d1, d3, d4); m_Coeff[2][1] = - det3x3( a1, a3, a4, b1, b3, b4, d1, d3, d4); m_Coeff[3][1] = det3x3( a1, a3, a4, b1, b3, b4, c1, c3, c4); m_Coeff[0][2] = det3x3( b1, b2, b4, c1, c2, c4, d1, d2, d4); m_Coeff[1][2] = - det3x3( a1, a2, a4, c1, c2, c4, d1, d2, d4); m_Coeff[2][2] = det3x3( a1, a2, a4, b1, b2, b4, d1, d2, d4); m_Coeff[3][2] = - det3x3( a1, a2, a4, b1, b2, b4, c1, c2, c4); m_Coeff[0][3] = - det3x3( b1, b2, b3, c1, c2, c3, d1, d2, d3); m_Coeff[1][3] = det3x3( a1, a2, a3, c1, c2, c3, d1, d2, d3); m_Coeff[2][3] = - det3x3( a1, a2, a3, b1, b2, b3, d1, d2, d3); m_Coeff[3][3] = det3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3); } /* * float = det4x4( matrix ) * * calculate the determinant of a 4x4 matrix. */ inline float det4x4( CDXMatrix4x4F *pIn ) { float ans; float a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; /* assign to individual variable names to aid selecting */ /* correct elements */ a1 = pIn->m_Coeff[0][0]; b1 = pIn->m_Coeff[0][1]; c1 = pIn->m_Coeff[0][2]; d1 = pIn->m_Coeff[0][3]; a2 = pIn->m_Coeff[1][0]; b2 = pIn->m_Coeff[1][1]; c2 = pIn->m_Coeff[1][2]; d2 = pIn->m_Coeff[1][3]; a3 = pIn->m_Coeff[2][0]; b3 = pIn->m_Coeff[2][1]; c3 = pIn->m_Coeff[2][2]; d3 = pIn->m_Coeff[2][3]; a4 = pIn->m_Coeff[3][0]; b4 = pIn->m_Coeff[3][1]; c4 = pIn->m_Coeff[3][2]; d4 = pIn->m_Coeff[3][3]; ans = a1 * det3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4 ) - b1 * det3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4 ) + c1 * det3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4 ) - d1 * det3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4 ); return ans; } /* * float = det3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3 ) * * calculate the determinant of a 3x3 matrix * in the form * * | a1, b1, c1 | * | a2, b2, c2 | * | a3, b3, c3 | */ inline float det3x3( float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3 ) { float ans; ans = a1 * det2x2( b2, b3, c2, c3 ) - b1 * det2x2( a2, a3, c2, c3 ) + c1 * det2x2( a2, a3, b2, b3 ); return ans; } /* * float = det2x2( float a, float b, float c, float d ) * * calculate the determinant of a 2x2 matrix. */ inline float det2x2( float a, float b, float c, float d ) { float ans = a * d - b * c; return ans; } inline HRESULT CDXMatrix4x4F::InitFromSafeArray( SAFEARRAY * /*pSA*/ ) { HRESULT hr = S_OK; #if 0 long *pData; if( !pSA || ( pSA->cDims != 1 ) || ( pSA->cbElements != sizeof(float) ) || ( pSA->rgsabound->lLbound != 1 ) || ( pSA->rgsabound->cElements != 8 ) ) { hr = E_INVALIDARG; } else { hr = SafeArrayAccessData(pSA, (void **)&pData); if( SUCCEEDED( hr ) ) { for( int i = 0; i < 4; ++i ) { m_Bounds[i].Min = pData[i]; m_Bounds[i].Max = pData[i+4]; m_Bounds[i].SampleRate = SampleRate; } hr = SafeArrayUnaccessData( pSA ); } } #endif return hr; } /* CDXMatrix4x4F::InitFromSafeArray */ inline HRESULT CDXMatrix4x4F::GetSafeArray( SAFEARRAY ** /*ppSA*/ ) const { HRESULT hr = S_OK; #if 0 SAFEARRAY *pSA; if( !ppSA ) { hr = E_POINTER; } else { SAFEARRAYBOUND rgsabound; rgsabound.lLbound = 1; rgsabound.cElements = 16; if( !(pSA = SafeArrayCreate( VT_I4, 1, &rgsabound ) ) ) { hr = E_OUTOFMEMORY; } else { long *pData; hr = SafeArrayAccessData( pSA, (void **)&pData ); if( SUCCEEDED( hr ) ) { for( int i = 0; i < 4; ++i ) { pData[i] = m_Bounds[i].Min; pData[i+4] = m_Bounds[i].Max; } hr = SafeArrayUnaccessData( pSA ); } } if( SUCCEEDED( hr ) ) { *ppSA = pSA; } } #endif return hr; } /* CDXMatrix4x4F::GetSafeArray */ inline void CDXMatrix4x4F::TransformBounds( DXBNDS& /*Bnds*/, DXBNDS& /*ResultBnds*/ ) { } /* CDXMatrix4x4F::TransformBounds */ #endif // DXVector_h
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
8958f4e9dfaf2bf97ec8d9f46749ea5ad7f28159
e2dfcf0d5f88b5c5d0fb93add9a34fbbcd0739e4
/LCA/main.cpp
f06e8edc2e0551cc0fa96b9bba75100c3c0d83f0
[]
no_license
MihailoMilenkovic/competitive-programming-templates
a05a04d5f9af837d9ce6f359ff8e3a2af978ffcb
9f1c17680f04a871aa6211ca9213030b923a9a32
refs/heads/master
2022-11-29T17:20:55.220729
2020-07-30T17:27:05
2020-07-30T17:27:05
219,322,450
1
1
null
null
null
null
UTF-8
C++
false
false
1,642
cpp
#include <bits/stdc++.h> using namespace std; const int N=2e5+5; const int LOGN=30; vector<int>g[N]; int n,q,dep[N]; int par[N][LOGN]; void dfs(int x,int d){ dep[x]=d; for(auto&y:g[x]){ if(dep[y]==-1){ dfs(y,d+1); par[y][0]=x; } } } void preprocess(){ for(int lv=1;lv<LOGN;lv++){ for(int i=1;i<=n;i++){ if(par[i][lv-1]!=-1){ par[i][lv]=par[par[i][lv-1]][lv-1]; } } } } int lca(int x,int y){ if(dep[x]<dep[y]){ swap(x,y); } int diff=dep[x]-dep[y]; for(int i=LOGN-1;i>=0;i--){ if(diff&(1<<i)){ x=par[x][i]; } } if(x==y){ return x; } for(int i=LOGN-1;i>=0;i--){ if(par[x][i]!=par[y][i]){ x=par[x][i]; y=par[y][i]; } } return par[x][0]; } int main() { scanf("%d%d",&n,&q); for(int i=0;i<N;i++){ dep[i]=-1; for(int j=0;j<LOGN;j++){ par[i][j]=-1; } } for(int i=1;i<n;i++){ int x,y; scanf("%d%d",&x,&y); g[x].push_back(y); g[y].push_back(x); } dfs(1,0); preprocess(); for(int i=1;i<=q;i++){ int x,y; scanf("%d%d",&x,&y); printf("%d\n",x,y,lca(x,y)); } /*for(int i=1;i<=n;i++){ for(int j=0;j<=3;j++){ printf("par[%d][%d]:%d\n",i,j,par[i][j]); } }*/ /*for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ printf("lca(%d,%d):%d\n",i,j,lca(i,j)); } }*/ return 0; } /* 8 1 1 2 1 3 2 4 2 5 2 6 3 7 3 8 1 8 4 7 4 6 */
[ "mihailo.milenkovic4@gmail.com" ]
mihailo.milenkovic4@gmail.com
515e0fe7ada641cfa8697baf6f0707696ed0e359
6e033c2e2a99f2b3a4185aa871087d08c8d6970e
/Servo/RightServoClockwise/RightServoClockwise.ino
9e8009f3863f26bdd84e41e4fa5bdcc17120ff2b
[]
no_license
jstitch/arduino_BOEShield
0ca4593f7c04821ffacdcee49bfc83ae66b2ac54
89060a124e98bef58c04d9041065953caace493b
refs/heads/master
2021-07-12T08:44:17.092341
2017-10-07T02:16:30
2017-10-14T00:02:13
105,387,616
0
0
null
null
null
null
UTF-8
C++
false
false
136
ino
#include <Servo.h> Servo servoRight; void setup() { servoRight.attach(12); servoRight.writeMicroseconds(1700); } void loop() { }
[ "jstitch@gmail.com" ]
jstitch@gmail.com
9668923866c74b9f3695c2fae4cf5685229673cc
f4e881c66d279b6c0271d5f11272050a19f0129b
/LearnOpenGL/LearnOpenGL/includes/learnopengl/filesystem.h
e90fd3946f8296af704858d450066d5bf03e8c5b
[ "Apache-2.0" ]
permissive
jiahaodev/OpenGL
9e2c21080e4a595493a000ab0cbcb98e892ca38b
6e6e690b366d3adeefd35e2e9d5c4637353d35e3
refs/heads/master
2020-03-29T22:27:14.118696
2020-03-16T03:02:18
2020-03-16T03:02:18
150,421,482
0
0
null
null
null
null
UTF-8
C++
false
false
1,311
h
#ifndef FILESYSTEM_H #define FILESYSTEM_H #include <string> #include <cstdlib> #include "root_directory.h" // This is a configuration file generated by CMake. class FileSystem { private: typedef std::string (*Builder) (const std::string& path); public: static std::string getPath(const std::string& path) { static std::string(*pathBuilder)(std::string const &) = getPathBuilder(); return (*pathBuilder)(path); } private: static std::string const & getRoot() { char *envRoot; size_t len; errno_t err = _dupenv_s(&envRoot, &len, "LOGL_ROOT_PATH"); //static char const * envRoot = _dupenv_s("LOGL_ROOT_PATH"); static char const * givenRoot = (envRoot != nullptr ? envRoot : logl_root); static std::string root = (givenRoot != nullptr ? givenRoot : ""); return root; } //static std::string(*foo (std::string const &)) getPathBuilder() static Builder getPathBuilder() { if (getRoot() != "") return &FileSystem::getPathRelativeRoot; else return &FileSystem::getPathRelativeBinary; } static std::string getPathRelativeRoot(const std::string& path) { return getRoot() + std::string("/") + path; } static std::string getPathRelativeBinary(const std::string& path) { return "../../../" + path; } }; // FILESYSTEM_H #endif
[ "jiahaowu@boyaa.com" ]
jiahaowu@boyaa.com
0b10d0839e7015211f748970abd70c845c268e1f
3f4f844928dfe595b0b128c39833dfe94fd9a8fc
/basics/OpenDisplayImage.cpp
0dd885500aae0a1e079bd070c3bdeb1c83c4e2fe
[]
no_license
PhilTKamp/OpenCVTesting
2e06f69c9961fb42ac763d74edb5d31450e75be1
03fa584079c6087d71fb7a7c21497039a0fca1f5
refs/heads/master
2020-03-28T14:43:32.589050
2018-09-12T20:19:19
2018-09-12T20:19:19
148,515,650
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
#include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <string> using namespace cv; using namespace std; int main(int argc, char** argv) { String imagePath = "./lena.jpg"; if( argc > 1 ) { imagePath = argv[1]; } Mat image; image = imread(imagePath, IMREAD_COLOR); if ( image.empty() ) { cout << "Unable to open or read image" << endl; return -1; } namedWindow("Display Window", WINDOW_AUTOSIZE); imshow("Display Window", image); waitKey(0); return 0; }
[ "philip.telkamp@mines.sdsmt.edu" ]
philip.telkamp@mines.sdsmt.edu
38acfd78e68166473945c5c84ce7022b240687b1
fe2362eda423bb3574b651c21ebacbd6a1a9ac2a
/VTK-7.1.1/Infovis/Core/vtkExtractSelectedTree.cxx
923ffc662a4d06aa994666c57f1b978a529c48ac
[ "BSD-3-Clause" ]
permissive
likewatchk/python-pcl
1c09c6b3e9de0acbe2f88ac36a858fe4b27cfaaf
2a66797719f1b5af7d6a0d0893f697b3786db461
refs/heads/master
2023-01-04T06:17:19.652585
2020-10-15T21:26:58
2020-10-15T21:26:58
262,235,188
0
0
NOASSERTION
2020-05-08T05:29:02
2020-05-08T05:29:01
null
UTF-8
C++
false
false
7,888
cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedTree.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkExtractSelectedTree.h" #include "vtkCellData.h" #include "vtkInformation.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTree.h" #include "vtkIdTypeArray.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkConvertSelection.h" #include "vtkEdgeListIterator.h" #include "vtkNew.h" #include <map> vtkStandardNewMacro(vtkExtractSelectedTree); vtkExtractSelectedTree::vtkExtractSelectedTree() { this->SetNumberOfInputPorts(2); } vtkExtractSelectedTree::~vtkExtractSelectedTree() { } //---------------------------------------------------------------------------- void vtkExtractSelectedTree::SetSelectionConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(1, in); } //---------------------------------------------------------------------------- int vtkExtractSelectedTree::FillInputPortInformation(int port, vtkInformation *info) { if(port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTree"); return 1; } else if(port == 1) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkExtractSelectedTree::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //---------------------------------------------------------------------------- int vtkExtractSelectedTree::BuildTree( vtkTree * inputTree, vtkIdTypeArray * selectedVerticesList, vtkMutableDirectedGraph * builder ) { // Get the input and builder vertex and edge data. vtkDataSetAttributes * inputVertexData = inputTree->GetVertexData(); vtkDataSetAttributes * inputEdgeData = inputTree->GetEdgeData(); vtkDataSetAttributes * builderVertexData = builder->GetVertexData(); vtkDataSetAttributes * builderEdgeData = builder->GetEdgeData(); builderVertexData->CopyAllocate(inputVertexData); builderEdgeData->CopyAllocate(inputEdgeData); //Add selected vertices and set up a map between the input tree vertex id //and the output tree vertex id std::map<vtkIdType, vtkIdType> vertexMap; for (vtkIdType j = 0; j < selectedVerticesList->GetNumberOfTuples();j++) { vtkIdType inVert = selectedVerticesList->GetValue(j); vtkIdType outVert = builder->AddVertex(); builderVertexData->CopyData(inputVertexData, inVert, outVert); vertexMap[inVert] = outVert; } // Add edges connecting selected vertices vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); inputTree->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if (vertexMap.find(e.Source) != vertexMap.end() && vertexMap.find(e.Target) != vertexMap.end()) { vtkIdType source = vertexMap[e.Source]; vtkIdType target = vertexMap[e.Target]; vtkEdgeType f = builder->AddEdge(source, target); builderEdgeData->CopyData(inputEdgeData, e.Id, f.Id); vtkIdType npts; double* pts; inputTree->GetEdgePoints(e.Id, npts, pts); builder->SetEdgePoints(f.Id, npts, pts); } } return 1; } int vtkExtractSelectedTree::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkTree * inputTree = vtkTree::GetData(inputVector[0]); vtkSelection * selection = vtkSelection::GetData(inputVector[1]); vtkTree * outputTree = vtkTree::GetData(outputVector); if(!selection) { vtkErrorMacro("No vtkSelection provided as input."); return 0; } //obtain a vertex selection list from the input vtkSelection // Convert the selection to an INDICES selection vtkSmartPointer<vtkSelection> converted; converted.TakeReference(vtkConvertSelection::ToIndexSelection(selection, inputTree)); if (!converted.GetPointer()) { vtkErrorMacro("Selection conversion to INDICES failed."); return 0; } vtkNew<vtkIdTypeArray> selectedVerticesList; for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i) { vtkSelectionNode * node = converted->GetNode(i); // Append the selectedVerticesList vtkIdTypeArray * curList = vtkArrayDownCast<vtkIdTypeArray>(node->GetSelectionList()); if (curList) { int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE()); if (inverse) {//selection is to be removed if (node->GetFieldType() == vtkSelectionNode::VERTEX) {//keep all the other vertices vtkIdType num = inputTree->GetNumberOfVertices(); for (vtkIdType j = 0; j < num; ++j) { if (curList->LookupValue(j) < 0 && selectedVerticesList->LookupValue(j) < 0) { selectedVerticesList->InsertNextValue(j); } } } else if (node->GetFieldType() == vtkSelectionNode ::EDGE) {// keep all the other edges vtkIdType num = inputTree->GetNumberOfEdges(); for (vtkIdType j = 0; j < num; ++j) { if (curList->LookupValue(j) < 0 ) { vtkIdType s = inputTree->GetSourceVertex(j); vtkIdType t = inputTree->GetTargetVertex(j); if (selectedVerticesList->LookupValue(s) < 0) { selectedVerticesList->InsertNextValue(s); } if (selectedVerticesList->LookupValue(t) < 0) { selectedVerticesList->InsertNextValue(t); } } } } }// end of if(!inverse) else {//selection is to be extracted vtkIdType numTuples = curList->GetNumberOfTuples(); for (vtkIdType j = 0; j < numTuples; ++j) { if (node->GetFieldType() == vtkSelectionNode::VERTEX ) { vtkIdType curVertexId = curList->GetValue(j); if (selectedVerticesList->LookupValue(curVertexId) < 0) { selectedVerticesList->InsertNextValue(curVertexId); } } else if (node->GetFieldType() == vtkSelectionNode::EDGE) {//if an edge is selected to be extracted, //keep both source and target vertices vtkIdType curEdgeId = curList->GetValue(j); vtkIdType t = inputTree->GetTargetVertex(curEdgeId); vtkIdType s = inputTree->GetSourceVertex(curEdgeId); if (selectedVerticesList->LookupValue(s) < 0) { selectedVerticesList->InsertNextValue(s); } if (selectedVerticesList->LookupValue(t) < 0) { selectedVerticesList->InsertNextValue(t); } } } } } // end if (curList) } // end for each selection node vtkNew<vtkMutableDirectedGraph> builder; // build the tree recursively this->BuildTree(inputTree, selectedVerticesList.GetPointer(), builder.GetPointer()); // Copy the structure into the output. if (!outputTree->CheckedShallowCopy(builder.GetPointer())) { vtkErrorMacro( <<"Invalid tree structure." << outputTree->GetNumberOfVertices()); return 0; } return 1; }
[ "likewatchk@gmail.com" ]
likewatchk@gmail.com
3b091579e3608f47d09688ace8979a503e23e21b
d5a2b525bf38c84f3199f7eec0142cc817c4f24f
/include/ros_lib/rospy_tutorials/BadTwoInts.h
0af8a83fc3920b6074506e5052aee9eb69b0c3ce
[]
no_license
msoe-vex/V5HAL
f3bf135d6878a450b020726e2c3b59fe93de112f
035ae322eb6d37e5207b9b955a0d34f102d33ec7
refs/heads/master
2023-02-04T21:12:57.892960
2020-11-04T23:27:17
2020-11-04T23:27:17
295,019,922
0
0
null
null
null
null
UTF-8
C++
false
false
4,601
h
#ifndef _ROS_SERVICE_BadTwoInts_h #define _ROS_SERVICE_BadTwoInts_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros_lib/ros/msg.h" namespace rospy_tutorials { static const char BADTWOINTS[] = "rospy_tutorials/BadTwoInts"; class BadTwoIntsRequest : public ros::Msg { public: typedef int64_t _a_type; _a_type a; typedef int32_t _b_type; _b_type b; BadTwoIntsRequest(): a(0), b(0) { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; union { int64_t real; uint64_t base; } u_a; u_a.real = this->a; *(outbuffer + offset + 0) = (u_a.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_a.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_a.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_a.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_a.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_a.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_a.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_a.base >> (8 * 7)) & 0xFF; offset += sizeof(this->a); union { int32_t real; uint32_t base; } u_b; u_b.real = this->b; *(outbuffer + offset + 0) = (u_b.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_b.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_b.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_b.base >> (8 * 3)) & 0xFF; offset += sizeof(this->b); return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; union { int64_t real; uint64_t base; } u_a; u_a.base = 0; u_a.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_a.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_a.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_a.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_a.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_a.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_a.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_a.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->a = u_a.real; offset += sizeof(this->a); union { int32_t real; uint32_t base; } u_b; u_b.base = 0; u_b.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_b.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_b.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_b.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->b = u_b.real; offset += sizeof(this->b); return offset; } virtual const char * getType() override { return BADTWOINTS; }; virtual const char * getMD5() override { return "29bb5c7dea8bf822f53e94b0ee5a3a56"; }; }; class BadTwoIntsResponse : public ros::Msg { public: typedef int32_t _sum_type; _sum_type sum; BadTwoIntsResponse(): sum(0) { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; union { int32_t real; uint32_t base; } u_sum; u_sum.real = this->sum; *(outbuffer + offset + 0) = (u_sum.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_sum.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_sum.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_sum.base >> (8 * 3)) & 0xFF; offset += sizeof(this->sum); return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; union { int32_t real; uint32_t base; } u_sum; u_sum.base = 0; u_sum.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->sum = u_sum.real; offset += sizeof(this->sum); return offset; } virtual const char * getType() override { return BADTWOINTS; }; virtual const char * getMD5() override { return "0ba699c25c9418c0366f3595c0c8e8ec"; }; }; class BadTwoInts { public: typedef BadTwoIntsRequest Request; typedef BadTwoIntsResponse Response; }; } #endif
[ "nathan.dupont01@gmail.com" ]
nathan.dupont01@gmail.com
c5d4e5b1394920f6070ad2754737fd88c0595bf2
0d6574b6f7b90007eac00e6dcfd4463de072bd82
/arduino/libs/local/app.hh
8bc31fb19729517c1d350a5a72688ddcff767819
[]
no_license
psycofdj/burger-quiz
c83c685e3235c632e663cb0522b6e7651befed9b
6b562cf83865d0526602700fc94fe74e425af685
refs/heads/master
2022-11-19T01:09:39.089752
2020-07-14T14:36:00
2020-07-14T14:36:00
269,616,892
0
0
null
null
null
null
UTF-8
C++
false
false
3,997
hh
#pragma once #include "common.hh" #include "serial.hh" #include "light.hh" #include "button.hh" #include "buzzer.hh" class App : public Updatable { public: static const duration_t mcsBuzzTime = 6000; enum state { loading = -2, idle = -1, mayo = 2, ketchup = 3, }; private: App(void): mLastTime(0), mState(state::loading), mTargetState(state::idle), mLastWinner(0), mBuzzerMayo(id::d2), mBuzzerKetchup(id::d3), mBlueLED(id::d7), mGreenLED(id::d6), mRedLamp(id::d5), mYellowLamp(id::d4), mButtons({ Button(id::d8), Button(id::d9), Button(id::d10), Button(id::d11), Button(id::d12), Button(id::d13) }) { for (std::size_t cIdx = 0; cIdx < 6; cIdx++) { mButtons[cIdx].onPressed([cIdx]{ std::sout << "button" << cIdx << "::pressed" << std::endl; }); mButtons[cIdx].onReleased([cIdx]{ std::sout << "button" << cIdx << "::released" << std::endl; }); } mBuzzerMayo.onTriggered([this](void) { this->onBuzzerPressed(App::state::mayo); }); mBuzzerKetchup.onTriggered([this](void) { this->onBuzzerPressed(App::state::ketchup); }); } public: static App& get(void) { if (App::msInstance == 0) { App::msInstance = new App(); } return *App::msInstance; } public: void setup(void) { initialize(); negociate(); ready(); } void initialize(void) { gSerial.begin(9600); ArduinoSTL_Serial.connect(gSerial); std::sout << "app::initialize" << std::endl; mGreenLED.on(); } void negociate(void) { std::sout << "app::negociating" << std::endl; char l_buf[16] = { 0x0 }; std::sin.read(l_buf, 15); std::string l_value(l_buf, 13); if (l_value != "client::ready") { std::sout << "unexpected client message: [" << l_value << "]" << std::endl; exit(1); } } void ready(void) { std::sout << "app::ready" << std::endl; mBlueLED.on(); mState = state::idle; mTargetState = idle; mLastTime = millis(); } void loop(void) { time_t lNow = millis(); duration_t lDelta = lNow - mLastTime; mLastTime = lNow; update(lNow, lDelta); mGreenLED.update(lNow, lDelta); mBlueLED.update(lNow, lDelta); for (std::size_t cIdx = 0; cIdx < 5; cIdx++) { mButtons[cIdx].update(lNow, lDelta); } } void update(time_t /* pTime */, duration_t /* pDuration */) override { if (mState != state::idle) { if (mLastTime - mLastWinner > mcsBuzzTime) { reset(); } } else if (mTargetState != mState) { winner(); } } void winner(void) { mState = mTargetState; switch (mState) { case state::mayo: std::sout << "buzzer::mayo" << std::endl; mYellowLamp.on(); break; case state::ketchup: std::sout << "buzzer::ketchup" << std::endl; mRedLamp.on(); break; case state::loading: case state::idle: break; } } void reset(void) { std::sout << "app::reset" << std::endl; flash(25); mState = state::idle; mTargetState = state::idle; mRedLamp.off(); mYellowLamp.off(); } void flash(duration_t pSpeed = 150) { for (size_t cIdx = 0; cIdx < 10; cIdx++) { mGreenLED.off(); mBlueLED.off(); delay(pSpeed); mGreenLED.on(); mBlueLED.on(); delay(pSpeed); } } void onBuzzerPressed(state pState) { if ((mState == state::idle) && (mTargetState == state::idle)) { std::sout << "buzzer::pressed" << std::endl; mTargetState = pState; mLastWinner = mLastTime; } } private: time_t mLastTime; state mState; state mTargetState; time_t mLastWinner; Buzzer mBuzzerMayo; Buzzer mBuzzerKetchup; Light mBlueLED; Light mGreenLED; Light mRedLamp; Light mYellowLamp; Button mButtons[6]; private: static App* msInstance; }; App* App::msInstance = 0;
[ "xavier@marcelet.com" ]
xavier@marcelet.com
4b39eaa2b403ae5abd5916755343b9469ecf469c
b6a4701da2ff5a3a9d5a37fa166f14ecfd7ab8f7
/Graph/Operator/MCTensorProduct.hpp
81c8b073aaf1581c15f1c6ca7c09c3c1ff4f5846
[]
no_license
jungla88/SPARE
de7b331081edb2102f291b9278e666b65cd4bf43
acb29cd9fa75d5c52a4f9ac2d13b1fdb2aabb2c1
refs/heads/master
2022-04-18T05:38:22.042943
2020-04-09T14:05:28
2020-04-09T14:05:28
254,387,791
0
0
null
null
null
null
UTF-8
C++
false
false
10,463
hpp
// MCTensorProduct class, part of the SPARE library. // Copyright (C) 2011 Lorenzo Livi // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** @brief File MCTensorProduct.hpp, that contains the tensor product class. * * Contains the declaration of the Multicore TensorProduct class. * It is a multi-threaded version of the standard tensor product computation, using a user-defined number of threads. * * @file MCTensorProduct.hpp * @author Lorenzo Livi */ #ifndef MCTENSORPRODUCT_HPP #define MCTENSORPRODUCT_HPP //STD INCLUDES #include <vector> //BOOST INCLUDES #include <boost/numeric/ublas/matrix.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> //SPARE INCLUDES #include <spare/SpareTypes.hpp> namespace spare { // Inclusione in namespace spare. /** @brief Multicore computation of the tensor product between two labeled graphs. * * This class implements the @a Operator concept of the graphs domain (i.e., an operator between graphs). * It contains two main types of interfaces: the first one uses object references, the second one uses pointers (mainly for multi-threading). * The number of threads is configurable by the user in the third template argument. */ template <class KernelType, class MatrixRepresentation, NaturalType NThreads> class MCTensorProduct { public: /** * Tensor product computation. * No explicit output tensor product matrix computation, and allocation, is performed. * * @param[in] g1 A reference to the first graph * @param[in] g2 A reference to the second graph * @return The weight of the tensor product graph. */ template <class GraphType> RealType product(const GraphType& g1, const GraphType& g2) const; /** * Tensor product computation using pointers instead of references in the interface (for threads compliance). * No explicit output tensor product matrix computation is performed. * * @param[in] g1 A pointer to the first graph * @param[in] g2 A pointer to the second graph * @param[out] weight A pointer to the weight of the tensor product graph */ template <class GraphType> void product(const GraphType* g1, const GraphType* g2, RealType* weight) const; /** * Read/Write access to the main kernel function */ KernelType& KernelAgent() { return kernel; } /** * Read-only access to the main kernel function */ const KernelType& KernelAgent() const { return kernel; } /** * Read/Write access to the matrix representation for the graph */ MatrixRepresentation& RepresentationAgent() { return mr; } /** * Read-only access to the matrix representation for the graph */ const MatrixRepresentation& RepresentationAgent() const { return mr; } /** * Read-only access to the number of threads */ const NaturalType& ThreadsAgent() const { return NThreads; } private: /** * Thread function for block-matrix weight computation * @param[in] g1 A pointer to the first graph * @param[in] g2 A pointer to the second graph * @param[in] m1 A pointer to the first adjacency matrix * @param[in] m2 A pointer to the second adjacency matrix * @param[in] pos * @param[in] g2Order * @param[out] weight */ template <class GraphType> void threadProduct(const GraphType* g1, const GraphType* g2, const boost::numeric::ublas::matrix<RealType>* m1, const boost::numeric::ublas::matrix<RealType>* m2, const NaturalType* pos, const NaturalType g2Order, RealType* weight) const; /** * Main composite kernel function */ KernelType kernel; /** * Matrix representation for the graph */ MatrixRepresentation mr; //mutex mutable boost::mutex boostMutex; }; //IMPL template <class KernelType, class MatrixRepresentation, NaturalType NThreads> template <class GraphType> void MCTensorProduct<KernelType, MatrixRepresentation, NThreads>::product(const GraphType* g1, const GraphType* g2, RealType* weight) const { *weight=product(*g1, *g2); } template <class KernelType, class MatrixRepresentation, NaturalType NThreads> template <class GraphType> RealType MCTensorProduct<KernelType, MatrixRepresentation, NThreads>::product(const GraphType& g1, const GraphType& g2) const { NaturalType o1=boost::num_vertices(g1); NaturalType o2=boost::num_vertices(g2); std::vector<NaturalType*> t; NaturalType rStart, rEnd, cStart, cEnd, block, tot, totThreads; //the weight of the tensor product graph RealType weight=0.; //matrix representations of the two input graphs boost::numeric::ublas::matrix<RealType> m1(o1, o1), m2(o2, o2); //threads boost::thread_group threadGroup; if(NThreads>o1) totThreads=o1; else totThreads=NThreads; //matrix representations of the graphs mr.getMatrix(g1, m1); mr.getMatrix(g2, m2); //compute tasks subdivision tot=o1*o1; block=tot/totThreads; RealType v=(RealType)block/(RealType)o1; NaturalType flooredRows=floor(v); NaturalType ceiledRows=ceil(v); //oldCEnd is equal to the next cStart NaturalType oldCEnd=0, rowsShift=0; // std::cout<<std::endl<<"Threads: "<<NThreads<<std::endl; // std::cout<<"Tot: "<<tot<<std::endl; // std::cout<<"BLock: "<<block<<std::endl; //threads dispatching for(NaturalType i=0;i<totThreads;i++) { // std::cout<<std::endl<<"T: "<<i<<std::endl; // std::cout<<"FLOORED blocks/o1: "<<flooredRows<<std::endl; // std::cout<<"CEILED blocks/o1: "<<ceiledRows<<std::endl; // std::cout<<"ROWS SHIFT: "<<rowsShift<<std::endl; // std::cout<<"Old cEnd: "<<oldCEnd<<std::endl; //TODO: il bug sembra essere risolto, ma e' sempre meglio fare ulteriori verifiche... rStart=i*flooredRows+rowsShift; rEnd=rStart+ceiledRows; cStart=oldCEnd; cEnd=block-(((rEnd-rStart)-1)*o1)+oldCEnd; //bounds check if(rEnd>o1) rEnd=o1; if(cEnd>o1) cEnd=o1; //next column start if(cEnd>=o1) oldCEnd=0; else oldCEnd=cEnd; //the next start row is incremented by 1 if(cStart!=0&&cEnd==o1) rowsShift++; if(i==totThreads-1) { rEnd=o1; cEnd=o1; } // std::cout<<"Row Start: "<<rStart<<std::endl; // std::cout<<"Row End (excluded): "<<rEnd<<std::endl; // std::cout<<"Col Start: "<<cStart<<std::endl; // std::cout<<"Col End (excluded): "<<cEnd<<std::endl; // std::cout<<"Old cEnd (next cStart): "<<oldCEnd<<std::endl<<std::endl; //dynamic positions buffer NaturalType* pos=new NaturalType[5]; pos[0]=rStart; pos[1]=rEnd; pos[2]=cStart; pos[3]=cEnd; pos[4]=o1; t.push_back(pos); //new thread threadGroup.add_thread(new boost::thread( boost::bind(&MCTensorProduct::threadProduct<GraphType>, this, &g1, &g2, &m1, &m2, pos, o2, &weight))); } threadGroup.join_all(); //free dynamic positions buffer for(NaturalType i=0;i<totThreads;i++) delete t[i]; return weight; } template <class KernelType, class MatrixRepresentation, NaturalType NThreads> template <class GraphType> void MCTensorProduct<KernelType, MatrixRepresentation, NThreads>::threadProduct( const GraphType* g1, const GraphType* g2, const boost::numeric::ublas::matrix<RealType>* m1, const boost::numeric::ublas::matrix<RealType>* m2, const NaturalType* pos, const NaturalType g2Order, RealType* weight) const { //part of the weight computed by this thread RealType localWeight=0.; bool isFirst=true; NaturalType startColM1, endColM1=0; //fetch the assigne block of positions for(NaturalType rM1=pos[0]; rM1<pos[1]; rM1++) { // std::cout<<"RM1: "<<rM1<<std::endl; //g1 columns determination based on the current row rM1 if(isFirst) { isFirst=false; startColM1=pos[2]; } else startColM1=0; if(rM1==pos[1]-1) endColM1=pos[3]; else endColM1=pos[4]; // std::cout<<"START COL: "<<startColM1<<std::endl; // std::cout<<"END COL: "<<endColM1<<std::endl; for(NaturalType cM1=startColM1; cM1<endColM1; cM1++) { // std::cout<<"CM1: "<<cM1<<std::endl; if((*m1)(rM1, cM1)) { //data of g2 for(NaturalType rM2=0; rM2<g2Order; rM2++) { for(NaturalType cM2=0; cM2<g2Order; cM2++) { if((*m2)(rM2, cM2)) { localWeight+=kernel.Sim( boost::get(v_info_t(), *g1, boost::vertex(rM1, *g1)), boost::get(v_info_t(), *g2, boost::vertex(rM2, *g2)), boost::get(v_info_t(), *g1, boost::vertex(cM1, *g1)), boost::get(v_info_t(), *g2, boost::vertex(cM2, *g2)), boost::get(e_info_t(), *g1, boost::edge(rM1, cM1, *g1).first), boost::get(e_info_t(), *g2, boost::edge(rM2, cM2, *g2).first) ); } } } }//if } } //synchronized access to the weight boostMutex.lock(); *weight+=localWeight; boostMutex.unlock(); } } #endif /* MCTENSORPRODUCT_HPP */
[ "baldini.luca88@gmail.com" ]
baldini.luca88@gmail.com
439b38dda797c153d2912f49b701d0a7a9ec7cb6
048c7caa1bec12c17b0f073f96900a488c5d055b
/src/ukf.cpp
1b2e351821a20e1bd6d6afc320e3988b0badca36
[]
no_license
amahd/Unscented_Kalman_filter
e6621e32b15756176f8c7eac3c212e5f632320a6
9cdf3fb8a9619a6c8b57ff8474d26e5ea2df66a6
refs/heads/master
2020-12-02T17:43:17.403926
2017-07-06T11:16:32
2017-07-06T11:16:32
96,417,304
0
0
null
null
null
null
UTF-8
C++
false
false
12,534
cpp
#include "ukf.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Main constructor, initlaizing variable */ UKF::UKF() { /* default state of teh filter*/ is_initialized_ = false; /*Time stamp in microsecond*/ // time_us_ = 0; //state dimension for radar n_x_ = 5; //augmented state dimension for ladar to support unscented operation n_aug_ = 7; // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd(n_x_); // initial covariance matrix P_ = MatrixXd(n_x_, n_x_); // Process noise standard deviation (longitudinal acceleration in m/s^2) std_a_ = 4.80; //original: 30 is too high when compared with other vals // Process noise standard deviation (yaw acceleration in rad/s^2) std_yawdd_ = 2; //original: 30 is too too high // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //lambda spreading parameter for unscented operations lambda_ = 3 - n_x_; //Corresponding weights for UKF weights_ = VectorXd( (2 * n_aug_) + 1); /* Initial weight value is different */ weights_(0) = lambda_ / ( lambda_ + n_aug_ ); /* Rest of the weights from formula in notes*/ for (int i = 1; i<2 * n_aug_ + 1; i++) weights_(i) = 1 / (2 * (lambda_ + n_aug_)); // Prediction covariance matrix, can be initialised in constructor P_ << VAL, 0, 0, 0, 0, 0, VAL, 0, 0, 0, 0, 0, VAL*65, 0, 0, 0, 0, 0, VAL*65, 0, 0, 0, 0, 0, VAL*65; } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { /* If very first packet, then initialise */ if (!is_initialized_) { // Initialize the state ekf_.x_ x_ << 1, 1, 0, 0, 0; if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { // Use the first measurement to initialise UKF double range = meas_package.raw_measurements_[0]; //magnitude double phi = tools.NormAngle(meas_package.raw_measurements_[1]); //angle in radians, start a check on the initial value too double range_dot = meas_package.raw_measurements_[2]; //range rate double px = range * cos(phi); double py = range * sin(phi); double vx = range_dot * cos(phi); double vy = range_dot * sin(phi); double val = atan2(vy, vx); double phi_dot = tools.NormAngle(val); //if initial values are zero, start from non-zero values for faster convergence if (px == 0 || py == 0) { px = 0.001; py = 0.001; } x_ << px, py, 0, 0, 0; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER) { // Set state x_ to the first measurement. x_(0) = meas_package.raw_measurements_[0]; x_(1) = meas_package.raw_measurements_[1]; //if initial values are zero /*if (px == 0 && py == 0) { px = py = 0.001; } */ //x_ << px, py, 0, 0, 0; } /* save the first timestam as it is*/ timestamp_prev_ = meas_package.timestamp_; // done initializing is_initialized_ = true; return; } //End of first initialization /* If not first time then do normal KF Prediction and Update steps */ //compute the time elapsed between the current and previous measurements double delta_t = (meas_package.timestamp_ - timestamp_prev_) / 1000000.0; //dt - expressed in seconds timestamp_prev_ = meas_package.timestamp_; // make prediction of sigma points Prediction(delta_t); //update radar measurememt and state estimation if (meas_package.sensor_type_ == MeasurementPackage::RADAR && use_radar_) UpdateRadar(meas_package); //update laser measurememt and state estimation else if (meas_package.sensor_type_ == MeasurementPackage::LASER && use_laser_) UpdateLidar(meas_package); } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { /** Estimate the object's location. Modify the state vector, x_. Predict sigma points, the state, and the state covariance matrix. */ //First make required matrices for augmented space VectorXd x_aug = VectorXd(n_aug_); MatrixXd P_aug = MatrixXd(n_aug_, n_aug_); P_aug.setZero(); // initialize to 0 //sigma point matrix, 7 * 15 MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1); //augmented state x_aug.head(5) = x_; // take first 5 values from previous a posterioir state, rest are 0 x_aug(5) = 0; x_aug(6) = 0; //augmented P matrix P_aug.fill(0.0); P_aug.topLeftCorner<5, 5>() = P_; //fill the top left section P_aug(5,5) = std_a_*std_a_; P_aug(6,6) = std_yawdd_*std_yawdd_; //P_aug.bottomRightCorner<2, 2>() = Q; //State Matrix MatrixXd A = P_aug.llt().matrixL(); //augmented sigma points //set first column of sigma point matrix Xsig_aug.col(0) = x_aug; //set remaining sigma points for (int i = 0; i < n_aug_; i++){ Xsig_aug.col(i + 1) = x_aug + sqrt(lambda_ + n_aug_) * A.col(i); Xsig_aug.col(i + 1 + n_aug_) = x_aug - sqrt(lambda_ + n_aug_) * A.col(i); } //Augmented Sigma point prediction Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1); //predict sigma points for (int i = 0; i< 2 * n_aug_ + 1; i++){ //Obtaining individual Xaug elements double p_x = Xsig_aug(0, i); double p_y = Xsig_aug(1, i); double v = Xsig_aug(2, i); double yaw = Xsig_aug(3, i); double yawd = Xsig_aug(4, i); double nu_a = Xsig_aug(5, i); double nu_yawdd = Xsig_aug(6, i); double px_p, py_p; //predicted state values //avoid division by zero, code from lectures if (fabs(yawd) > 0.001) { px_p = p_x + v / yawd * (sin(yaw + yawd*delta_t) - sin(yaw)); py_p = p_y + v / yawd * (cos(yaw) - cos(yaw + yawd*delta_t)); } else { px_p = p_x + v*delta_t*cos(yaw); py_p = p_y + v*delta_t*sin(yaw); } double v_p = v; double yaw_p = yaw + yawd*delta_t; double yawd_p = yawd; //adding noise related parameters px_p = px_p + 0.5*nu_a*delta_t*delta_t * cos(yaw); py_p = py_p + 0.5*nu_a*delta_t*delta_t * sin(yaw); v_p = v_p + nu_a*delta_t; yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t; yawd_p = yawd_p + nu_yawdd*delta_t; //write predicted sigma point into right column Xsig_pred_(0, i) = px_p; Xsig_pred_(1, i) = py_p; Xsig_pred_(2, i) = v_p; Xsig_pred_(3, i) = yaw_p; Xsig_pred_(4, i) = yawd_p; } //end of the long for loop //predict state mean x_.fill(0.0); //iteratation with sigma points for (int i = 0; i < 2 * n_aug_ + 1; i++) x_ = x_ + weights_(i) * Xsig_pred_.col(i); //predicted state covariance matrix P_.fill(0.0); //iterate over sigma points for (int i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd x_diff = Xsig_pred_.col(i) - x_; // state difference x_diff(3) = tools.NormAngle(x_diff(3)); //Normalize angle before use P_ = P_ + weights_(i) * x_diff * x_diff.transpose(); //set the rest of Pmatrix with weights } } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { /** Use lidar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. Calculate the lidar NIS. */ // sensor state dimension int n_z = 2; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1); //transform sigma points into measurement space for (int i = 0; i < 2 * n_aug_ + 1; i++){ double p_x = Xsig_pred_(0, i); double p_y = Xsig_pred_(1, i); double v = Xsig_pred_(2, i); double yaw = Xsig_pred_(3, i); // measurement model Zsig(0, i) = Xsig_pred_(0, i); //px Zsig(1, i) = Xsig_pred_(1, i); //py } //mean predicted measurement VectorXd z_pred = VectorXd(n_z); z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) z_pred = z_pred + weights_(i) * Zsig.col(i); //measurement covariance matrix S MatrixXd S = MatrixXd(n_z, n_z); S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd z_diff = Zsig.col(i) - z_pred; z_diff(1) = tools.NormAngle(z_diff(1)); // normalization of angle before use S = S + weights_(i) * z_diff * z_diff.transpose(); } //add measurement noise covariance matrix MatrixXd R = MatrixXd(n_z, n_z); R << std_laspx_*std_laspx_, 0, 0, std_laspy_*std_laspy_; S = S + R; // cross correlation G MatrixXd G = MatrixXd(n_x_, n_z); G.fill(0.0); //calculate cross correlation matrix for (int i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd z_diff = Zsig.col(i) - z_pred; z_diff(1) = tools.NormAngle(z_diff(1)); //Norm angle before use // state difference VectorXd x_diff = Xsig_pred_.col(i) - x_; //Norm angle before use x_diff(3) = tools.NormAngle(x_diff(3)); //Cross-correlation matrix G = G + weights_(i) * x_diff * z_diff.transpose(); } //Kalman gain K; MatrixXd K = G * S.inverse(); //actual measurement VectorXd z = VectorXd(n_z); z << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1];// 0.0, 0.0; //residual VectorXd z_diff = z - z_pred; //Norm angle before use z_diff(1) = tools.NormAngle(z_diff(1)); //Final kalman update x_ = x_ + K * z_diff; P_ = P_ - K * S * K.transpose(); //Calculate the lidar NIS. nis_lidar_= z_diff.transpose() * S.inverse() * z_diff; } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { /** Use radar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. Calculate the radar NIS. */ // sensor state dimension int n_z = 3; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1); //transform sigma points into measurement space for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points double p_x = Xsig_pred_(0, i); double p_y = Xsig_pred_(1, i); double v = Xsig_pred_(2, i); double yaw = Xsig_pred_(3, i); double v1 = cos(yaw)*v; double v2 = sin(yaw)*v; // measurement model Zsig(0, i) = sqrt(p_x*p_x + p_y*p_y); //range Zsig(1, i) = atan2(p_y, p_x); //phi Zsig(2, i) = (p_x*v1 + p_y*v2) / sqrt(p_x*p_x + p_y*p_y); //range_dot } //mean predicted measurement VectorXd z_pred = VectorXd(n_z); z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) z_pred = z_pred + weights_(i) * Zsig.col(i); //measurement covariance matrix S MatrixXd S = MatrixXd(n_z, n_z); S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points VectorXd z_diff = Zsig.col(i) - z_pred; //difference //Normalize angle before use z_diff(1) = tools.NormAngle(z_diff(1)); S = S + weights_(i) * z_diff * z_diff.transpose(); } //Obtain R matrix MatrixXd R = MatrixXd(n_z, n_z); R << std_radr_*std_radr_, 0, 0, 0, std_radphi_*std_radphi_, 0, 0, 0, std_radrd_*std_radrd_; S = S + R; // cross correlation matrix G MatrixXd G = MatrixXd(n_x_, n_z); G.fill(0.0); //calculate cross correlation matrix for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points //residual VectorXd z_diff = Zsig.col(i) - z_pred; //Norm angle before use z_diff(1) = tools.NormAngle(z_diff(1)); // state difference VectorXd x_diff = Xsig_pred_.col(i) - x_; //Norm angle before use x_diff(3) = tools.NormAngle(x_diff(3)); G = G + weights_(i) * x_diff * z_diff.transpose(); } //Gain matrix , Kalman Filter MatrixXd K = G * S.inverse(); //actual measurement VectorXd z = VectorXd(n_z); z << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1], meas_package.raw_measurements_[2]; //error VectorXd z_diff = z - z_pred; //Norm angle before use z_diff(1) = tools.NormAngle(z_diff(1)); x_ = x_ + K * z_diff; // kalman update P_ = P_ - K * S * K.transpose(); nis_radar_ = z_diff.transpose() * S.inverse() * z_diff; }
[ "aneeq.sdc@gmail.com" ]
aneeq.sdc@gmail.com
8d64fcd8cf1bb80bdb20bd178f79ac78f50d8328
f0904d63fd6ee225c378ec71c8551ca643d3d5df
/957-Popes.cc
2f3b3ac853c9929a5424ec27fba46540fe0fbb1c
[]
no_license
A1phaZer0/competitive_programming
8978c7651f00c031fbd6c4b523a2c1b11ad65422
2ed1b2a38166007edf65ae668b621d8eb425b9fd
refs/heads/master
2021-09-09T17:35:23.280175
2018-03-18T15:44:15
2018-03-18T15:44:15
125,740,247
0
0
null
null
null
null
UTF-8
C++
false
false
751
cc
#include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; int main (int argc, char *argv[]) { int Y, N, year; int i; int max, start, end; int popes; vector<int> vi; vector<int>::iterator it; vector<int>::iterator tmp; while (scanf("%d", &Y) != EOF) { vi.clear(); max = 0; scanf("%d", &N); for (i = 0; i < N; i++) { scanf("%d", &year); vi.push_back(year); } it = vi.begin(); while (it != vi.end()) { tmp = upper_bound(it, vi.end(), *it + Y - 1); popes = tmp - it; if (popes > max) { max = popes; start = *it; end = *(tmp-1); } it++; } printf("%d %d %d\n", max, start, end); } return 0; }
[ "ini.universe@gmail.com" ]
ini.universe@gmail.com
c2e5c028b7ce98e0708c21e4b9baa47ea8e484dd
aba42de3e1f69309c8e841bf4c56170262ce8986
/src/main.cpp
37b693999eb0da4cd67a1f304edc916140febe84
[ "MIT" ]
permissive
szczypiorofix/dungeon_engine
44a73ef8288e5b560d77300fe850631ad1aec2e5
dd1db1c22a73eabd9ea18d44a133d71427957180
refs/heads/master
2020-12-07T20:22:43.936557
2020-02-13T20:43:56
2020-02-13T20:43:56
232,792,430
0
0
MIT
2020-02-13T20:43:58
2020-01-09T11:23:21
C++
UTF-8
C++
false
false
440
cpp
/* * Dungeon Engine v0.1.0 * Copyright (C) 2020 szczypiorofix <szczypiorofix@o2.pl> */ #include <iostream> #include "game/DungeonGame.h" /** * Main entry point */ int main(int argc, char* argv[]) { if (argc > 1) { std::cout << "Parameters: " << argc << std::endl; for (int i = 1; i < argc; i++) { std::cout << i << ":" << argv[i] << std::endl; } } DungeonGame* game = new DungeonGame(); game->launch(); return 0; }
[ "szczypiorofix@o2.pl" ]
szczypiorofix@o2.pl
f274ceb85aeb3f05a8123c35f775680238795d20
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/services/network/public/mojom/origin_policy_manager.mojom.cc
a63c354bc4e7ef42f73c6b81ba1955438dea96f0
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,761
cc
// Copyright 2013 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif #include "services/network/public/mojom/origin_policy_manager.mojom.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/location.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/task/common/task_annotator.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "services/network/public/mojom/origin_policy_manager.mojom-params-data.h" #include "services/network/public/mojom/origin_policy_manager.mojom-shared-message-ids.h" #include "services/network/public/mojom/origin_policy_manager.mojom-import-headers.h" #ifndef SERVICES_NETWORK_PUBLIC_MOJOM_ORIGIN_POLICY_MANAGER_MOJOM_JUMBO_H_ #define SERVICES_NETWORK_PUBLIC_MOJOM_ORIGIN_POLICY_MANAGER_MOJOM_JUMBO_H_ #include "url/mojom/url_gurl_mojom_traits.h" #endif namespace network { namespace mojom { OriginPolicyContents::OriginPolicyContents() : features(), content_security_policies(), content_security_policies_report_only() {} OriginPolicyContents::OriginPolicyContents( const std::vector<std::string>& features_in, const std::vector<std::string>& content_security_policies_in, const std::vector<std::string>& content_security_policies_report_only_in) : features(std::move(features_in)), content_security_policies(std::move(content_security_policies_in)), content_security_policies_report_only(std::move(content_security_policies_report_only_in)) {} OriginPolicyContents::~OriginPolicyContents() = default; bool OriginPolicyContents::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } OriginPolicy::OriginPolicy() : state(), policy_url(), contents() {} OriginPolicy::OriginPolicy( OriginPolicyState state_in, const GURL& policy_url_in, OriginPolicyContentsPtr contents_in) : state(std::move(state_in)), policy_url(std::move(policy_url_in)), contents(std::move(contents_in)) {} OriginPolicy::~OriginPolicy() = default; bool OriginPolicy::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } const char OriginPolicyManager::Name_[] = "network.mojom.OriginPolicyManager"; OriginPolicyManagerProxy::OriginPolicyManagerProxy(mojo::MessageReceiverWithResponder* receiver) : receiver_(receiver) { } // static bool OriginPolicyManagerStubDispatch::Accept( OriginPolicyManager* impl, mojo::Message* message) { return false; } // static bool OriginPolicyManagerStubDispatch::AcceptWithResponder( OriginPolicyManager* impl, mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder) { return false; } bool OriginPolicyManagerRequestValidator::Accept(mojo::Message* message) { if (!message->is_serialized() || mojo::internal::ControlMessageHandler::IsControlMessage(message)) { return true; } mojo::internal::ValidationContext validation_context( message->payload(), message->payload_num_bytes(), message->handles()->size(), message->payload_num_interface_ids(), message, "OriginPolicyManager RequestValidator"); switch (message->header()->name) { default: break; } // Unrecognized message. ReportValidationError( &validation_context, mojo::internal::VALIDATION_ERROR_MESSAGE_HEADER_UNKNOWN_METHOD); return false; } } // namespace mojom } // namespace network namespace mojo { // static bool StructTraits<::network::mojom::OriginPolicyContents::DataView, ::network::mojom::OriginPolicyContentsPtr>::Read( ::network::mojom::OriginPolicyContents::DataView input, ::network::mojom::OriginPolicyContentsPtr* output) { bool success = true; ::network::mojom::OriginPolicyContentsPtr result(::network::mojom::OriginPolicyContents::New()); if (!input.ReadFeatures(&result->features)) success = false; if (!input.ReadContentSecurityPolicies(&result->content_security_policies)) success = false; if (!input.ReadContentSecurityPoliciesReportOnly(&result->content_security_policies_report_only)) success = false; *output = std::move(result); return success; } // static bool StructTraits<::network::mojom::OriginPolicy::DataView, ::network::mojom::OriginPolicyPtr>::Read( ::network::mojom::OriginPolicy::DataView input, ::network::mojom::OriginPolicyPtr* output) { bool success = true; ::network::mojom::OriginPolicyPtr result(::network::mojom::OriginPolicy::New()); if (!input.ReadState(&result->state)) success = false; if (!input.ReadPolicyUrl(&result->policy_url)) success = false; if (!input.ReadContents(&result->contents)) success = false; *output = std::move(result); return success; } } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
04d1f1558863419d67f2345f2b58a09ab4e6d33f
b18adf09556fa66a9db188684c69ea48849bb01b
/new_projects/src/granular/gransim2d/engine/particle_source.h
09b71ec2589f046003c583d1196fdf21b73f9412
[]
no_license
zzfd97/projects
d78e3fa6418db1a5a2580edcaef1f2e197d5bf8c
f8e7ceae143317d9e8461f3de8cfccdd7627c3ee
refs/heads/master
2022-01-12T19:56:48.014510
2019-04-05T05:30:31
2019-04-05T05:30:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,827
h
#ifndef PARTICLE_SOURCE_H #define PARTICLE_SOURCE_H #include "geometry2d_object.h" #include "particle_type.h" // Forward declarations class CParticle2D; typedef enum { PARTICLE_SOURCE_FLOW_TYPE_UNIFORM, PARTICLE_SOURCE_FLOW_TYPE_POISSON } PARTICLE_SOURCE_FLOW_TYPE_ENUM; class CParticleSource : public CGeometry2DObject { //Constuctors/destructors public: CParticleSource(); virtual ~CParticleSource(); // Public methods public: void SetFlowType(const char *pszType); void SetFlowType(const common::portable::CTextString &Type) { SetFlowType(Type.GetText()); } void Simulation_Started(); void Simulation_ClipTimeStep(double t, double &dt); CParticle2D *Simulation_NewParticle(double t); common::portable::CTextString &GetParticleTypeName() { return m_ParticleTypeName; } CParticleType *GetParticleType() { return m_pParticleType; } void SetParticleType(CParticleType *pType); double GetMaxParticleSize() { return m_pParticleType->GetMaxParticleSize(); } double GetMinParticleSize() { return m_pParticleType->GetMinParticleSize(); } double GetAveParticleSize() { return m_pParticleType->GetAveParticleSize(); } double GetIntensity() { return m_fIntensity; } // Public overridables public: virtual const char *GetKeyWord() = 0; virtual void SaveToFile(FILE *fd); virtual void DeleteFromDesign(); // Public members public: PARTICLE_SOURCE_FLOW_TYPE_ENUM m_FlowType; double m_fIntensity; double m_fNextGenTime; // time when the next particle will be generated // Protected methods protected: // Protected overridables protected: virtual void LocateProbeParticle() = 0; // Protected members protected: static CParticle2D g_ProbeParticle; CParticleType *m_pParticleType; common::portable::CTextString m_ParticleTypeName; // At loading time we store particle type name, and find particle type itself later (probably particle type does not exist yet) // Private methods private: // Private overridables private: // Private members private: }; typedef std::vector<CParticleSource *> cParticleSources; class CParticlePointSource : public CParticleSource { //Constuctors/destructors public: CParticlePointSource(common::geometry2d::CPoint2D *pPoint); virtual ~CParticlePointSource(); // Public methods public: void SetPoint(common::geometry2d::CPoint2D *pPoint); // Public overridables public: virtual const char *GetTypeDesc() { return "Particle Point Source"; } virtual const char *GetKeyWord(); virtual int GetFormCount(); virtual SFormDesc *GetFormDesc(int iFormNumber); virtual common::geometry2d::CGeometry2D *GetGeometry() { return &m_Point; } // Public members public: common::geometry2d::CPoint2D *GetPoint() { return &m_Point; } // Protected methods protected: // Protected overridables protected: virtual void LocateProbeParticle(); // Protected members protected: common::geometry2d::CPoint2D m_Point; // Private methods private: // Private overridables private: // Private members private: }; class CParticleLinearSource : public CParticleSource { //Constuctors/destructors public: CParticleLinearSource(common::geometry2d::CLine2D *pLine); virtual ~CParticleLinearSource(); // Public overridables public: virtual const char *GetTypeDesc() { return "Particle Linear Source"; } virtual const char *GetKeyWord(); virtual int GetFormCount(); virtual SFormDesc *GetFormDesc(int iFormNumber); virtual common::geometry2d::CGeometry2D *GetGeometry() { return &m_Line; } // Public members public: common::geometry2d::CLine2D *GetLine() { return &m_Line; } // Protected methods protected: // Protected overridables protected: virtual void LocateProbeParticle(); // Protected members protected: common::geometry2d::CLine2D m_Line; // Private methods private: // Private overridables private: // Private members private: }; #endif // PARTICLE_SOURCE_H
[ "hp@kozhevnikov.org" ]
hp@kozhevnikov.org
62538c995b9aec328344c188ff9a3305170d8c12
f503ce877d2b7c497c970396db09a2e3c2d50758
/code-for-today-for-everyDay/Practice/HackerRank/LinkedinPlacement/BitwiseAND/main.cpp
f15fbbe61c451038b3939c472f275b5d71cc3439
[]
no_license
Iraniya/code-for-today-for-everyDay
c7018ee1edd746ea3ddf3aa88033bddde48a6191
5a46eeae944bcecbd1caf473c95590da05166165
refs/heads/master
2022-12-02T14:26:22.682854
2020-08-20T17:31:18
2020-08-20T17:31:18
115,755,575
0
0
null
null
null
null
UTF-8
C++
false
false
894
cpp
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib>COn #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main(){ int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; int k; int maxNumber=0; cin >> n >> k; for(int i=1;i<=n;i++){ for(int j=i+1;j<=n;j++){ int test = i&j; // cout<<"i "<<i<<" j "<<j<<" a&b "<<max<<endl; if(test<k && test>maxNumber){ maxNumber =test; } } } cout<<maxNumber<<endl; } return 0; }
[ "n201101047@gmail.com" ]
n201101047@gmail.com
171b650da07679981b13465e1913356fa95bf241
e86dedc5b0bb79b9eba41e74c343e77bd1ee1512
/llvm/examples/OrcV2Examples/LLJITWithExecutorProcessControl/LLJITWithExecutorProcessControl.cpp
8d2ac3261e399df52968130cd10c3aeab09beb2c
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
shafik/llvm-project
a5e1b66fb053f9aa01720a40ea7985b4cc57d16f
be556c838de06c3c2f69bf594996cace6ffa17eb
refs/heads/main
2023-05-28T22:35:12.937142
2023-05-16T18:22:53
2023-05-16T18:25:41
221,325,771
0
0
Apache-2.0
2019-11-12T22:40:44
2019-11-12T22:40:44
null
UTF-8
C++
false
false
6,815
cpp
//===- LLJITWithExecutorProcessControl.cpp - LLJIT example with EPC utils -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // In this example we will use the lazy re-exports utility to lazily compile // IR modules. We will do this in seven steps: // // 1. Create an LLJIT instance. // 2. Install a transform so that we can see what is being compiled. // 3. Create an indirect stubs manager and lazy call-through manager. // 4. Add two modules that will be conditionally compiled, plus a main module. // 5. Add lazy-rexports of the symbols in the conditionally compiled modules. // 6. Dump the ExecutionSession state to see the symbol table prior to // executing any code. // 7. Verify that only modules containing executed code are compiled. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h" #include "llvm/ExecutionEngine/Orc/EPCIndirectionUtils.h" #include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" #include "llvm/ExecutionEngine/Orc/OrcABISupport.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include "../ExampleModules.h" #include <future> using namespace llvm; using namespace llvm::orc; ExitOnError ExitOnErr; // Example IR modules. // // Note that in the conditionally compiled modules, FooMod and BarMod, functions // have been given an _body suffix. This is to ensure that their names do not // clash with their lazy-reexports. // For clients who do not wish to rename function bodies (e.g. because they want // to re-use cached objects between static and JIT compiles) techniques exist to // avoid renaming. See the lazy-reexports section of the ORCv2 design doc. const llvm::StringRef FooMod = R"( declare i32 @return1() define i32 @foo_body() { entry: %0 = call i32 @return1() ret i32 %0 } )"; const llvm::StringRef BarMod = R"( declare i32 @return2() define i32 @bar_body() { entry: %0 = call i32 @return2() ret i32 %0 } )"; const llvm::StringRef MainMod = R"( define i32 @entry(i32 %argc) { entry: %and = and i32 %argc, 1 %tobool = icmp eq i32 %and, 0 br i1 %tobool, label %if.end, label %if.then if.then: ; preds = %entry %call = tail call i32 @foo() #2 br label %return if.end: ; preds = %entry %call1 = tail call i32 @bar() #2 br label %return return: ; preds = %if.end, %if.then %retval.0 = phi i32 [ %call, %if.then ], [ %call1, %if.end ] ret i32 %retval.0 } declare i32 @foo() declare i32 @bar() )"; extern "C" int32_t return1() { return 1; } extern "C" int32_t return2() { return 2; } static void *reenter(void *Ctx, void *TrampolineAddr) { std::promise<void *> LandingAddressP; auto LandingAddressF = LandingAddressP.get_future(); auto *EPCIU = static_cast<EPCIndirectionUtils *>(Ctx); EPCIU->getLazyCallThroughManager().resolveTrampolineLandingAddress( ExecutorAddr::fromPtr(TrampolineAddr), [&](ExecutorAddr LandingAddress) { LandingAddressP.set_value(LandingAddress.toPtr<void *>()); }); return LandingAddressF.get(); } static void reportErrorAndExit() { errs() << "Unable to lazily compile function. Exiting.\n"; exit(1); } cl::list<std::string> InputArgv(cl::Positional, cl::desc("<program arguments>...")); int main(int argc, char *argv[]) { // Initialize LLVM. InitLLVM X(argc, argv); InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); cl::ParseCommandLineOptions(argc, argv, "LLJITWithLazyReexports"); ExitOnErr.setBanner(std::string(argv[0]) + ": "); // (1) Create LLJIT instance. auto EPC = ExitOnErr(SelfExecutorProcessControl::Create()); auto J = ExitOnErr( LLJITBuilder().setExecutorProcessControl(std::move(EPC)).create()); // (2) Install transform to print modules as they are compiled: J->getIRTransformLayer().setTransform( [](ThreadSafeModule TSM, const MaterializationResponsibility &R) -> Expected<ThreadSafeModule> { TSM.withModuleDo([](Module &M) { dbgs() << "---Compiling---\n" << M; }); return std::move(TSM); // Not a redundant move: fix build on gcc-7.5 }); // (3) Create stubs and call-through managers: auto EPCIU = ExitOnErr(EPCIndirectionUtils::Create( J->getExecutionSession().getExecutorProcessControl())); ExitOnErr(EPCIU->writeResolverBlock(ExecutorAddr::fromPtr(&reenter), ExecutorAddr::fromPtr(EPCIU.get()))); EPCIU->createLazyCallThroughManager( J->getExecutionSession(), ExecutorAddr::fromPtr(&reportErrorAndExit)); auto ISM = EPCIU->createIndirectStubsManager(); // (4) Add modules. ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(FooMod, "foo-mod")))); ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(BarMod, "bar-mod")))); ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(MainMod, "main-mod")))); // (5) Add lazy reexports. MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout()); SymbolAliasMap ReExports( {{Mangle("foo"), {Mangle("foo_body"), JITSymbolFlags::Exported | JITSymbolFlags::Callable}}, {Mangle("bar"), {Mangle("bar_body"), JITSymbolFlags::Exported | JITSymbolFlags::Callable}}}); ExitOnErr(J->getMainJITDylib().define( lazyReexports(EPCIU->getLazyCallThroughManager(), *ISM, J->getMainJITDylib(), std::move(ReExports)))); // (6) Dump the ExecutionSession state. dbgs() << "---Session state---\n"; J->getExecutionSession().dump(dbgs()); dbgs() << "\n"; // (7) Execute the JIT'd main function and pass the example's command line // arguments unmodified. This should cause either ExampleMod1 or ExampleMod2 // to be compiled, and either "1" or "2" returned depending on the number of // arguments passed. // Look up the JIT'd function, cast it to a function pointer, then call it. auto EntryAddr = ExitOnErr(J->lookup("entry")); auto *Entry = EntryAddr.toPtr<int(int)>(); int Result = Entry(argc); outs() << "---Result---\n" << "entry(" << argc << ") = " << Result << "\n"; // Destroy the EPCIndirectionUtils utility. ExitOnErr(EPCIU->cleanup()); return 0; }
[ "lhames@gmail.com" ]
lhames@gmail.com
c49b3e097ad64ae0912c5512aac0c72a068264a3
e7504e796df90bfe606781c14442a564eb01754b
/plugins/G3D/VRG3D/src/G3DOperators.cpp
3b9785b38924c41542a820fc06b26e35cca7fdf2
[ "BSD-3-Clause" ]
permissive
MinVR/MinVR
1dc4c007b10f184732d3a90e362175c8e950e95b
33386e6b49de6c6b75f735704ffa49ab6069f8bf
refs/heads/master
2022-06-28T19:50:09.692509
2022-05-17T21:44:13
2022-05-17T21:44:13
40,127,890
23
21
NOASSERTION
2022-05-17T21:44:14
2015-08-03T14:02:01
C++
UTF-8
C++
false
false
8,794
cpp
// Copyright Regents of the University of Minnesota and Brown University, 2010. All rights are reserved. #include "../include/G3DOperators.h" namespace MinVR { using namespace G3D; void growAABox(AABox &box, const Vector3 &point) { box = AABox(min(point, box.low()), max(point, box.high())); } void growAABox(AABox &box, const AABox &box2) { box = AABox(min(box.low(), box2.low()), max(box.high(), box2.high())); } Color3 Color3FromUints(G3D::uint8 r, G3D::uint8 g, G3D::uint8 b) { return Color3((double)r/255.0, (double)g/255.0, (double)b/255.0); } // This could definately be implemented more smartly.. but it works.. Turn the double // into a string, then use the usual code for computing a hash code from a string. unsigned int hashCode(const double d) { std::ostringstream ostr; // if using strstream rather than stringstream, the following call // requires a << "\0" at the end. ostr << d; std::string a = std::string(ostr.str()); int s = (int)a.length(); int i = 0; unsigned int key = s; s = G3D::iMin(s, 5); while (i < s) { key = key ^ ((unsigned int)a[i] << ((i & 3) * 8)); ++i; } return key; } std::ostream & operator<< ( std::ostream &os, const Vector2 &vec2) { // format: (x, y) return os << vec2.toString(); } std::istream & operator>> ( std::istream &is, Vector2 &vec2) { // format: (x, y) char dummy; return is >> dummy >> vec2.x >> dummy >> vec2.y >> dummy; } /* This is now defined inside G3D: std::ostream & operator<< ( std::ostream &os, const Vector3 &vec3) { // format: (x, y, z) return os << vec3.toString(); } */ std::istream & operator>> ( std::istream &is, Vector3 &vec3) { // format: (x, y, z) char dummy; return is >> dummy >> vec3.x >> dummy >> vec3.y >> dummy >> vec3.z >> dummy; } std::ostream & operator<< ( std::ostream &os, const Matrix3 &m) { // format: ((r1c1, r1c2, r1c3), (r2c1, r2c2, r2c3), (r3c1, r3c2, r3c3)) return os << "((" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << "), " << "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] << "), " << "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] << "))"; } std::istream & operator>> ( std::istream &is, Matrix3&m) { // format: ((r1c1, r1c2, r1c3), (r2c1, r2c2, r2c3), (r3c1, r3c2, r3c3)) char c; return is >> c >> c >> m[0][0] >> c >> m[0][1] >> c >> m[0][2] >> c >> c >> c >> m[1][0] >> c >> m[1][1] >> c >> m[1][2] >> c >> c >> c >> m[2][0] >> c >> m[2][1] >> c >> m[2][2] >> c >> c; } std::ostream & operator<< ( std::ostream &os, const Matrix4 &m) { // format: ((r1c1, r1c2, r1c3, r1c4), (r2c1, r2c2, r2c3, r2c4), etc.. ) return os << "((" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << ", " << m[0][3] << "), " << "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] << ", " << m[1][3] << "), " << "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] << ", " << m[2][3] << "), " << "(" << m[3][0] << ", " << m[3][1] << ", " << m[3][2] << ", " << m[3][3] << "))"; } std::istream & operator>> ( std::istream &is, Matrix4 &m) { // format: ((r1c1, r1c2, r1c3, r1c4), (r2c1, r2c2, r2c3, r2c4), etc.. ) char c; return is >> c >> c >> m[0][0] >> c >> m[0][1] >> c >> m[0][2] >> c >> m[0][3] >> c >> c >> c >> m[1][0] >> c >> m[1][1] >> c >> m[1][2] >> c >> m[1][3] >> c >> c >> c >> m[2][0] >> c >> m[2][1] >> c >> m[2][2] >> c >> m[2][3] >> c >> c >> c >> m[3][0] >> c >> m[3][1] >> c >> m[3][2] >> c >> m[3][3] >> c >> c; } // This orthonormalizes the rotation matrix, which means you will loose any scale // that is in there, but you will gain orthonormal axes, which otherwise you wouldn't // necessarily have due to precision errors when reading/writing out data to a string. // If you want to keep scaling info use a Matrix4 instead. std::istream & operator>> ( std::istream &is, CoordinateFrame &m) { // format: ((r1c1, r1c2, r1c3, r1c4), (r2c1, r2c2, r2c3, r2c4), etc.. ) char c; double d; Matrix3 r(1,0,0,0,1,0,0,0,1); Vector3 t; is >> c >> c >> r[0][0] >> c >> r[0][1] >> c >> r[0][2] >> c >> t[0] >> c >> c >> c >> r[1][0] >> c >> r[1][1] >> c >> r[1][2] >> c >> t[1] >> c >> c >> c >> r[2][0] >> c >> r[2][1] >> c >> r[2][2] >> c >> t[2] >> c >> c >> c >> d >> c >> d >> c >> d >> c >> d >> c >> c; r.orthonormalize(); m = CoordinateFrame(r,t); return is; } std::ostream & operator<< ( std::ostream &os, const Color3 &c) { // format: (x, y) return os << c.toString(); } std::istream & operator>> ( std::istream &is, Color3 &c) { // format: (x, y) char dummy; return is >> dummy >> c[0] >> dummy >> c[1] >> dummy >> c[2] >> dummy; } std::ostream & operator<< ( std::ostream &os, const Color4 &c) { // format: (x, y) return os << c.toString(); } std::istream & operator>> ( std::istream &is, Color4 &c) { // format: (x, y) char dummy; return is >> dummy >> c[0] >> dummy >> c[1] >> dummy >> c[2] >> dummy >> c[3] >> dummy; } std::string matrix4ToString(Matrix4 m) { // format: ((r1c1, r1c2, r1c3, r1c4), (r2c1, r2c2, r2c3, r2c4), etc.. ) // in the past, this was output with only 2 decimal places of // precision. that is BAD if you're using this routine to store // CoordinateFrames in XML. So, changing it to output full // precision. return format("((%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f))", m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2], m[3][3]); } std::string coordinateFrameToString(CoordinateFrame cf) { return matrix4ToString(cf.toMatrix4()); } #define BIGNUMBER 9999 int iMinNonNeg(int i1, int i2) { if (i1 < 0) i1 = BIGNUMBER; if (i2 < 0) i2 = BIGNUMBER; if (i1 < i2) return i1; else return i2; } bool popNextToken(std::string &in, std::string &token, bool returnFalseOnSemiColon) { in = trimWhitespace(in); // if no more tokens, return false if (in.size() == 0) { return false; } else if ((in[0] == ';') && (returnFalseOnSemiColon)) { in = in.substr(1); return false; } int end = in.size(); end = iMinNonNeg(end, in.find(" ")); end = iMinNonNeg(end, in.find('\t')); end = iMinNonNeg(end, in.find(";")); end = iMinNonNeg(end, in.find(",")); end = iMinNonNeg(end, in.find('\n')); end = iMinNonNeg(end, in.find('\r')); token = in.substr(0,end); in = in.substr(end); return (token.size() > 0); } Array<std::string> splitStringIntoArray(const std::string &in) { Array<std::string> a; std::string s = in; std::string token; while (popNextToken(s, token, false)) { a.append(token); } return a; } std::string decygifyPath(const std::string &in) { /******************************* CYGWIN std::string input = in; int startofcyg = input.find("/cygdrive/"); if (startofcyg >= 0) { std::string drive = input.substr(startofcyg + 10, 1); std::string newpath = input.substr(0,startofcyg) + drive + std::string(":") + input.substr(startofcyg + 11); // recursive call return decygifyPath(newpath); } else { return input; } **********************************/ return in; } std::string replaceEnvVars(const std::string &in) { // the special sequence $(NAME) gets replaced by the decygified value // of the environment variable NAME // If any variable is undefined then an empty string is returned. // std::string instr = in; // int evstart = instr.find("\$("); int evstart = instr.find("$("); while (evstart >= 0) { std::string evandrest = instr.substr(evstart+2); int evend = evandrest.find(")"); std::string ev = evandrest.substr(0,evend); const char *pevval = getenv( ev.c_str() ); if ( pevval == NULL ) { instr = ""; break; } std::string evval = pevval; evval = decygifyPath(evval); instr = instr.substr(0,evstart) + evval + evandrest.substr(evend+1); // evstart = instr.find("\$("); evstart = instr.find("$("); } return instr; } std::string intToString(int i) { std::ostringstream ostr; // if using strstream rather than stringstream, the following call // requires a << "\0" at the end. ostr << i; return std::string(ostr.str()); } int stringToInt(const std::string &in) { int i; std::istringstream istr(in.c_str()); istr >> i; return i; } std::string realToString(double r) { std::ostringstream ostr; // if using strstream rather than stringstream, the following call // requires a << "\0" at the end. ostr << r; return std::string(ostr.str()); } double stringToReal(const std::string &in) { double r; std::istringstream istr(in.c_str()); istr >> r; return r; } } // end namespace
[ "k.diaz99@gmail.com" ]
k.diaz99@gmail.com
476f865bf6aae0f2d5e4a3ce22f626a7a59331cb
31c5eb1fd3841ae24d6d1a57523d4c4d8bb587a3
/Simple/Accepted/Leetcode_Simple_100_Same_Tree.cpp
4f00ab901d1ecb31679c999aca04461ae0caf0ec
[]
no_license
yhc520314484/LeetCode
814a16970b5a4ee6ae9f433b5069ab86d0bc9352
6326b407e89784a0c5f8143dda9f43e83d76f5c5
refs/heads/master
2022-11-03T05:17:56.673714
2020-06-14T03:19:53
2020-06-14T03:19:53
255,896,906
0
0
null
null
null
null
UTF-8
C++
false
false
2,505
cpp
/* Leecode 100 Same Tree Level: Simple Author: JackWilliam Date: 29, May, 2020 */ /* Version 0.1 使用中序遍历分别遍历两个二叉树,将二叉树中的元素依次压入vector中,然后进行对比 4ms 8.2MB */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode*> nodeStack_p; stack<TreeNode*> nodeStack_q; vector<int> vec_p; vector<int> vec_q; while (!nodeStack_p.empty() || p != nullptr) { if(p != nullptr){ vec_p.push_back(p->val); nodeStack_p.push(p); p = p->left; } else{ vec_p.push_back(NULL); p = nodeStack_p.top(); nodeStack_p.pop(); p = p->right; } } while (!nodeStack_q.empty() || q != nullptr) { if(q != nullptr){ vec_q.push_back(q->val); nodeStack_q.push(q); q = q->left; } else{ vec_q.push_back(NULL); q = nodeStack_q.top(); nodeStack_q.pop(); q = q->right; } } if(vec_p.size() != vec_q.size()) return false; for(int i = 0; i < vec_p.size(); i++){ if(vec_p[i] != vec_q[i]) return false; } return true; } }; /* Solution Key Point: 递归依次查找 时间复杂度 O(N) 空间复杂度O(N) 4ms 7.4Mb Source: LeetCode Author: 作者:youlookdeliciousc Url: https://leetcode-cn.com/problems/same-tree/solution/c-di-gui-ji-jian-shuang-bai-xie-fa-si-lu-zhu-shi-b/ */ /* 验证相同的树,若当前节点都为空,返回true 若仅有一个节点为空,说明不相同,返回false 对比当前节点的值,进入递归,p的左子树和q的左子树对比,p的右子树和q的右子树对比 */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(!p && !q) return true; if(!p || !q) return false; // 说明有且仅有一个为空节点,所以不相同 return p -> val == q -> val && isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right); } };
[ "2013021287@cuit.edu.cn" ]
2013021287@cuit.edu.cn
8c01eec7dc20c8c9b3fe1dfe061ba07ae632643f
f1c01a3b5b35b59887bf326b0e2b317510deef83
/SDK/SoT_BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner_classes.hpp
98548d4608b1adb1c0331cf97749c4546e7cd2b6
[]
no_license
codahq/SoT-SDK
0e4711e78a01f33144acf638202d63f573fa78eb
0e6054dddb01a83c0c1f3ed3e6cdad5b34b9f094
refs/heads/master
2023-03-02T05:00:26.296260
2021-01-29T13:03:35
2021-01-29T13:03:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
932
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner.BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner_C // 0x0000 (0x0550 - 0x0550) class UBP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner_C : public USalvageItemSpawnComponent { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner.BP_FeatureandResourceIslandWashedUpBoxofSecretsSpawner_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
40c55b6cc0c430165fe5bd20a8e627a5ca9b500f
ae654e0807f2799986c571507ab17fd402692423
/ZPGApp/Cubemap.h
2aa65cc35f5568184c4e800c55c673623722da8d
[]
no_license
Or1m/ZPGApp
9d1fe8fce9113407c4fda357fe997c2ba716bacc
616e74a86bf32fff6a65be07a96d4f87b5429586
refs/heads/master
2023-04-03T13:47:22.793345
2021-04-07T13:51:57
2021-04-07T13:51:57
299,253,580
0
0
null
null
null
null
UTF-8
C++
false
false
147
h
#pragma once #include "Texture.h" class Cubemap : public Texture { public: Cubemap(const std::string paths[6]); void bind() const override; };
[ "k.z.w.212@gmail.com" ]
k.z.w.212@gmail.com
65795202bde2f969265e944072c4fd51cc3e3b73
1e25ce089c4e5c4cfd6bff76a8839a40b76270d0
/Lib/TLibCommon/globals_YS.h
3ba4df0ff726bb71c36da29f124a9f54ad842550
[]
no_license
Vector-S/Fast-CU-Decision-HEVC
2db431dcac44c4451705ec0183a0ecb90d3e9e98
e17193a55aaf99dead3da1c9d37ceff912277794
refs/heads/master
2021-06-03T09:33:54.799634
2016-07-29T18:21:50
2016-07-29T18:21:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,247
h
#include <iostream> #include <fstream> #include <iterator> #include <vector> #include <String> #include "cvheaders.h" #include "TLibCommon/CommonDef.h" #include "TLibCommon/TComYuv.h" #include "TLibCommon/TComPic.h" #include "TLibCommon/TComPrediction.h" #include "TLibCommon/TComTrQuant.h" #include "TLibCommon/TComBitCounter.h" #include "TLibCommon/TComDataCU.h" #include "TLibEncoder/TEncCu.h" #include "TLibCommon/linear.h" //////////////////////////////////// Macro Definiton #define OBSERVATION 0 #define OUTPUT_INSIGHTDATA 1 #define NEW_FEATURESYSTEM 0 #define PARAMETER_SELECTION 0 #define NUM_CU_DEPTH 4 #define NUM_MODELTYPE 15 #define NUM_RESULTTYPE 7 #define NUM_DECISIONTYPE 4 #define NUM_FEATURETYPE 20 #define NUM_FEATUREFORMAT 4 //////////////////////////////////// Enumeration enum FeatureFormat { Unknown, LibLinear, OpenCV, BayesStat }; enum FeatureType { N_OBF, OBF, EOBF, SOC, SUBSOC, BOutlier, MIXED, Outlier, NewFeature, OBF_SATD, OBF_SATD_RDCost, NoneFeature }; enum FeatureName { J_RMD_2Nx2N, J_RDO_2Nx2N }; enum ModelType { SVM_0 = 0, SVM_1, SVM_2, SVM_OpenCV, RTS_OpenCV, Naive, BayesDecision, Assistant_Skip, BayesNew, NoneModel }; enum ResultType{ NoResult = -1, TP, FP, TN, FN, FPLoss, FNLoss, }; enum DecisionType{ Unsure = 0, Skip2Nx2N, TerminateCU, SkipRDO }; enum CurrentState{ Training, Verifying, Testing }; extern double g_C[3]; extern double g_W_P[3]; extern double g_W_N[3]; ////////////////////////////////////////////////////////////////////////// // New feature system /////////////////////////////////////////////////////////////////////////// extern Mat* g_TrainingDataMat; // [uiDepth] extern ofstream* g_TrainingDataSet; extern FILE* g_pFile_Performance; //= fopen("precison.txt", "at"); extern ofstream* g_InsightDataSet; /////////////////////////////////////////////////////////////////////////// #if SVM_ONLINE_TRAIN // extern declaration of global model objects extern model* ** model_linear; // [uiDepth][FeatureType] extern CvSVM* CvSVM_model; extern CvRTrees* CvRTrees_model; #endif extern const char * FeatureFormat_Names[]; extern const char * FeatureType_Names[]; extern const char * ModelType_Names[]; #if ENABLE_YS_GLOBAL // extern declaration of global variables //////////////////////////////////////////////////////////////////////////////////////////////////////////// //Training Statistic ////////////////////////////////////////////////////////////////////////////////////////////////////////// // SVM feature Scale Factor extern Double* g_ScaleFactor; extern Double* g_d2NRDCost; extern Double* g_d2NBits; extern Double* g_d2NDistortion; extern Double* g_dSOC; extern double*** g_iVerResult;// [uiDepth][ModelType][TFPN] extern bool*** g_bDecisionSwitch;// [uiDepth][ModelType][DecisionType] extern bool* g_bModelSwitch;// [ModelType] #endif ////////////////////////////////////// //global control variables ////////////////////////////////////// extern char* g_pchInputFile; extern Int g_iQP; extern Int g_iSourceWidth; extern Int g_iSourceHeight; extern Double g_dBitRate; extern Double g_dYUVPSNR; extern Double g_dET; extern Int g_iPOC; extern Int* g_iP; // [uiDepth] extern Int* g_iT; // [uiDepth] extern Int* g_iV; // [uiDepth] extern Double*** g_dPrecision_Th; // [uiDepth][ModelType][DecisionType] extern Double g_dPrecision_Th_Default; extern ModelType g_mainModelType; extern FeatureType g_mainFeatureType; extern ModelType g_modelType_2; extern FeatureType g_featureType_2; extern ModelType g_modelType_3; extern FeatureType g_featureType_3; extern ofstream*** g_TrainingSet;//[uiDepth][FeatureFormat][FeatureType] extern Int** g_iFeatureLength; // [uiDepth][FeatureType] extern Int** g_iSampleNumber; // [uiDepth][FeatureType] // contral bools extern Bool g_bTrustAssistantSkip; extern Bool g_bMultiModel; extern Bool g_bDepthException; // variables for SkipRDO rhis are couted during testing extern UInt g_uiNumCU_Decision[NUM_CU_DEPTH][NUM_DECISIONTYPE]; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[ "jiasenxu@gmail.com" ]
jiasenxu@gmail.com
f33e2bd5c51eba597c2c56a318285ab7a5f6d547
904d5a0f818942c73c5bbf102c722d657566fc67
/src/119-pascals-triangle-ii.cpp
d6a82664392df1d3aecc4e6cbe05ca25138821e7
[]
no_license
Ace-0/MyLeetCode
95ae2c7a21997478f0834932bdf42fb2f655af06
b2af4adbfba26d72ef13af6210744dfeabfff510
refs/heads/master
2022-12-09T15:05:29.227287
2019-11-24T04:13:02
2019-11-24T04:13:02
170,652,315
0
0
null
2022-12-08T01:37:55
2019-02-14T08:07:13
C++
UTF-8
C++
false
false
362
cpp
// 119. Pascal's Triangle II #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { vector<int> line(rowIndex + 1, 0); line[rowIndex] = 1; for (int row = 1; row <= rowIndex; ++row) { for (int i = rowIndex - row; i < rowIndex; ++i) line[i] += line[i + 1]; } return line; } };
[ "w674901087@163.com" ]
w674901087@163.com
ce674f1ce03c40cefa07ca5227ca11bf7679aa13
ff3e66484ff5175d73a6501654823850f0de8036
/Contest/Google Code Jam/Google_Problem_B.cpp
b19fb6753dd68135e68f53c650fed248039492e8
[]
no_license
Sabuj-Kumar/Problem_Solve
05f83455069f9e0a7f4541bc078b19c19d42eecf
b3bbf070ead97debbfebc868c358826e3e503406
refs/heads/main
2023-08-15T00:29:20.485529
2021-09-16T18:08:08
2021-09-16T18:08:08
407,263,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,845
cpp
#include<bits/stdc++.h> #define pi acos(-1) #define ll long long #define ull unsigned long long #define db double #define ldb long double #define pii pair<int,int> #define pll pair< ll,ll > #define pb push_back #define pf push_front #define f first #define s second #define sc( n ) scanf("%d",&n) #define sl( n ) scanf("%lld",&n) #define Case( n ) for(int cs = 1; cs <= n; cs++) #define lop(i,v,n) for(int i = v; i < n; i++) #define op ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define in freopen("in.txt","r",stdin) using namespace std; void file(){ #ifndef ONLINE_JUDGE in; #endif // ONLINE_JUDGE } struct data{ int x,y,c; data(){} data(int x) { this -> x = x; } data(int x,int y) { this -> x = x,this -> y = y,this -> c = c; } data(int x,int y,int c) { this -> x = x,this -> y = y,this -> c = c; } bool operator < ( const data &a )const{ return c > a.c; } }; ll gcd(ll a,ll b){ if( !b ) return a; return gcd(b,a%b); } ll big(ll n,ll p,ll m){ if( !p ) return 1; if( !(p % 2) ){ ll x = big(n,p/2,m); return (x * x) % m; } ll x = big(n,p-1,m); return ( (n % m) * x ) % m; } int X[ ] = {0,0,1,-1,1,-1,1,-1}; int Y[ ] = {1,-1,0,0,-1,1,1,-1}; int hx[ ] = {2,2,1,1,-2,-2,-1,-1}; int hy[ ] = {1,-1,2,-2,1,-1,2,-2}; const int N = 1e6; const int inf = 1e9; const ll mx = 1e18; const ll mxx = -1e18; const ll mod = 1e9 + 7; int I(){ int n; sc( n ); return n; } ll Il(){ ll n; sl( n ); return n; } string out,s,b; int a[ 110 ]; int add(char ch,int idx){ } int main(){ file(); int t = I(); Case( t ){ out = ""; cin >> s; int sz = s.length(); for(int i = 0; i < 110; i++) a[ i ] = 0; int idx = 0; cout << "Case #" << cs << ": " << out << endl; } return 0; }
[ "78817174+Sabuj-Kumar@users.noreply.github.com" ]
78817174+Sabuj-Kumar@users.noreply.github.com
a54557900eccdf8e79b70e10663b442df75a0d94
d3a033203fd6959cda5a0f5531ce3fd78422832f
/navigation/global_planner/include/global_planner/expander.h
c7fbbcfba8f5c06d2a0e56c570fc9f328ad4b802
[]
no_license
rsbGroup1/frobo_rsd
a3b832c671e736c17a81cd0e36bc386281a55fdc
6397f121e19589aabd6f969e1255b5935ecd9b61
refs/heads/master
2021-01-19T22:11:04.686040
2015-12-10T18:52:40
2015-12-10T18:52:40
42,850,212
0
0
null
null
null
null
UTF-8
C++
false
false
3,994
h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, 2013, Willow Garage, 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 Willow Garage, 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. * * Author: Eitan Marder-Eppstein * David V. Lu!! *********************************************************************/ #ifndef _EXPANDER_H #define _EXPANDER_H #include <global_planner/potential_calculator.h> #include <global_planner/planner_core.h> namespace global_planner { class Expander { public: Expander (PotentialCalculator* p_calc, int nx, int ny) : unknown_ (true), lethal_cost_ (253), neutral_cost_ (50), factor_ (3.0), p_calc_ (p_calc) { setSize (nx, ny); } virtual bool calculatePotentials (unsigned char* costs, double start_x, double start_y, double end_x, double end_y, int cycles, float* potential) = 0; /** * @brief Sets or resets the size of the map * @param nx The x size of the map * @param ny The y size of the map */ virtual void setSize (int nx, int ny) { nx_ = nx; ny_ = ny; ns_ = nx * ny; } /**< sets or resets the size of the map */ void setLethalCost (unsigned char lethal_cost) { lethal_cost_ = lethal_cost; } void setNeutralCost (unsigned char neutral_cost) { neutral_cost_ = neutral_cost; } void setFactor (float factor) { factor_ = factor; } void setHasUnknown (bool unknown) { unknown_ = unknown; } void clearEndpoint (unsigned char* costs, float* potential, int gx, int gy, int s) { int startCell = toIndex (gx, gy); for (int i = -s; i <= s; i++) { for (int j = -s; j <= s; j++) { int n = startCell + i + nx_ * j; if (potential[n] < POT_HIGH) continue; float c = costs[n] + neutral_cost_; float pot = p_calc_->calculatePotential (potential, c, n); potential[n] = pot; } } } protected: inline int toIndex (int x, int y) { return x + nx_ * y; } int nx_, ny_, ns_; /**< size of grid, in pixels */ bool unknown_; unsigned char lethal_cost_, neutral_cost_; int cells_visited_; float factor_; PotentialCalculator* p_calc_; }; } //end namespace global_planner #endif
[ "dowei14@student.sdu.dk" ]
dowei14@student.sdu.dk
a97db316eb68d4b867523074c8bda234e99eb4d4
e98b8922ee3d566d7b7193bc71d269ce69b18b49
/include/qpid/framing/FieldValue.h
3717d2dee86fc8db3130bbd9c8bd99d25891a89b
[]
no_license
QuarkCloud/qpid-lite
bfcf275eb5a99be3a1defb18331780d1b242dfa6
3818811d1b2eb70c9603c1e74045072b9a9b8cbc
refs/heads/master
2020-04-14T17:18:28.441389
2019-02-18T02:20:56
2019-02-18T02:20:56
163,975,774
1
1
null
null
null
null
UTF-8
C++
false
false
14,400
h
#ifndef QPID_FRAMING_FIELD_VALUE_H #define QPID_FRAMING_FIELD_VALUE_H 1 /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "qpid/sys/Exception.h" #include "qpid/framing/amqp_types.h" #include "qpid/framing/Buffer.h" #include "qpid/framing/FieldTable.h" #include "qpid/framing/Endian.h" #include "qpid/framing/Compile.h" #include <iostream> #include <memory> #include <vector> #include <assert.h> namespace qpid { namespace framing { /** * Exception that is the base exception for all field table errors. * * \ingroup clientapi */ class QPID_FRAMING_CLASS_EXTERN FieldValueException : public qpid::sys::Exception {}; /** * Exception thrown when we can't perform requested conversion * * \ingroup clientapi */ struct QPID_FRAMING_CLASS_EXTERN InvalidConversionException : public FieldValueException { InvalidConversionException() {} }; class List; /** * Value that can appear in an AMQP field table * * \ingroup clientapi */ class QPID_FRAMING_CLASS_EXTERN FieldValue { public: /* * Abstract type for content of different types */ class Data { public: virtual ~Data() {} virtual uint32_t encodedSize() const = 0; virtual void encode(Buffer& buffer) = 0; virtual void decode(Buffer& buffer) = 0; virtual bool operator==(const Data&) const = 0; virtual bool convertsToInt() const { return false; } virtual bool convertsToFloat() const { return false; } virtual bool convertsToString() const { return false; } virtual int64_t getInt() const { throw InvalidConversionException();} virtual double getFloat() const { throw InvalidConversionException();} virtual std::string getString() const { throw InvalidConversionException(); } virtual void print(std::ostream& out) const = 0; }; FieldValue(): data(0) {}; // Default assignment operator is fine void setType(uint8_t type); QPID_FRAMING_EXTERN uint8_t getType() const; Data& getData() { return *data; } uint32_t encodedSize() const { return 1 + data->encodedSize(); }; bool empty() const { return data.get() == 0; } void encode(Buffer& buffer); void decode(Buffer& buffer); QPID_FRAMING_EXTERN bool operator==(const FieldValue&) const; QPID_FRAMING_INLINE_EXTERN bool operator!=(const FieldValue& v) const { return !(*this == v); } QPID_FRAMING_EXTERN void print(std::ostream& out) const; template <typename T> bool convertsTo() const { return false; } template <typename T> T get() const { throw InvalidConversionException(); } template <class T, int W> T getIntegerValue() const; template <class T> T getIntegerValue() const; template <class T, int W> T getFloatingPointValue() const; template <int W> void getFixedWidthValue(unsigned char*) const; template <class T> bool get(T&) const; protected: FieldValue(uint8_t t, Data* d): typeOctet(t), data(d) {} private: uint8_t typeOctet; std::auto_ptr<Data> data; }; template <> inline bool FieldValue::convertsTo<int>() const { return data->convertsToInt(); } template <> inline bool FieldValue::convertsTo<int64_t>() const { return data->convertsToInt(); } template <> inline bool FieldValue::convertsTo<std::string>() const { return data->convertsToString(); } template <> inline bool FieldValue::convertsTo<float>() const { return data->convertsToFloat(); } template <> inline bool FieldValue::convertsTo<double>() const { return data->convertsToFloat(); } template <> inline int FieldValue::get<int>() const { return static_cast<int>(data->getInt()); } template <> inline int64_t FieldValue::get<int64_t>() const { return data->getInt(); } template <> inline float FieldValue::get<float>() const { return (float)data->getFloat(); } template <> inline double FieldValue::get<double>() const { return data->getFloat(); } template <> inline std::string FieldValue::get<std::string>() const { return data->getString(); } inline std::ostream& operator<<(std::ostream& out, const FieldValue& v) { v.print(out); return out; } template <int width> class FixedWidthValue : public FieldValue::Data { protected: uint8_t octets[width]; public: FixedWidthValue() {} FixedWidthValue(const uint8_t (&data)[width]) : octets(data) {} FixedWidthValue(const uint8_t* const data) { std::copy(data, data + width, octets); } uint32_t encodedSize() const { return width; } void encode(Buffer& buffer) { buffer.putRawData(octets, width); } void decode(Buffer& buffer) { buffer.getRawData(octets, width); } bool operator==(const Data& d) const { const FixedWidthValue<width>* rhs = dynamic_cast< const FixedWidthValue<width>* >(&d); if (rhs == 0) return false; else return std::equal(&octets[0], &octets[width], &rhs->octets[0]); } uint8_t* rawOctets() { return octets; } const uint8_t* rawOctets() const { return octets; } void print(std::ostream& o) const { o << "F" << width << ":"; }; }; template <class T> class FixedWidthIntValue : public FixedWidthValue<sizeof(T)> { public: FixedWidthIntValue(T v = 0) { endian::encodeInt(this->octets, v); } bool convertsToInt() const { return true; } int64_t getInt() const { return endian::decodeInt<T>(this->octets); } bool convertsToFloat() const { return true; } double getFloat() const { return (double)getInt(); } }; // Explicitly specialise width 1 variants to avoid using the byte swapping code template<> inline FixedWidthIntValue<bool>::FixedWidthIntValue(bool v) { this->octets[0] = v; } template<> inline FixedWidthIntValue<int8_t>::FixedWidthIntValue(int8_t v) { this->octets[0] = v; } template<> inline FixedWidthIntValue<uint8_t>::FixedWidthIntValue(uint8_t v) { this->octets[0] = v; } template<> inline int64_t FixedWidthIntValue<bool>::getInt() const { return this->octets[0]; } template<> inline int64_t FixedWidthIntValue<int8_t>::getInt() const { return this->octets[0]; } template<> inline int64_t FixedWidthIntValue<uint8_t>::getInt() const { return this->octets[0]; } template <class T> class FixedWidthFloatValue : public FixedWidthValue<sizeof(T)> { public: FixedWidthFloatValue(T v = 0) { endian::encodeFloat(this->octets, v); } bool convertsToFloat() const { return true; } double getFloat() const { return endian::decodeFloat<T>(this->octets); } }; class UuidData : public FixedWidthValue<16> { public: UuidData(); UuidData(const unsigned char* bytes); bool convertsToString() const; std::string getString() const; }; template <class T, int W> inline T FieldValue::getIntegerValue() const { FixedWidthValue<W>* const fwv = dynamic_cast< FixedWidthValue<W>* const>(data.get()); if (fwv) { return endian::decodeInt<T>(fwv->rawOctets()); } else { throw InvalidConversionException(); } } template <class T> inline T FieldValue::getIntegerValue() const { FixedWidthValue<1>* const fwv = dynamic_cast< FixedWidthValue<1>* const>(data.get()); if (fwv) { uint8_t* octets = fwv->rawOctets(); return octets[0]; } else { throw InvalidConversionException(); } } template <class T, int W> inline T FieldValue::getFloatingPointValue() const { const FixedWidthFloatValue<T>* fv = dynamic_cast<FixedWidthFloatValue<T>*>(data.get()); if (fv) { return endian::decodeFloat<T>(fv->rawOctets()); } else { throw InvalidConversionException(); } } template <int W> void FieldValue::getFixedWidthValue(unsigned char* value) const { FixedWidthValue<W>* const fwv = dynamic_cast< FixedWidthValue<W>* const>(data.get()); if (fwv) { std::copy(fwv->rawOctets(), fwv->rawOctets() + W, value); } else { throw InvalidConversionException(); } } template <> class FixedWidthValue<0> : public FieldValue::Data { public: // Implicit default constructor is fine uint32_t encodedSize() const { return 0; } void encode(Buffer&) {}; void decode(Buffer&) {}; bool operator==(const Data& d) const { const FixedWidthValue<0>* rhs = dynamic_cast< const FixedWidthValue<0>* >(&d); return rhs != 0; } void print(std::ostream& o) const { o << "F0"; }; }; template <int lenwidth> class VariableWidthValue : public FieldValue::Data { std::vector<uint8_t> octets; public: VariableWidthValue() {} VariableWidthValue(const std::vector<uint8_t>& data) : octets(data) {} VariableWidthValue(const uint8_t* start, const uint8_t* end) : octets(start, end) {} uint32_t encodedSize() const { return lenwidth + octets.size(); } void encode(Buffer& buffer) { buffer.putUInt<lenwidth>(octets.size()); if (octets.size() > 0) buffer.putRawData(&octets[0], octets.size()); }; void decode(Buffer& buffer) { uint32_t len = (uint32_t)buffer.getUInt<lenwidth>(); buffer.checkAvailable(len); octets.resize(len); if (len > 0) buffer.getRawData(&octets[0], len); } bool operator==(const Data& d) const { const VariableWidthValue<lenwidth>* rhs = dynamic_cast< const VariableWidthValue<lenwidth>* >(&d); if (rhs == 0) return false; else return octets==rhs->octets; } bool convertsToString() const { return true; } std::string getString() const { return std::string(octets.begin(), octets.end()); } void print(std::ostream& o) const { o << "V" << lenwidth << ":" << octets.size() << ":"; }; }; template <class T> class EncodedValue : public FieldValue::Data { T value; public: EncodedValue() {} EncodedValue(const T& v) : value(v) {} T& getValue() { return value; } const T& getValue() const { return value; } uint32_t encodedSize() const { return value.encodedSize(); } void encode(Buffer& buffer) { value.encode(buffer); }; void decode(Buffer& buffer) { value.decode(buffer); } bool operator==(const Data& d) const { const EncodedValue<T>* rhs = dynamic_cast< const EncodedValue<T>* >(&d); if (rhs == 0) return false; else return value==rhs->value; } void print(std::ostream& o) const { o << "[" << value << "]"; }; }; /** * Accessor that can be used to get values of type FieldTable, Array * and List. */ template <class T> inline bool FieldValue::get(T& t) const { const EncodedValue<T>* v = dynamic_cast< EncodedValue<T>* >(data.get()); if (v != 0) { t = v->getValue(); return true; } else { try { t = get<T>(); return true; } catch (const InvalidConversionException&) { return false; } } } class Str8Value : public FieldValue { public: QPID_FRAMING_EXTERN Str8Value(const std::string& v); }; class Str16Value : public FieldValue { public: QPID_FRAMING_EXTERN Str16Value(const std::string& v); }; class Var16Value : public FieldValue { public: QPID_FRAMING_EXTERN Var16Value(const std::string& v, uint8_t code); }; class Var32Value : public FieldValue { public: QPID_FRAMING_EXTERN Var32Value(const std::string& v, uint8_t code); }; class Struct32Value : public FieldValue { public: QPID_FRAMING_EXTERN Struct32Value(const std::string& v); }; class FloatValue : public FieldValue { public: QPID_FRAMING_EXTERN FloatValue(float f); }; class DoubleValue : public FieldValue { public: QPID_FRAMING_EXTERN DoubleValue(double f); }; /* * Basic integer value encodes as signed 32 bit */ class IntegerValue : public FieldValue { public: QPID_FRAMING_EXTERN IntegerValue(int v); }; class TimeValue : public FieldValue { public: QPID_FRAMING_EXTERN TimeValue(uint64_t v); }; class Integer64Value : public FieldValue { public: QPID_FRAMING_EXTERN Integer64Value(int64_t v); }; class Unsigned64Value : public FieldValue { public: QPID_FRAMING_EXTERN Unsigned64Value(uint64_t v); }; class FieldTableValue : public FieldValue { public: typedef FieldTable ValueType; QPID_FRAMING_EXTERN FieldTableValue(const FieldTable&); }; class ArrayValue : public FieldValue { public: QPID_FRAMING_EXTERN ArrayValue(const Array&); }; class VoidValue : public FieldValue { public: QPID_FRAMING_EXTERN VoidValue(); }; class BoolValue : public FieldValue { public: QPID_FRAMING_EXTERN BoolValue(bool); }; class Unsigned8Value : public FieldValue { public: QPID_FRAMING_EXTERN Unsigned8Value(uint8_t); }; class Unsigned16Value : public FieldValue { public: QPID_FRAMING_EXTERN Unsigned16Value(uint16_t); }; class Unsigned32Value : public FieldValue { public: QPID_FRAMING_EXTERN Unsigned32Value(uint32_t); }; class Integer8Value : public FieldValue { public: QPID_FRAMING_EXTERN Integer8Value(int8_t); }; class Integer16Value : public FieldValue { public: QPID_FRAMING_EXTERN Integer16Value(int16_t); }; typedef IntegerValue Integer32Value; class ListValue : public FieldValue { public: typedef List ValueType; QPID_FRAMING_EXTERN ListValue(const List&); }; class UuidValue : public FieldValue { public: QPID_FRAMING_EXTERN UuidValue(); QPID_FRAMING_EXTERN UuidValue(const unsigned char*); }; template <class T> bool getEncodedValue(FieldTable::ValuePtr vptr, T& value) { if (vptr) { const EncodedValue<T>* ev = dynamic_cast< EncodedValue<T>* >(&(vptr->getData())); if (ev != 0) { value = ev->getValue(); return true; } } return false; } }} // qpid::framing #endif /** QPID_FRAMING_FIELD_VALUE_H */
[ "romandion@163.com" ]
romandion@163.com
310e8d3e563acc13b6b19a608233702b1d53e6e9
09f872ea3be98ddceb4106c48e3169a3acb7a418
/src/Zlang/zsharp/AST/AstNumericBuilder.h
b9e26a24e0a87fa99a387e33e1efad9837ceb5e7
[]
no_license
obiwanjacobi/Zlang
ce51c3e5cdfcde13510a23b862519ea7947617e1
c9dea8b6a3dc6fd9bb6a556cdf515413d6e299dc
refs/heads/master
2021-07-15T17:48:36.377567
2020-10-11T15:13:43
2020-10-11T15:13:43
216,856,286
1
0
null
null
null
null
UTF-8
C++
false
false
1,620
h
#pragma once #include "AstNumeric.h" #include "../grammar/parser/zsharp_parserBaseVisitor.h" #include <antlr4-runtime.h> class AstNumericBuilder : protected zsharp_parserBaseVisitor { typedef zsharp_parserBaseVisitor base; public: AstNumericBuilder() : _parent(nullptr) {} AstNumericBuilder(std::shared_ptr<AstNode> parent) : _parent(parent) {} std::shared_ptr<AstNumeric> Build(zsharp_parserParser::NumberContext* numberCtx) { auto val = visitNumber(numberCtx); if (val.is<std::shared_ptr<AstNumeric>>()) { return val.as<std::shared_ptr<AstNumeric>>(); } return nullptr; } std::shared_ptr<AstNumeric> Test(antlr4::ParserRuleContext* ctx) { auto val = visit(ctx); if (val.is<std::shared_ptr<AstNumeric>>()) { return val.as<std::shared_ptr<AstNumeric>>(); } return nullptr; } protected: antlrcpp::Any aggregateResult(antlrcpp::Any aggregate, const antlrcpp::Any& nextResult) override; antlrcpp::Any visitNumber(zsharp_parserParser::NumberContext* ctx) override; antlrcpp::Any visitNumber_bin(zsharp_parserParser::Number_binContext* ctx) override; antlrcpp::Any visitNumber_oct(zsharp_parserParser::Number_octContext* ctx) override; antlrcpp::Any visitNumber_dec(zsharp_parserParser::Number_decContext* ctx) override; antlrcpp::Any visitNumber_hex(zsharp_parserParser::Number_hexContext* ctx) override; antlrcpp::Any visitNumber_char(zsharp_parserParser::Number_charContext* ctx) override; private: std::shared_ptr<AstNode> _parent; };
[ "marc.jacobi@macaw.nl" ]
marc.jacobi@macaw.nl
95c92dace2a1e9b50d987cd0981dc21ae1ccc4ed
29df6c19670409064a1243847a5c34123acc6734
/DasDatabaseManager/tableinfo/userinfo.cpp
e28f8362d9881e06ec67a947046470b9cb84a161
[]
no_license
ErroMsg/das-project
15f63a3ce5d31a37f633c9ac7b315ae1f06cd32b
e09f03dca9b5bb14e2fa3c18935b320d0a5aef9a
refs/heads/main
2023-01-22T15:39:16.376516
2020-12-08T12:59:16
2020-12-08T12:59:16
319,638,839
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
#include "userinfo.h" UserInfo::UserInfo() : BaseInfo() { } QStringList UserInfo::getColumns() { QStringList colums; colums << "id" << "user_name" << "user_pwd" << "user_type"; return colums; } void UserInfo::parseData() { if(m_rowData.isEmpty() || m_rowData.size() < 4) return; int i = 0; id = m_rowData.at(i++).toInt(); user_name = m_rowData.at(i++).toString(); user_password = m_rowData.at(i++).toString(); user_type = m_rowData.at(i++).toInt(); } const QVariantList UserInfo::getVariants() { QVariantList varlist; varlist<<user_name<<user_password<<user_type; return varlist; } int UserInfo::getId() const { return id; } void UserInfo::setId(int value) { id = value; } QString UserInfo::getUser_name() const { return user_name; } void UserInfo::setUser_name(const QString &value) { user_name = value; } QString UserInfo::getUser_password() const { return user_password; } void UserInfo::setUser_password(const QString &value) { user_password = value; } int UserInfo::getUser_type() const { return user_type; } void UserInfo::setUser_type(int value) { user_type = value; }
[ "admin@localhost.localdomain" ]
admin@localhost.localdomain
313bab70712dadb2686038b81877246e6b370e8b
652cec5b7ca27dada2104f2e47be0193edc15c09
/high_school/Extra programs/ARRAY_QU.CPP
7d287fa8e6c1be6b40390bdbb5830c44084b3188
[]
no_license
rahuljain/playground_CPlusPlus
1693b75bbffe1a14219591ff7189f4d09540cee4
8698ceec1a24f8fa012324346d5e82063aa99a37
refs/heads/master
2020-12-24T17:26:08.390455
2012-06-11T03:36:56
2012-06-11T03:36:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
cpp
/* Programme written by :- Rishabh Mehta XII-D 2003-04 For array implementation of queues. */ #include<iostream.h> #include<conio.h> #include<process.h> const n=10; class Queue { int Q[n]; int fr,re; public: Queue() { fr=re=-1; } void add(); void Delete(); void display(); }; void main() { clrscr(); Queue q; char ch,ch2; do { clrscr(); cout<<"1.......Add\n"; cout<<"2.......Deleted\n"; cout<<"3.......Display\n"; cout<<"4.......Quit\n"; cout<<"\nInput an Option : "; cin>>ch; switch(ch) { case '1' : q.add(); break; case '2' : q.Delete(); break; case '3' : q.display(); break; case '4' : exit(0); } cout<<endl<<endl<<"Continue............. : "; cin>>ch2; }while(ch2=='y'); getch(); } void Queue::add() { if((fr==0 && re==n-1) || (fr==re+1)) { cout<<"Overflow......Overflow"; getch(); return; } if(re==n-1) re=0; else if(fr==-1) fr=re=0; else re++; cin>>Q[re]; } void Queue::Delete() { if(fr==-1) cout<<endl<<"Empty Queue"; else { cout<<endl<<"Element Deleted out : "; cout<<Q[fr]; } if(fr==re) fr=re=-1; else if(fr==n-1) fr=0; else fr++; getch(); } void Queue::display() { if(fr<=re) { for(int i=fr;fr<=re;fr++) cout<<Q[i]<<' '; } } /* Output:- 1.......Puqh 2.......Pop 3.......Display 4.......Quit Input an Option : 1 Give the data : 1 Continue............. : y ( After inputing.........) Input an Option : 3 3 2 1 Input an Option : 2 Element Deleted out : 3 Input an Option : 3 2 1 Continue............. : n */
[ "rjain@fanfueled.com" ]
rjain@fanfueled.com
1a5193dba42db68a55106d5c408e125d54ccf832
29a4c1e436bc90deaaf7711e468154597fc379b7
/modules/gsl_specfun/include/nt2/toolbox/gsl_specfun/function/simd/vmx/spu/gsl_sf_lngamma.hpp
64742391a3d07671fe0336b5c1a27dd3728865b6
[ "BSL-1.0" ]
permissive
brycelelbach/nt2
31bdde2338ebcaa24bb76f542bd0778a620f8e7c
73d7e8dd390fa4c8d251c6451acdae65def70e0b
refs/heads/master
2021-01-17T12:41:35.021457
2011-04-03T17:37:15
2011-04-03T17:37:15
1,263,345
1
0
null
null
null
null
UTF-8
C++
false
false
756
hpp
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_VMX_SPU_GSL_SF_LNGAMMA_HPP_INCLUDED #define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_VMX_SPU_GSL_SF_LNGAMMA_HPP_INCLUDED #include <nt2/toolbox/gsl_specfun/function/simd/vmx/common/gsl_sf_lngamma.hpp> #endif
[ "joel.falcou@lri.fr" ]
joel.falcou@lri.fr
eb9ff9b6216d6729627af7a4d220a446932707f0
42a750f33ad47cef7d384fcf1aa7304715239ef9
/CS161/A9/Board.cpp
2ce87b2d942790a3f03c01295ed3f4130ac61dec
[]
no_license
sunny-aguilar/OSU
7a6f6e5597778563b9161fb304b83469160104e1
1ca59072e1e52f8f03d4ba7c864985aa43334015
refs/heads/master
2020-06-28T03:55:16.270665
2016-12-07T07:52:58
2016-12-07T07:52:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,605
cpp
/********************************************************************* ** Author: Pedro Torres-Picon ** Date: 07/29/2016 ** Description: Module 9, Assignment 9 - Part of a two-player tic-tac-toe game. This file is part of the Board class, which defines a game board and the things that can be done within it. This is the implementation file for the Board class, which defines all the functions the class contains. *********************************************************************/ #include "Board.hpp" #include <string> #include <iostream> /********************************************************************* ** Description: ** This is the default constuctor that sets the every value on the board array to empty and numMoves to 0 *********************************************************************/ Board::Board() { numMoves = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { moves[i][j] = '.'; } } } /********************************************************************* ** Description: makeMove() ** This function places a move on the board. It takes coordinates and an x or o char and places the corresponding char on that slot in the board if the slot is available. If it is not available, then it returns false. *********************************************************************/ bool Board::makeMove(int xCoord, int yCoord, char playerChar) { bool success = false; // variable to hold whether the move was successful if (moves[xCoord][yCoord] == '.') // if the space is empty, place the move { moves[xCoord][yCoord] = playerChar; success = true; numMoves++; } return success; } /********************************************************************* ** Description: gameState() ** This is the function that holds most of the game logic, as it is used to check the status of the game. It uses a series of conditional statements and loops to go through every scenario and return whether the game is still going, or it has ended in a draw or a winner. *********************************************************************/ State Board::gameState() { State gameState = UNFINISHED; // this loop checks whether there is a winning combination in the rows and columns of the grid for (int i = 0; i < 3; i++) { if ((moves[i][0] == moves[i][1] && moves[i][1] == moves[i][2]) || (moves[0][i] == moves[1][i] && moves[1][i] == moves[2][i])) { if (moves[i][i] == 'x') { gameState = X_WON; } if (moves[i][i] == 'o') { gameState = O_WON; } } } // and this if statement checks the diagonals if ((moves[0][0] == moves[1][1] && moves[1][1] == moves[2][2]) || (moves[0][2] == moves[1][1] && moves[1][1] == moves[2][0])) { if (moves[1][1] == 'x') { gameState = X_WON; } if (moves[1][1] == 'o') { gameState = O_WON; } } // finally this checks to see if there are no more moves left (9 is the max)and calls a draw if (numMoves > 8 && gameState == UNFINISHED) { gameState = DRAW; } return gameState; } /********************************************************************* ** Description: print() ** In this function we use a for loop to print each line of the board along with labels indicating x and y coordinates. *********************************************************************/ void Board::print() { std::cout << " 0 1 2" << std::endl; for (int i = 0; i < 3; i++) { std::cout << i << " " << moves[i][0] << " " << moves[i][1] << " " << moves[i][2] << std::endl; } }
[ "pedro@pedrotp.com" ]
pedro@pedrotp.com
d606b7af895866f8b127b4460e404db5c54cddc1
b20f72e5014457aac7b603b9b8775e4451efc740
/Project1/Enemy.h
f1cc03b2c1624dd4d718158395405bc0bc3ffe76
[]
no_license
gitJaesik/3dmp
51613e268428f2d28c05bb479ee9f18c47e0b49f
200e5121a958ded65662e2d8633ee3bad22b7f1b
refs/heads/master
2021-01-12T01:06:56.320113
2017-04-16T06:56:31
2017-04-16T06:56:31
78,345,686
0
0
null
null
null
null
UTF-8
C++
false
false
129
h
#pragma once #include "Actor.h" class Enemy : public Actor { public: Enemy(); ~Enemy(); virtual void update() override; };
[ "maguire1815@gmail.com" ]
maguire1815@gmail.com
e37123470a9cca498fa6dfadb5fc9d4cf249ba29
8dc84558f0058d90dfc4955e905dab1b22d12c08
/net/reporting/reporting_delivery_agent.cc
467bfd9959ab48bcf211211e2d19493f4bba640a
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
8,897
cc
// Copyright 2017 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/reporting/reporting_delivery_agent.h" #include <map> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/bind.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/time/tick_clock.h" #include "base/timer/timer.h" #include "base/values.h" #include "net/reporting/reporting_cache.h" #include "net/reporting/reporting_delegate.h" #include "net/reporting/reporting_endpoint_manager.h" #include "net/reporting/reporting_observer.h" #include "net/reporting/reporting_report.h" #include "net/reporting/reporting_uploader.h" #include "url/gurl.h" #include "url/origin.h" namespace net { namespace { void SerializeReports(const std::vector<const ReportingReport*>& reports, base::TimeTicks now, std::string* json_out) { base::ListValue reports_value; for (const ReportingReport* report : reports) { std::unique_ptr<base::DictionaryValue> report_value = std::make_unique<base::DictionaryValue>(); report_value->SetInteger("age", (now - report->queued).InMilliseconds()); report_value->SetString("type", report->type); report_value->SetString("url", report->url.spec()); report_value->SetKey("report", report->body->Clone()); reports_value.Append(std::move(report_value)); } bool json_written = base::JSONWriter::Write(reports_value, json_out); DCHECK(json_written); } class ReportingDeliveryAgentImpl : public ReportingDeliveryAgent, public ReportingObserver { public: ReportingDeliveryAgentImpl(ReportingContext* context) : context_(context), timer_(std::make_unique<base::OneShotTimer>()), weak_factory_(this) { context_->AddObserver(this); } // ReportingDeliveryAgent implementation: ~ReportingDeliveryAgentImpl() override { context_->RemoveObserver(this); } void SetTimerForTesting(std::unique_ptr<base::Timer> timer) override { DCHECK(!timer_->IsRunning()); timer_ = std::move(timer); } // ReportingObserver implementation: void OnCacheUpdated() override { if (CacheHasReports() && !timer_->IsRunning()) { SendReports(); StartTimer(); } } private: class Delivery { public: Delivery(const GURL& endpoint, std::vector<const ReportingReport*> reports) : endpoint(endpoint), reports(std::move(reports)) {} ~Delivery() = default; const GURL endpoint; std::vector<const ReportingReport*> reports; }; using OriginGroup = std::pair<url::Origin, std::string>; bool CacheHasReports() { std::vector<const ReportingReport*> reports; context_->cache()->GetReports(&reports); return !reports.empty(); } void StartTimer() { timer_->Start(FROM_HERE, policy().delivery_interval, base::BindRepeating(&ReportingDeliveryAgentImpl::OnTimerFired, base::Unretained(this))); } void OnTimerFired() { if (CacheHasReports()) { SendReports(); StartTimer(); } } void SendReports() { std::vector<const ReportingReport*> reports; cache()->GetNonpendingReports(&reports); // Mark all of these reports as pending, so that they're not deleted out // from under us while we're checking permissions (possibly on another // thread). cache()->SetReportsPending(reports); // First determine which origins we're allowed to upload reports about. std::set<url::Origin> origins; for (const ReportingReport* report : reports) { origins.insert(url::Origin::Create(report->url)); } delegate()->CanSendReports( std::move(origins), base::BindOnce(&ReportingDeliveryAgentImpl::OnSendPermissionsChecked, weak_factory_.GetWeakPtr(), std::move(reports))); } void OnSendPermissionsChecked(std::vector<const ReportingReport*> reports, std::set<url::Origin> allowed_origins) { // Sort reports into (origin, group) buckets. std::map<OriginGroup, std::vector<const ReportingReport*>> origin_group_reports; for (const ReportingReport* report : reports) { url::Origin origin = url::Origin::Create(report->url); if (allowed_origins.find(origin) == allowed_origins.end()) continue; OriginGroup origin_group(origin, report->group); origin_group_reports[origin_group].push_back(report); } // Find endpoint for each (origin, group) bucket and sort reports into // endpoint buckets. Don't allow concurrent deliveries to the same (origin, // group) bucket. std::map<GURL, std::vector<const ReportingReport*>> endpoint_reports; for (auto& it : origin_group_reports) { const OriginGroup& origin_group = it.first; if (base::ContainsKey(pending_origin_groups_, origin_group)) continue; GURL endpoint_url; if (!endpoint_manager()->FindEndpointForOriginAndGroup( origin_group.first, origin_group.second, &endpoint_url)) { continue; } cache()->MarkClientUsed(origin_group.first, endpoint_url); endpoint_reports[endpoint_url].insert( endpoint_reports[endpoint_url].end(), it.second.begin(), it.second.end()); pending_origin_groups_.insert(origin_group); } // Keep track of which of these reports we don't queue for delivery; we'll // need to mark them as not-pending. std::unordered_set<const ReportingReport*> undelivered_reports( reports.begin(), reports.end()); // Start a delivery to each endpoint. for (auto& it : endpoint_reports) { const GURL& endpoint = it.first; const std::vector<const ReportingReport*>& reports = it.second; endpoint_manager()->SetEndpointPending(endpoint); std::string json; SerializeReports(reports, tick_clock()->NowTicks(), &json); int max_depth = 0; for (const ReportingReport* report : reports) { undelivered_reports.erase(report); if (report->depth > max_depth) max_depth = report->depth; } // TODO: Calculate actual max depth. uploader()->StartUpload( endpoint, json, max_depth, base::BindOnce( &ReportingDeliveryAgentImpl::OnUploadComplete, weak_factory_.GetWeakPtr(), std::make_unique<Delivery>(endpoint, std::move(reports)))); } cache()->ClearReportsPending( {undelivered_reports.begin(), undelivered_reports.end()}); } void OnUploadComplete(const std::unique_ptr<Delivery>& delivery, ReportingUploader::Outcome outcome) { cache()->IncrementEndpointDeliveries( delivery->endpoint, delivery->reports, outcome == ReportingUploader::Outcome::SUCCESS); if (outcome == ReportingUploader::Outcome::SUCCESS) { cache()->RemoveReports(delivery->reports, ReportingReport::Outcome::DELIVERED); endpoint_manager()->InformOfEndpointRequest(delivery->endpoint, true); } else { cache()->IncrementReportsAttempts(delivery->reports); endpoint_manager()->InformOfEndpointRequest(delivery->endpoint, false); } if (outcome == ReportingUploader::Outcome::REMOVE_ENDPOINT) cache()->RemoveClientsForEndpoint(delivery->endpoint); for (const ReportingReport* report : delivery->reports) { pending_origin_groups_.erase( OriginGroup(url::Origin::Create(report->url), report->group)); } endpoint_manager()->ClearEndpointPending(delivery->endpoint); cache()->ClearReportsPending(delivery->reports); } const ReportingPolicy& policy() { return context_->policy(); } const base::TickClock* tick_clock() { return context_->tick_clock(); } ReportingDelegate* delegate() { return context_->delegate(); } ReportingCache* cache() { return context_->cache(); } ReportingUploader* uploader() { return context_->uploader(); } ReportingEndpointManager* endpoint_manager() { return context_->endpoint_manager(); } ReportingContext* context_; std::unique_ptr<base::Timer> timer_; // Tracks OriginGroup tuples for which there is a pending delivery running. // (Would be an unordered_set, but there's no hash on pair.) std::set<OriginGroup> pending_origin_groups_; base::WeakPtrFactory<ReportingDeliveryAgentImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ReportingDeliveryAgentImpl); }; } // namespace // static std::unique_ptr<ReportingDeliveryAgent> ReportingDeliveryAgent::Create( ReportingContext* context) { return std::make_unique<ReportingDeliveryAgentImpl>(context); } ReportingDeliveryAgent::~ReportingDeliveryAgent() = default; } // namespace net
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
f374be096d38a544b7f656cddfa8ab1231826bea
fb9b97269ad61497ae7a667a58d2e9638b6c0cf5
/src/spmxml/spmxml.cpp
8d258a27cb4663df7e86cc005a4dd0a4e83801c7
[]
no_license
smurav/gis36
b98e4b485ae205a1025d8ccb280bbc3412b9961b
3c7ad6e43cb3bdcb00622ee4008dde0ad96ce56d
refs/heads/master
2016-09-05T13:36:53.446309
2012-09-07T05:59:56
2012-09-07T05:59:56
2,359,643
22
9
null
null
null
null
WINDOWS-1251
C++
false
false
15,883
cpp
// Реализация классов для работы с XML, XPath, DTD #include "stdspm.h" #include "spmxml.h" CSpmXml::CSpmXml(bool bAutoDestroy) : m_pXMLDoc(0), m_pCurNode(0), m_bModified(false), m_pCurNodeSet(0), m_nCurItem(-1), m_bAutoDestroy(bAutoDestroy) { } CSpmXml::CSpmXml(xmlDocPtr pDoc, bool bAutoDestroy, bool bModified) { m_pXMLDoc = pDoc; if (pDoc) m_pCurNode = xmlDocGetRootElement(pDoc); else m_pCurNode = 0; m_bModified = bModified; m_bAutoDestroy = bAutoDestroy; m_pCurNodeSet = 0; m_nCurItem = -1; } CSpmXml::CSpmXml(xmlNodePtr pNode, bool bAutoDestroy, bool bModified) { if (pNode) { m_pXMLDoc = pNode->doc; m_pCurNode = pNode; } else { m_pXMLDoc = 0; m_pCurNode = 0; } m_bModified = bModified; m_bAutoDestroy = bAutoDestroy; m_pCurNodeSet = 0; m_nCurItem = -1; } bool CSpmXml::Attach(xmlDocPtr pDoc, bool bAutoDestroy, bool bModified) { if (pDoc == 0) return false; Detach(); m_pXMLDoc = pDoc; m_pCurNode = xmlDocGetRootElement(pDoc); m_bModified = bModified; m_bAutoDestroy = bAutoDestroy; return true; } bool CSpmXml::Attach(xmlNodePtr pNode, bool bAutoDestroy, bool bModified) { if (pNode == 0) return false; Detach(); m_pCurNode = pNode; m_pXMLDoc = pNode->doc; m_bModified = bModified; m_bAutoDestroy = bAutoDestroy; return true; } void CSpmXml::Detach() { m_pCurNode = 0; m_pXMLDoc = 0; m_bModified = false; m_bAutoDestroy = true; m_pCurNodeSet = 0; m_nCurItem = -1; m_lstNodes.clear(); } void CSpmXml::Destroy() { Detach(); if (m_pXMLDoc) { xmlFreeDoc(m_pXMLDoc); m_pXMLDoc = 0; } } CSpmXml::~CSpmXml() { if (m_bAutoDestroy) Destroy(); } bool CSpmXml::New(const QString& strRootNode, const QString& strDTDFile) { Destroy(); m_pXMLDoc = xmlNewDoc(BAD_CAST "1.0"); if (0 == m_pXMLDoc) return false; m_pCurNode = xmlNewNode(0, BAD_CAST strRootNode.toUtf8().data()); if (0 == m_pCurNode) return false; xmlDocSetRootElement(m_pXMLDoc, m_pCurNode); if (strDTDFile.size()) xmlCreateIntSubset(m_pXMLDoc, BAD_CAST strRootNode.toUtf8().data(), NULL, BAD_CAST strDTDFile.toUtf8().data()); SetModified(); return true; } bool CSpmXml::Load(const QString& strFileName, bool bDTDValidation) { xmlParserCtxtPtr pXMLParser = xmlNewParserCtxt(); if (0 == pXMLParser) return false; int nOptions = XML_PARSE_NOBLANKS; if (bDTDValidation) nOptions |= XML_PARSE_DTDVALID; m_pXMLDoc = xmlCtxtReadFile(pXMLParser, strFileName.toLocal8Bit().data(), NULL, nOptions); if (0 == m_pXMLDoc) { xmlFreeParserCtxt(pXMLParser); return false; } // Проверка корректности структуры if (bDTDValidation && (false == pXMLParser->valid)) { xmlFreeParserCtxt(pXMLParser); return false; } m_pCurNode = xmlDocGetRootElement(m_pXMLDoc); if (0 == m_pCurNode) return false; SetModified(false); xmlFreeParserCtxt(pXMLParser); return true; } bool CSpmXml::LoadXML(const QString& strXML, bool bDTDValidation) { xmlParserCtxtPtr pXMLParser = xmlNewParserCtxt(); if (0 == pXMLParser) return false; int nOptions = XML_PARSE_NOBLANKS; if (bDTDValidation) nOptions |= XML_PARSE_DTDVALID; m_pXMLDoc = xmlCtxtReadDoc(pXMLParser, (xmlChar*)strXML.toUtf8().data(), "", NULL, nOptions); if (0 == m_pXMLDoc) { xmlFreeParserCtxt(pXMLParser); return false; } // Проверка корректности структуры if (bDTDValidation && (false == pXMLParser->valid)) { xmlFreeParserCtxt(pXMLParser); return false; } m_pCurNode = xmlDocGetRootElement(m_pXMLDoc); if (0 == m_pCurNode) return false; SetModified(false); xmlFreeParserCtxt(pXMLParser); return true; } bool CSpmXml::Save(const QString& strFileName) { if (0 == m_pXMLDoc) return false; if (-1 == xmlSaveFormatFileEnc(strFileName.toLocal8Bit(), m_pXMLDoc, "UTF-8", 1)) return false; SetModified(false); return true; } bool CSpmXml::SaveXML(QString& strXML, const QString& strCodec) { strXML.clear(); if (0 == m_pXMLDoc) return false; int len = 0; xmlChar* pDoc = 0; xmlDocDumpMemoryEnc(m_pXMLDoc, &pDoc, &len, strCodec.toLocal8Bit()); if ((0 == pDoc) || (0 == len)) return false; //strXML.fromLocal8Bit((const char*)pDoc); strXML = (const char*)pDoc; return true; } bool CSpmXml::IsModified() { return m_bModified; } void CSpmXml::SetModified(bool bModified) { m_bModified = bModified; } xmlNodePtr CSpmXml::AddNode(const QString& strNodeName, xmlNodePtr pContext, char nContext, const QString& strContent) { pContext = GetNode(pContext); if (0 == pContext) return 0; xmlNodePtr pResNode = xmlNewChild(pContext, 0, BAD_CAST strNodeName.toUtf8().data(), strContent.isEmpty()? 0: BAD_CAST strContent.toUtf8().data()); if (0 == pResNode) return 0; xmlUnlinkNode(pResNode); if (!AddNode(pResNode, pContext, nContext)) { xmlFreeNode(pResNode); return 0; } return pResNode; } bool CSpmXml::AddNode(xmlNodePtr pNode, xmlNodePtr pContext, char nContext) { if (0 == pNode) return false; pContext = GetNode(pContext); if (0 == pContext) return false; xmlNodePtr pCurNode = 0; switch (nContext) { case SPM_XML_CHILD: pCurNode = xmlAddChild(pContext, pNode); break; case SPM_XML_NEXT_SIBLING: pCurNode = xmlAddNextSibling(pContext, pNode); break; case SPM_XML_PREV_SIBLING: pCurNode = xmlAddPrevSibling(pContext, pNode); break; default: return false; } if (0 == pCurNode) return false; m_pCurNode = pCurNode; SetModified(); return true; } bool CSpmXml::MoveNode(xmlNodePtr pNode, xmlNodePtr pContext, char nContext) { if (0 == pNode) return false; xmlUnlinkNode(pNode); return AddNode(pNode, pContext, nContext); } bool CSpmXml::DeleteNode(xmlNodePtr pNode) { if (0 == pNode) { if (0 == m_pCurNode) return false; pNode = m_pCurNode; m_pCurNode = m_pCurNode->parent; } xmlUnlinkNode(pNode); xmlFreeNode(pNode); SetModified(); return true; } bool CSpmXml::DeleteNodes(const QString& strXPathQuery, xmlNodePtr pParent) { if (strXPathQuery.isEmpty()) return false; pParent = GetNode(pParent); if (0 == pParent) return false; QString strQuery; if (strXPathQuery.left(2) != "//") // локальный запрос { strQuery = (char *)xmlGetNodePath(pParent); strQuery += strXPathQuery; } else strQuery = strXPathQuery; xmlXPathContextPtr pContext = xmlXPathNewContext(m_pXMLDoc); if (0 == pContext) return false; xmlXPathObjectPtr pQuery = xmlXPathEvalExpression(BAD_CAST strQuery.toUtf8().data(), pContext); xmlXPathFreeContext(pContext); if (0 == pQuery) return false; xmlNodeSetPtr pNodeSet = pQuery->nodesetval; if ((0 == pNodeSet) || (0 == pNodeSet->nodeNr)) return false; for (int i = 0; i < pNodeSet->nodeNr; i++) { xmlNodePtr pNode = pNodeSet->nodeTab[i]; xmlUnlinkNode(pNode); SetModified(); } xmlXPathFreeNodeSet(pNodeSet); return true; } QString CSpmXml::GetPath(xmlNodePtr pNode) { QString strRes; pNode = GetNode(pNode); if (0 == pNode) return strRes; return QString::fromUtf8((char *)xmlGetNodePath(pNode)); } QString CSpmXml::GetName(xmlNodePtr pNode) { QString strRes; pNode = GetNode(pNode); if (0 == pNode) return strRes; return QString::fromUtf8((char *)pNode->name); } QVariant CSpmXml::GetValue(xmlNodePtr pNode) { QVariant vtRes; pNode = GetNode(pNode); if (0 == pNode) return vtRes; if (pNode->type != XML_TEXT_NODE && pNode->type != XML_COMMENT_NODE) // patch by vpasha 01.09.09 return vtRes; QString strValue = QString::fromUtf8((char *)xmlNodeGetContent(pNode)); if (strValue.startsWith(":", Qt::CaseInsensitive)) // Возможно хранится вариант { vtRes = UnpackValue(strValue); if (vtRes.isValid()) return vtRes; else return strValue; } else return strValue; } bool CSpmXml::SetValue(const QVariant& vtValue, xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return false; QString strValue = PackValue(vtValue); if (strValue.isEmpty()) return false; xmlNodeSetContent(pNode, BAD_CAST strValue.toUtf8().data()); SetModified(); return true; } QVariant CSpmXml::GetAttr(const QString& strAttrName, xmlNodePtr pNode) { QVariant vtRes; pNode = GetNode(pNode); if (0 == pNode) return vtRes; if (!xmlHasProp(pNode, BAD_CAST strAttrName.toUtf8().data())) return vtRes; QString strValue = QString::fromUtf8((char *)xmlGetProp(pNode, BAD_CAST strAttrName.toUtf8().data())); if (strValue.startsWith(":", Qt::CaseInsensitive)) // Возможно хранится вариант { vtRes = UnpackValue(strValue); if (vtRes.isValid()) return vtRes; else return strValue; } else return strValue; } QString CSpmXml::PackValue(const QVariant& vtValue) { QString strValue; switch (vtValue.type()) { case QVariant::Size: { QSize size = vtValue.toSize(); strValue.sprintf(":%s:%d:%d", vtValue.typeName(), size.width(), size.height()); } break; case QVariant::Point: { QPoint pt = vtValue.toPoint(); strValue.sprintf(":%s:%d:%d", vtValue.typeName(), pt.x(), pt.y()); } break; default: strValue = vtValue.toString(); break; }; return strValue; } QVariant CSpmXml::UnpackValue(const QString& strValue) { QVariant vtRes; QStringList parts = strValue.split(":", QString::SkipEmptyParts); if (parts.size() == 0) return vtRes; switch(QVariant::nameToType(parts.at(0).toUtf8().data())) { case QVariant::Size: { if (parts.size() != 3) break; return QSize(parts.at(1).toInt(), parts.at(2).toInt()); } break; case QVariant::Point: { if (parts.size() != 3) break; return QPoint(parts.at(1).toInt(), parts.at(2).toInt()); } break; } return vtRes; } bool CSpmXml::SetAttr(const QString& strAttrName, const QVariant& vtAttrVal, xmlNodePtr pNode, bool bCreate) { pNode = GetNode(pNode); if (0 == pNode) return false; QString strValue = PackValue(vtAttrVal); if (0 == xmlHasProp(pNode, BAD_CAST strAttrName.toUtf8().data())) { if (false == bCreate) return false; return 0 != xmlNewProp(pNode, BAD_CAST strAttrName.toUtf8().data(), BAD_CAST strValue.toUtf8().data()); } bool bRes = (0 != xmlSetProp(pNode, BAD_CAST strAttrName.toUtf8().data(), BAD_CAST strValue.toUtf8().data())); if (bRes) SetModified(); return bRes; } bool CSpmXml::DeleteAttr(const QString& strAttrName, xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return false; bool bRes = (0 == xmlUnsetProp(pNode, BAD_CAST strAttrName.toUtf8().data())); if (bRes) SetModified(); return bRes; } QString CSpmXml::GetQuery(QStringList lstKeys, xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return ""; QStringList strQuery("//"); strQuery.append(QString::fromUtf8((char *)pNode->name)); if (lstKeys.size()) { strQuery.append("["); for (int i = 0; i < lstKeys.size(); i++) { QVariant vtValue = GetAttr(lstKeys.at(i)); if (!vtValue.isValid()) return ""; if (i > 0) strQuery.append("and"); strQuery.append("(@"); strQuery.append(lstKeys.at(i)); strQuery.append("='"); strQuery.append(vtValue.toString()); strQuery.append("')"); } strQuery.append("]"); } return strQuery.join(""); } xmlNodePtr CSpmXml::Clone(xmlNodePtr pNode, bool bDeep) { pNode = GetNode(pNode); if (0 == pNode) return 0; int nRecursive = 1; if (!bDeep) nRecursive = 2; return xmlCopyNode(pNode, nRecursive); } xmlNodePtr CSpmXml::GetPosition() { if (0 == m_pXMLDoc) return 0; if (0 == m_pCurNode) m_pCurNode = xmlDocGetRootElement(m_pXMLDoc); return m_pCurNode; } void CSpmXml::SetPosition(xmlNodePtr pNode) { if (0 == m_pXMLDoc) return; if (pNode) m_pCurNode = pNode; else m_pCurNode = xmlDocGetRootElement(m_pXMLDoc); } xmlNodePtr CSpmXml::MoveParent() { xmlNodePtr pNode = GetNode(0); if (0 == pNode) return 0; if (0 == pNode->parent) return 0; m_pCurNode = pNode->parent; return m_pCurNode; } bool CSpmXml::HasChilds(xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return false; return 0 != pNode->children; } xmlNodePtr CSpmXml::MoveFirstChild() { xmlNodePtr pNode = GetNode(0); if (0 == pNode) return 0; if (0 == pNode->children) return 0; m_pCurNode = pNode->children; return m_pCurNode; } xmlNodePtr CSpmXml::MoveNextSibling() { xmlNodePtr pNode = GetNode(0); if (0 == pNode) return 0; if (0 == pNode->next) return 0; m_pCurNode = pNode->next; return m_pCurNode; } xmlNodePtr CSpmXml::MoveFirst(const QString& strXPathQuery, xmlNodePtr pParent, int* pnCount) { if (strXPathQuery.isEmpty()) return 0; pParent = GetNode(pParent); if (0 == pParent) return 0; QString strQuery; if (strXPathQuery.left(2) != "//") // локальный запрос { strQuery = (char *)xmlGetNodePath(pParent); strQuery += strXPathQuery; } else strQuery = strXPathQuery; xmlXPathContextPtr pContext = xmlXPathNewContext(m_pXMLDoc); if (0 == pContext) return 0; xmlXPathObjectPtr pQuery = xmlXPathEvalExpression(BAD_CAST strQuery.toUtf8().data(), pContext); xmlXPathFreeContext(pContext); if (0 == pQuery) return 0; if (m_pCurNodeSet) { xmlXPathFreeNodeSet(m_pCurNodeSet); m_pCurNodeSet = 0; } m_nCurItem = 0; m_pCurNodeSet = pQuery->nodesetval; if (0 == m_pCurNodeSet) return 0; if (pnCount) *pnCount = m_pCurNodeSet->nodeNr; if (0 == m_pCurNodeSet->nodeNr) return 0; m_pCurNode = m_pCurNodeSet->nodeTab[m_nCurItem]; return m_pCurNode; } xmlNodePtr CSpmXml::MoveNext() { if (0 == m_pXMLDoc) return 0; if (0 == m_pCurNodeSet) return 0; m_nCurItem++; if (m_nCurItem < m_pCurNodeSet->nodeNr) { m_pCurNode = m_pCurNodeSet->nodeTab[m_nCurItem]; return m_pCurNode; } else { xmlXPathFreeNodeSet(m_pCurNodeSet); m_pCurNodeSet = 0; m_nCurItem = 0; return 0; } } bool CSpmXml::SetContent(const QString& strContent, xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return false; xmlNodeSetContent(pNode, BAD_CAST strContent.toUtf8().data()); return true; } QString CSpmXml::GetContent(xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return ""; return QString::fromUtf8((char *)xmlNodeGetContent(pNode)); } bool CSpmXml::Push(xmlNodePtr pNode) { pNode = GetNode(pNode); if (0 == pNode) return false; m_lstNodes.push_back(pNode); return true; } xmlNodePtr CSpmXml::Pop() { if (0 == m_lstNodes.size()) return 0; m_pCurNode = m_lstNodes.back(); m_lstNodes.pop_back(); return m_pCurNode; } bool CSpmXml::PushQuery() { if (0 == m_pCurNodeSet) return false; m_lstSets.push_back(CNodeSet(m_pCurNodeSet, m_nCurItem)); return true; } bool CSpmXml::PopQuery() { if (0 == m_lstSets.size()) return false; if (m_pCurNodeSet) xmlXPathFreeNodeSet(m_pCurNodeSet); CNodeSet& nodeset = m_lstSets.back(); m_pCurNodeSet = nodeset.set; m_nCurItem = nodeset.cur; m_lstSets.pop_back(); return true; } xmlNodePtr CSpmXml::GetNode(xmlNodePtr pNode) { if (0 == m_pXMLDoc) return 0; if (pNode) return pNode; if (m_pCurNode) return m_pCurNode; return xmlDocGetRootElement(m_pXMLDoc); }
[ "sergey.muraviov@ctc.local" ]
sergey.muraviov@ctc.local
221b6b3ae4c796530dbc38212bb3d4c5dcdfa1a0
6dcc36f15b3a8d0b020991cd8d9073e9c6874472
/Templates/ClassTemplate.cpp
8898c0d6266dd410aeb39de20c9adf7ec31fdc28
[]
no_license
ShabdKumar/CPlusPlus
dfd4204d8e90bd2b736f93b2bc0e8980c282248e
95bee9648643364f945ffa1bf21383fc93cbdfc8
refs/heads/master
2020-03-11T21:02:07.023434
2018-04-19T18:10:45
2018-04-19T18:10:45
130,253,748
0
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
#include<iostream> using namespace std; template<typename T> class Array { private : T *ptr; int length; public : void print(); Array(T arr[], int s); }; template<typename T> Array<T> :: Array(T arr[], int s) { ptr = new T[s]; length = s; for(int i=0; i<s; i++) ptr[i] = arr[i]; } template<typename T> void Array<T> :: print() { for(int i=0; i<length; i++) cout<<ptr[i]<<"\t"; } int main() { int arr[5] = {1,2,3,4,5}; Array<int> a(arr, 5); a.print(); return 0; }
[ "shabdkumarsahu@gmail.com" ]
shabdkumarsahu@gmail.com
faf21f683d23199062c81bcc67677ada41dbfc3d
aacfe8a25dc84ae5b783ea1d4f41a68d7e6cd28d
/src/SequenceData.h
765e083b182e86d3e49e215b472c5e46fdbdd324
[ "MIT" ]
permissive
sonir/slSequencer
37bcb20d1c3b8cb887059285cae6a81f3c9edac1
8454180c13c8343e459584ee3fe0998a11d5f393
refs/heads/master
2016-09-05T12:28:54.890057
2015-10-24T02:10:37
2015-10-24T02:10:37
38,199,748
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
h
// // SequenceData.h // yagiSys // // Created by sonir on 6/16/15. // // #ifndef __yagiSys__SequenceData__ #define __yagiSys__SequenceData__ #define QUANTUM_ELEMENTS_NUM 5 #define QUANTUMS_TOP_INDEX 2 #include <stdio.h> #include <iostream> #include <vector> #include "slChrono.h" //Function prototype // int64_t mergeInt32to64(unsigned int hi, unsigned int low); typedef enum {TEST} command; typedef struct quantum { bool done; int delta; command cmd; float param1; float param2; float param3; } quantum ; //C Func for merge ints // int64_t mergeInt32to64(unsigned int hi, unsigned int low){ // int64_t int64; // int64 = (int64_t)hi; // int64 = int64 << 32; //Bitshift to HiBit // int64 += (int64_t)low; //Write remainbit to // return int64; // } class SequenceData { public: SequenceData(){ }; void print(); bool finished = false; time_t st; chrono_t st_usec = -1; int qtm_count = 0; std::vector<quantum> quantums; }; #endif /* defined(__yagiSys__SequenceData__) */
[ "isana@sonir.jp" ]
isana@sonir.jp
9f2f3c0ad93cf04348f43bc04305d0de636ef6ed
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/content/public/common/resource_type.mojom-shared.h
50cc09d9df9745516de0a25347835483aa425f79
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
3,340
h
// content/public/common/resource_type.mojom-shared.h is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_COMMON_RESOURCE_TYPE_MOJOM_SHARED_H_ #define CONTENT_PUBLIC_COMMON_RESOURCE_TYPE_MOJOM_SHARED_H_ #include <stdint.h> #include <functional> #include <ostream> #include <type_traits> #include <utility> #include "base/compiler_specific.h" #include "base/containers/flat_map.h" #include "mojo/public/cpp/bindings/array_data_view.h" #include "mojo/public/cpp/bindings/enum_traits.h" #include "mojo/public/cpp/bindings/interface_data_view.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/map_data_view.h" #include "mojo/public/cpp/bindings/string_data_view.h" #include "content/public/common/resource_type.mojom-shared-internal.h" namespace content { namespace mojom { } // namespace mojom } // namespace content namespace mojo { namespace internal { } // namespace internal } // namespace mojo namespace content { namespace mojom { enum class ResourceType : int32_t { kMainFrame = 0, kSubFrame = 1, kStylesheet = 2, kScript = 3, kImage = 4, kFontResource = 5, kSubResource = 6, kObject = 7, kMedia = 8, kWorker = 9, kSharedWorker = 10, kPrefetch = 11, kFavicon = 12, kXhr = 13, kPing = 14, kServiceWorker = 15, kCspReport = 16, kPluginResource = 17, kNavigationPreloadMainFrame = 19, kNavigationPreloadSubFrame = 20, kMinValue = 0, kMaxValue = 20, }; std::ostream& operator<<(std::ostream& os, ResourceType value); inline bool IsKnownEnumValue(ResourceType value) { return internal::ResourceType_Data::IsKnownValue( static_cast<int32_t>(value)); } } // namespace mojom } // namespace content namespace std { template <> struct hash<::content::mojom::ResourceType> : public mojo::internal::EnumHashImpl<::content::mojom::ResourceType> {}; } // namespace std namespace mojo { template <> struct EnumTraits<::content::mojom::ResourceType, ::content::mojom::ResourceType> { static ::content::mojom::ResourceType ToMojom(::content::mojom::ResourceType input) { return input; } static bool FromMojom(::content::mojom::ResourceType input, ::content::mojom::ResourceType* output) { *output = input; return true; } }; namespace internal { template <typename MaybeConstUserType> struct Serializer<::content::mojom::ResourceType, MaybeConstUserType> { using UserType = typename std::remove_const<MaybeConstUserType>::type; using Traits = EnumTraits<::content::mojom::ResourceType, UserType>; static void Serialize(UserType input, int32_t* output) { *output = static_cast<int32_t>(Traits::ToMojom(input)); } static bool Deserialize(int32_t input, UserType* output) { return Traits::FromMojom(static_cast<::content::mojom::ResourceType>(input), output); } }; } // namespace internal } // namespace mojo namespace content { namespace mojom { } // namespace mojom } // namespace content #endif // CONTENT_PUBLIC_COMMON_RESOURCE_TYPE_MOJOM_SHARED_H_
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
dbfa90639b38fd9d383d2e6a2840b34bd870239f
f357526ecf311ac1e56e88219e97df293d7fad9c
/PedestrianDetection/DetectorCascade.h
f677ebc959f33a59e413de25daa72c1f66aa6506
[]
no_license
drake7707/pedestriandetection
f9a50b4b65cfa8310f23ec0f96db4f761ca8d6e3
1bca0f72c74ffbbe4ff62b1a4c28d6ad1267ee97
refs/heads/master
2022-12-15T18:36:16.913557
2017-02-21T12:01:10
2017-02-21T12:01:10
296,381,535
0
0
null
null
null
null
UTF-8
C++
false
false
2,932
h
#pragma once #include "opencv2\opencv.hpp" #include <functional> #include "FeatureVector.h" #include "KITTIDataSet.h" #include "Helper.h" #include "Detector.h" struct ClassifierEvaluation { int nrOfTruePositives = 0; int nrOfTrueNegatives = 0; int nrOfFalsePositives = 0; int nrOfFalseNegatives = 0; void print(std::ostream& out) { int totalNegatives = nrOfTrueNegatives + nrOfFalseNegatives; int totalPositives = nrOfTruePositives + nrOfFalsePositives; out << std::setprecision(2); out << "Evaluation result " << std::endl; out << "# True Positives " << nrOfTruePositives << " (" << floor(nrOfTruePositives * 1.0 / totalPositives * 100) << "%)" << std::endl; out << "# True Negatives " << nrOfTrueNegatives << " (" << floor(nrOfTrueNegatives * 1.0 / totalNegatives * 100) << "%)" << std::endl; out << "# False Positives " << nrOfFalsePositives << " (" << floor(nrOfFalsePositives * 1.0 / totalPositives * 100) << "%)" << std::endl; out << "# False Negatives " << nrOfFalseNegatives << " (" << floor(nrOfFalseNegatives * 1.0 / totalNegatives * 100) << "%)" << std::endl; } }; struct MatchRegion { cv::Rect2d region; float result; }; class DetectorCascade { private: int refWidth = 64; int refHeight = 128; int nrOfTN = 2; int testSampleEvery = 5; bool addS2 = true; int patchSize = 8; int binSize = 9; int sizeVariance = 4; int max_iterations = 5; DataSet* dataSet; std::vector<Detector> cascade; void getFeatureVectorsFromDataSet(std::vector<FeatureVector>& truePositiveFeatures, std::vector<FeatureVector>& trueNegativeFeatures); FeatureVector getFeatures(cv::Mat& mat); ClassifierEvaluation evaluateDetector(Detector& d, std::vector<FeatureVector>& truePositives, std::vector<FeatureVector>& trueNegatives); void slideWindow(cv::Mat& img, std::function<void(cv::Rect2d rect, cv::Mat& region)> func); void iterateDataset(std::function<void(cv::Mat&)> tpFunc, std::function<void(cv::Mat&)> tnFunc, std::function<bool(int)> includeSample); public: DetectorCascade(DataSet* dataSet) : dataSet(dataSet) { } ~DetectorCascade(); void saveSVMLightFiles(); void buildCascade(); double evaluateRegion(cv::Mat& region); std::vector<MatchRegion> evaluateImage(cv::Mat& img); void saveCascade(std::string& path); void loadCascade(std::string& path); void toString(std::ostream& o) { std::string str = ""; o << "Reference size: " << refWidth << "x" << refHeight << std::endl; o << "Patch size: " << patchSize << std::endl; o << "Bin size: " << binSize << std::endl; o << "Number of TN per TP/TPFlipped : " << nrOfTN << std::endl; o << "Training/test set split : " << (100 - (100 / testSampleEvery)) << "/" << (100 / testSampleEvery) << std::endl; o << "Add S^2 of histograms to features: " << (addS2 ? "yes" : "no") << std::endl; } };
[ "DwightKerkhove@behindthebuttons.com" ]
DwightKerkhove@behindthebuttons.com
67c0bdc98423d21caa61ae3da9d476e1ad7eedae
2e68b0ed8651350eeebd2fecc69129e445446f41
/蓝桥杯/官网/历届试题/蚂蚁感冒.cpp
ae42fcb61b4200afc433e1092e2b3c5fe008aed8
[]
no_license
Violet-Guo/ACM
1dd7104172834ad75515d4b0ecba39ec2f90c201
7b5781349dc77cb904f522135cb06ad6872f7646
refs/heads/master
2021-01-21T04:40:27.151145
2016-06-23T01:39:17
2016-06-23T01:39:17
50,434,940
2
0
null
null
null
null
GB18030
C++
false
false
1,040
cpp
#include<cstdio> #include<cmath> #include<cstring> #include<algorithm> using namespace std; int num[55], f[55], b[55]; int main() { int n, a; while(scanf("%d", &n)!=EOF){ int cnt = 1; for(int i = 0; i < n; i++){ scanf("%d", &a); num[i] = abs(a); if(a > 0) f[i] = 1; else f[i] = -1; } int flag = f[0]; if(flag==1){ //感冒的蚂蚁往右走 for(int i = 1; i < n; i++){ //把向左走的蚂蚁都感染了 if(num[i] > num[0] && f[i]==-1){ cnt++; } } if(cnt > 1){ for(int i = 1; i < n; i++){ //把向右走的蚂蚁都感染了 if(num[i] < num[0] && f[i]==1) cnt++; } } } else{ //感冒的蚂蚁往左走 for(int i = 1; i < n; i++){ //把向右走的蚂蚁都感染了 if(num[i] < num[0] && f[i]==1){ cnt++; } } if(cnt > 1){ for(int i = 1; i < n; i++){ // 把向左走的蚂蚁都感染了 if(num[i] > num[0] && f[i]==-1) cnt++; } } } printf("%d\n", cnt); } return 0; }
[ "iamguojing@qq.com" ]
iamguojing@qq.com
e92db02263ea3991c004f721b606eac88bf10f0f
c0fcbf4f99099d336c2f9a1cf5b10d08be9f59d3
/bvm/Shaders/liquity/contract.cpp
47bbff0c20cb1d6ba68192248174075e6dc172c5
[ "Apache-2.0" ]
permissive
unwaz/beam
00bf13b50ffff2e2a4007b033f5696d05a8cc775
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
refs/heads/master
2022-04-28T16:37:11.030079
2022-04-25T11:51:33
2022-04-25T11:51:33
204,409,378
0
0
Apache-2.0
2019-08-26T06:22:27
2019-08-26T06:22:27
null
UTF-8
C++
false
false
12,966
cpp
//////////////////////// #include "../common.h" #include "../Math.h" #include "contract.h" namespace Liquity { struct EpochStorage { static EpochKey get_Key(uint32_t iEpoch) { EpochKey k; k.m_Tag = Tags::s_Epoch_Stable; k.m_iEpoch = iEpoch; return k; } static void Load(uint32_t iEpoch, HomogenousPool::Epoch& e) { Env::LoadVar_T(get_Key(iEpoch), e); } static void Save(uint32_t iEpoch, const HomogenousPool::Epoch& e) { Env::SaveVar_T(get_Key(iEpoch), e); } static void Del(uint32_t iEpoch) { Env::DelVar_T(get_Key(iEpoch)); } }; struct MyGlobal :public Global { void Load() { auto key = Tags::s_State; Env::LoadVar_T(key, *this); } void Save() { auto key = Tags::s_State; Env::SaveVar_T(key, *this); } static void AdjustStrict(Amount& x, Amount val, uint8_t bAdd) { if (bAdd) Strict::Add(x, val); else Strict::Sub(x, val); } static void AdjustBank(const FlowPair& fp, const PubKey& pk) { Env::AddSig(pk); AdjustBankNoSig(fp, pk); } static void AdjustBankNoSig(const FlowPair& fp, const PubKey& pk) { if (fp.Tok.m_Val || fp.Col.m_Val) { Balance::Key kub; _POD_(kub.m_Pk) = pk; Balance ub; if (!Env::LoadVar_T(kub, ub)) _POD_(ub).SetZero(); AdjustStrict(ub.m_Amounts.Tok, fp.Tok.m_Val, fp.Tok.m_Spend); AdjustStrict(ub.m_Amounts.Col, fp.Col.m_Val, fp.Col.m_Spend); if (ub.m_Amounts.Tok || ub.m_Amounts.Col) Env::SaveVar_T(kub, ub); else Env::DelVar_T(kub); } } static void ExtractSurplusCol(Amount val, const Trove& t) { FlowPair fp; _POD_(fp.Tok).SetZero(); fp.Col.m_Spend = 1; fp.Col.m_Val = val; AdjustBankNoSig(fp, t.m_pkOwner); } static void AdjustTxFunds(const Flow& f, AssetID aid) { if (f.m_Val) { if (f.m_Spend) Env::FundsLock(aid, f.m_Val); else Env::FundsUnlock(aid, f.m_Val); } } void AdjustTxFunds(const Method::BaseTx& r) const { AdjustTxFunds(r.m_Flow.Tok, m_Aid); AdjustTxFunds(r.m_Flow.Col, 0); } void AdjustTxBank(const FlowPair& fpLogic, const Method::BaseTx& r, const PubKey& pk) { FlowPair fpDelta = r.m_Flow; fpDelta.Tok -= fpLogic.Tok; fpDelta.Col -= fpLogic.Col; AdjustBank(fpDelta, pk); } void AdjustAll(const Method::BaseTx& r, const Pair& totals0, const FlowPair& fpLogic, const PubKey& pk) { if (m_Troves.m_Totals.Tok > totals0.Tok) Env::Halt_if(!Env::AssetEmit(m_Aid, m_Troves.m_Totals.Tok - totals0.Tok, 1)); AdjustTxFunds(r); if (totals0.Tok > m_Troves.m_Totals.Tok) Env::Halt_if(!Env::AssetEmit(m_Aid, totals0.Tok - m_Troves.m_Totals.Tok, 0)); AdjustTxBank(fpLogic, r, pk); } Trove::ID TrovePop(Trove::ID iPrev, Trove& t) { Trove tPrev; Trove::Key tk; Trove::ID iTrove; if (iPrev) { tk.m_iTrove = iPrev; Env::Halt_if(!Env::LoadVar_T(tk, tPrev)); iTrove = tPrev.m_iNext; } else iTrove = m_Troves.m_iHead; tk.m_iTrove = iTrove; Env::Halt_if(!Env::LoadVar_T(tk, t)); m_RedistPool.Remove(t); // just for more safety. Theoretically strict isn't necessary Strict::Sub(m_Troves.m_Totals.Tok, t.m_Amounts.Tok); Strict::Sub(m_Troves.m_Totals.Col, t.m_Amounts.Col); if (iPrev) { tPrev.m_iNext = t.m_iNext; tk.m_iTrove = iPrev; Env::SaveVar_T(tk, tPrev); } else m_Troves.m_iHead = t.m_iNext; return iTrove; } int TroveLoadCmp(const Trove::Key& tk, Trove& t, const Trove& tRef) { Env::Halt_if(!Env::LoadVar_T(tk, t)); auto vals = m_RedistPool.get_UpdatedAmounts(t); return vals.CmpRcr(tRef.m_Amounts); } void TrovePush(Trove::ID iTrove, Trove& t, Trove::ID iPrev) { Strict::Add(m_Troves.m_Totals.Tok, t.m_Amounts.Tok); Strict::Add(m_Troves.m_Totals.Col, t.m_Amounts.Col); m_RedistPool.Add(t); Trove::Key tk; if (iPrev) { Trove tPrev; tk.m_iTrove = iPrev; int iCmp = TroveLoadCmp(tk, tPrev, t); Env::Halt_if(iCmp > 0); t.m_iNext = tPrev.m_iNext; tPrev.m_iNext = iTrove; Env::SaveVar_T(tk, tPrev); } else { t.m_iNext = m_Troves.m_iHead; m_Troves.m_iHead = iTrove; } if (t.m_iNext) { Trove tNext; tk.m_iTrove = t.m_iNext; int iCmp = TroveLoadCmp(tk, tNext, t); Env::Halt_if(iCmp < 0); } tk.m_iTrove = iTrove; Env::SaveVar_T(tk, t); } void TroveModify(Trove::ID iPrev0, Trove::ID iPrev1, const Pair* pNewVals, const PubKey* pPk, const Method::BaseTx& r) { bool bOpen = !!pPk; bool bClose = !pNewVals; Pair totals0 = m_Troves.m_Totals; FlowPair fpLogic; _POD_(fpLogic).SetZero(); Trove t; Trove::ID iTrove; if (bOpen) { _POD_(t).SetZero(); _POD_(t.m_pkOwner) = *pPk; iTrove = ++m_Troves.m_iLastCreated; fpLogic.Tok.Add(m_Settings.m_TroveLiquidationReserve, 1); } else { iTrove = TrovePop(iPrev0, t); fpLogic.Tok.Add(t.m_Amounts.Tok, 1); fpLogic.Col.Add(t.m_Amounts.Col, 0); } if (bClose) { fpLogic.Tok.Add(m_Settings.m_TroveLiquidationReserve, 0); Trove::Key tk; tk.m_iTrove = iTrove; Env::DelVar_T(tk); } else { fpLogic.Tok.Add(pNewVals->Tok, 0); fpLogic.Col.Add(pNewVals->Col, 1); t.m_Amounts = *pNewVals; Env::Halt_if(t.m_Amounts.Tok <= m_Settings.m_TroveLiquidationReserve); TrovePush(iTrove, t, iPrev1); // check cr Price price = get_Price(); bool bRecovery = IsRecovery(price); Env::Halt_if(IsTroveUpdInvalid(t, totals0, price, bRecovery)); Amount feeCol = get_BorrowFee(m_Troves.m_Totals.Tok, totals0.Tok, bRecovery, price); if (feeCol) { m_ProfitPool.AddValue(feeCol, 0); fpLogic.Col.Add(feeCol, 1); } } AdjustAll(r, totals0, fpLogic, t.m_pkOwner); // will invoke AddSig } Global::Price get_Price() { Method::OracleGet args; Env::CallFar_T(m_Settings.m_cidOracle, args, 0); Global::Price ret; ret.m_Value = args.m_Value; return ret; } }; struct MyGlobal_Load :public MyGlobal { MyGlobal_Load() { Load(); } }; struct MyGlobal_LoadSave :public MyGlobal_Load { ~MyGlobal_LoadSave() { #ifdef HOST_BUILD if (std::uncaught_exceptions()) return; #endif // HOST_BUILD Save(); } }; BEAM_EXPORT void Ctor(const Method::Create& r) { if (Env::get_CallDepth() == 1) return; MyGlobal g; _POD_(g).SetZero(); _POD_(g.m_Settings) = r.m_Settings; g.m_StabPool.Init(); g.m_RedistPool.Reset(); static const char szMeta[] = "STD:SCH_VER=1;N=Liquity Token;SN=Liqt;UN=LIQT;NTHUN=GROTHL"; g.m_Aid = Env::AssetCreate(szMeta, sizeof(szMeta) - 1); Env::Halt_if(!g.m_Aid); Env::Halt_if(!Env::RefAdd(g.m_Settings.m_cidOracle)); g.Save(); } BEAM_EXPORT void Dtor(void*) { } BEAM_EXPORT void Method_2(void*) { // called on upgrade // // Make sure it's invoked appropriately //ContractID cid0, cid1; //Env::get_CallerCid(0, cid0); //Env::get_CallerCid(1, cid1); //Env::Halt_if(_POD_(cid0) != cid1); } BEAM_EXPORT void Method_3(const Method::TroveOpen& r) { MyGlobal_LoadSave g; g.TroveModify(0, r.m_iPrev1, &r.m_Amounts, &r.m_pkUser, r); } BEAM_EXPORT void Method_4(const Method::TroveClose& r) { MyGlobal_LoadSave g; g.TroveModify(r.m_iPrev0, 0, nullptr, nullptr, r); } BEAM_EXPORT void Method_5(Method::TroveModify& r) { MyGlobal_LoadSave g; g.TroveModify(r.m_iPrev0, r.m_iPrev1, &r.m_Amounts, nullptr, r); } BEAM_EXPORT void Method_6(const Method::FundsAccess& r) { MyGlobal_Load g; g.AdjustTxFunds(r); g.AdjustBank(r.m_Flow, r.m_pkUser); // will invoke AddSig } BEAM_EXPORT void Method_7(Method::UpdStabPool& r) { MyGlobal_LoadSave g; StabPoolEntry::Key spk; _POD_(spk.m_pkUser) = r.m_pkUser; FlowPair fpLogic; _POD_(fpLogic).SetZero(); Height h = Env::get_Height(); StabPoolEntry spe; if (!Env::LoadVar_T(spk, spe)) _POD_(spe).SetZero(); else { Env::Halt_if(spe.m_hLastModify == h); EpochStorage stor; HomogenousPool::Pair out; g.m_StabPool.UserDel(spe.m_User, out, stor); fpLogic.Tok.m_Val = out.s; fpLogic.Col.m_Val = out.b; if ((r.m_NewAmount < out.s) && g.m_Troves.m_iHead) { // ensure no pending liquidations Global::Price price = g.get_Price(); Env::Halt_if(price.IsRecovery(g.m_Troves.m_Totals)); Trove::Key tk; tk.m_iTrove = g.m_Troves.m_iHead; Trove t; Env::Halt_if(!Env::LoadVar_T(tk, t)); auto vals = g.m_RedistPool.get_UpdatedAmounts(t); auto cr = price.ToCR(vals.get_Rcr()); Env::Halt_if((cr < Global::Price::get_k110())); } } if (r.m_NewAmount) { spe.m_hLastModify = h; g.m_StabPool.UserAdd(spe.m_User, r.m_NewAmount); Env::SaveVar_T(spk, spe); fpLogic.Tok.Add(r.m_NewAmount, 1); } else Env::DelVar_T(spk); g.AdjustTxFunds(r); g.AdjustTxBank(fpLogic, r, r.m_pkUser); } BEAM_EXPORT void Method_8(Method::Liquidate& r) { MyGlobal_LoadSave g; Global::Liquidator ctx; ctx.m_Price = g.get_Price(); _POD_(ctx.m_fpLogic).SetZero(); Pair totals0 = g.m_Troves.m_Totals; Trove::Key tk; for (uint32_t i = 0; i < r.m_Count; i++) { Pair totals1 = g.m_Troves.m_Totals; Trove t; tk.m_iTrove = g.TrovePop(0, t); Env::DelVar_T(tk); Amount valSurplus = 0; Env::Halt_if(!g.LiquidateTrove(t, totals1, ctx, valSurplus)); if (valSurplus) g.ExtractSurplusCol(valSurplus, t); } if (ctx.m_Stab) { EpochStorage stor; g.m_StabPool.OnPostTrade(stor); } g.AdjustAll(r, totals0, ctx.m_fpLogic, r.m_pkUser); } BEAM_EXPORT void Method_9(Method::UpdProfitPool& r) { MyGlobal_LoadSave g; ProfitPoolEntry::Key pk; _POD_(pk.m_pkUser) = r.m_pkUser; FlowPair fpLogic; _POD_(fpLogic).SetZero(); Height h = Env::get_Height(); ProfitPoolEntry pe; if (!Env::LoadVar_T(pk, pe)) _POD_(pe).SetZero(); else { Env::Halt_if(pe.m_hLastModify == h); Amount valOut; g.m_ProfitPool.Remove(&valOut, pe.m_User); fpLogic.Col.m_Val = valOut; } if (r.m_NewAmount > pe.m_User.m_Weight) Env::FundsLock(g.m_Settings.m_AidProfit, r.m_NewAmount - pe.m_User.m_Weight); if (pe.m_User.m_Weight > r.m_NewAmount) Env::FundsUnlock(g.m_Settings.m_AidProfit, pe.m_User.m_Weight - r.m_NewAmount); if (r.m_NewAmount) { pe.m_User.m_Weight = r.m_NewAmount; g.m_ProfitPool.Add(pe.m_User); pe.m_hLastModify = h; Env::SaveVar_T(pk, pe); } else Env::DelVar_T(pk); g.AdjustTxFunds(r); g.AdjustTxBank(fpLogic, r, r.m_pkUser); } BEAM_EXPORT void Method_10(Method::Redeem& r) { MyGlobal_LoadSave g; Env::Halt_if(Env::get_Height() < g.m_Settings.m_hMinRedemptionHeight); Pair totals0 = g.m_Troves.m_Totals; Global::Redeemer ctx; ctx.m_Price = g.get_Price(); _POD_(ctx.m_fpLogic).SetZero(); Trove::Key tk; for (ctx.m_TokRemaining = r.m_Amount; ctx.m_TokRemaining; ) { Trove t; tk.m_iTrove = g.TrovePop(0, t); Env::Halt_if(!g.RedeemTrove(t, ctx)); if (t.m_Amounts.Tok) g.TrovePush(tk.m_iTrove, t, r.m_iPrev1); else { // close trove Env::DelVar_T(tk); g.ExtractSurplusCol(t.m_Amounts.Col, t); } } Amount fee = g.AddRedeemFee(ctx); if (fee) g.m_ProfitPool.AddValue(fee, 0); g.AdjustAll(r, totals0, ctx.m_fpLogic, r.m_pkUser); } } // namespace Liquity
[ "valdo@beam-mw.com" ]
valdo@beam-mw.com
1166f26dc61061a440cdd7f93fe8f0cc3cf0616d
91e204031477be6c110699ea55c03657129ef508
/Arduino.ino
551de7e105b72d6f0b2aef85a41f2d6dd1000a02
[]
no_license
bziarkowski/Arduino-Pit-Stop-Mechanic
914de38d090c0e8ef2731c69dca92c0fe59a3949
8ffc16ad432ba55a1d9951fb72b38d5dbab13473
refs/heads/master
2022-04-14T08:19:18.411671
2020-04-15T15:32:01
2020-04-15T15:32:01
255,918,423
0
0
null
null
null
null
UTF-8
C++
false
false
677
ino
const int potentiometer1Pin = A0; const int potentiometer2Pin = A1; const int potentiometer3Pin = A2; const int potentiometer4Pin = A3; #define SERIAL_USB void setup() { #ifdef SERIAL_USB Serial.begin(9600); // You can choose any baudrate, just need to also change it in Unity. while (!Serial); #endif } // Run forever void loop() { String valuesToSend = String(analogRead(potentiometer1Pin)) + " " + String(analogRead(potentiometer2Pin)) + " " + String(analogRead(potentiometer3Pin)) + " " + String(analogRead(potentiometer4Pin)); sendData(valuesToSend); delay(50); } void sendData(String data){ #ifdef SERIAL_USB Serial.println(data); #endif }
[ "bart@empyrean.games" ]
bart@empyrean.games
9ac3a5f9bd8633dfb49caa0972cb42eadad29691
a241fc77ccf11164a4090eb2e1d9e7801a0d5f32
/server/XML/test.cpp
9b9173cb1c9834c32660419fdf0f7c50e00e910a
[]
no_license
sj-team/ShootPlane
a1f0c8c5d774bc9463606515c6bfee29e1e61962
cd644630d7bfd7be4f2f212ba5d5e5470448308d
refs/heads/master
2020-05-18T23:48:36.947217
2019-05-09T14:16:36
2019-05-09T14:16:36
184,721,112
3
1
null
null
null
null
UTF-8
C++
false
false
799
cpp
#include "XmlLog.h" using namespace std; int main() { XmlLog log; Packet packet; packet.header.subType = sbt::request; ClientInfo c1("jiahaolin"), c2("menglingchen"); c1.sockaddr.sin_addr.s_addr = inet_addr("192.168.80.230"); c2.sockaddr.sin_addr.s_addr = inet_addr("192.168.80.111"); log.writeNorm(&c1, NULL, &packet); sleep(1); c1.name = "wanghan"; log.writeNorm(&c1, NULL, &packet); c1.sockaddr.sin_addr.s_addr = inet_addr("10.60.17.56"); packet.header.subType = sbt::idNotExit; sleep(1); log.writeNorm(&c1, &c2, &packet); c2.name = "xiaowei"; sleep(1); log.writeNorm(&c1, NULL, &packet); log.writeNorm(&c1, &c2, &packet); packet.header.subType = sbt::tellOffline; sleep(1); log.saveLog(); return 0; }
[ "920105279@qq.com" ]
920105279@qq.com
d4a07a4f6778ad51dd6e2cf982560eac9460e67d
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/log/utility/manipulators/add_value.hpp
51a38e58cb7b5210f8c1a3875c31e77a853a0916
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
80
hpp
#include "thirdparty/boost_1_55_0/boost/log/utility/manipulators/add_value.hpp"
[ "liuhuahang@xiaomi.com" ]
liuhuahang@xiaomi.com
2ecfada33db54f3288149637f5c1ea066eada4e1
ecd252c3ca60df77e58b84870c403b2f5e4aec59
/src/windows/kernel/nt/types/registry/KEY_VALUE_STRING_IMPL.cc
60c97d0be52fb817429895ee43195996289411ad
[ "Apache-2.0" ]
permissive
srpape/IntroVirt
ffe81b7ed24029ee54acdd7702a7a20921ec8f3f
fe553221c40b8ef71f06e79c9d54d9e123a06c89
refs/heads/main
2022-07-29T02:34:20.216930
2021-03-19T23:10:38
2021-03-19T23:14:41
344,861,919
0
0
Apache-2.0
2021-03-05T16:02:50
2021-03-05T16:02:50
null
UTF-8
C++
false
false
2,396
cc
/* * Copyright 2021 Assured Information Security, 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 "KEY_VALUE_STRING_IMPL.hh" #include <boost/io/ios_state.hpp> #include <introvirt/windows/kernel/nt/types/registry/KEY_VALUE_EXPAND_STRING.hh> namespace introvirt { namespace windows { namespace nt { template <typename _BaseClass> std::string KEY_VALUE_STRING_IMPL<_BaseClass>::StringValue() const { if (unlikely(!Value_)) return std::string(); return Value_->utf8(); } template <typename _BaseClass> void KEY_VALUE_STRING_IMPL<_BaseClass>::write(std::ostream& os, const std::string& linePrefix) const { KEY_VALUE_IMPL<_BaseClass>::write(os, linePrefix); boost::io::ios_flags_saver ifs(os); os << linePrefix << "Value: " << StringValue() << '\n'; } template <typename _BaseClass> Json::Value KEY_VALUE_STRING_IMPL<_BaseClass>::json() const { Json::Value result = KEY_VALUE_IMPL<_BaseClass>::json(); result["StringValue"] = StringValue(); return result; } template <typename _BaseClass> KEY_VALUE_STRING_IMPL<_BaseClass>::KEY_VALUE_STRING_IMPL(const GuestVirtualAddress& gva, uint32_t size) : KEY_VALUE_STRING_IMPL(REG_TYPE::REG_SZ, gva, size) {} template <typename _BaseClass> KEY_VALUE_STRING_IMPL<_BaseClass>::KEY_VALUE_STRING_IMPL(REG_TYPE type, const GuestVirtualAddress& gva, uint32_t size) : KEY_VALUE_IMPL<_BaseClass>(type, gva, size) { Value_.emplace(this->address(), this->DataSize()); } template class KEY_VALUE_STRING_IMPL<KEY_VALUE_STRING>; template class KEY_VALUE_STRING_IMPL<KEY_VALUE_EXPAND_STRING>; } // namespace nt } // namespace windows } /* namespace introvirt */
[ "srpape@gmail.com" ]
srpape@gmail.com
0090215edd7ad891bb3c3450f164f09e07ef7818
1ddbf0686fcd8f10a66ce35897b432e161edae94
/Exercises/exercise5/sol-exercise5/sortwords.cc
03c8818e7bf5963ed55c3da4a7b3f22ba9f920aa
[]
no_license
NilsKarlbrinkMalmquist/EDAF50
b37e7cf0717cbfda5c329052c3ff458eb115d200
d65d16737b0930590123633e614742a94232b0ad
refs/heads/master
2023-04-04T01:15:12.893371
2021-03-26T08:49:18
2021-03-26T08:49:18
332,183,483
1
0
null
null
null
null
UTF-8
C++
false
false
1,738
cc
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <iterator> using namespace std; ostream& operator<<(ostream& os, const vector<string>& v) { for (const string& s : v) { os << s << " "; } return os; } int main() { vector<string> v = {"Mary", "had", "a", "little", "lamb", "and", "some", "olives", "on", "the", "side"}; // print the words: Mary had a little lamb and some olives on the side cout << v << endl; // sort in alphabetical order: Mary a and had lamb little olives on side some the sort(v.begin(), v.end()); cout << v << endl; // in reverse order:the some side on olives little lamb had and a Mary sort(v.begin(), v.end(), [](const string& s1, const string& s2) { return s1 > s2; }); cout << v << endl; // by ascending length: a on the and had Mary lamb side some olives little sort(v.begin(), v.end(), [](const string& s1, const string& s2) { return s1.length() < s2.length(); }); cout << v << endl; // sort in alphabetical order again, print three-letter words: and had the sort(v.begin(), v.end()); for_each(v.begin(), v.end(), [](const string& s) { if (s.length() == 3) { cout << s << " "; }}); cout << endl; // For the output, an alternative to for_each, an if-statement and cout << s is: // use copy_if and an ostream_iterator: same output as above std::copy_if(v.begin(), v.end(), std::ostream_iterator<string>(cout, " "), [](const string& s) {return s.length() == 3;}) ; cout << endl; // remove words with <= three letters: Mary lamb little olives side some auto it = remove_if(v.begin(), v.end(), [](const string& s) { return s.length() <= 3; }); v.erase(it, v.end()); cout << v << endl; }
[ "71669738+NilsKarlbrinkMalmquist@users.noreply.github.com" ]
71669738+NilsKarlbrinkMalmquist@users.noreply.github.com
d44ed1bbbc9abe757efffebdad7b245fedf9114d
f72f3d3f1b8c75f7d8ef9ca5000e6e7cb2079ff4
/core_base/psx_base_buffer.cpp
9b0ca21996f366dad8982b4812b40357278b9832
[]
no_license
elPoublo256/hell_and_heaven
5f82769e15011c418ace38fb2df556a29c00e793
33bae154a4d6ea336d7a6e0845354bacbd61d716
refs/heads/master
2021-06-02T07:34:07.187488
2020-10-28T21:42:33
2020-10-28T21:42:33
150,132,053
1
0
null
null
null
null
UTF-8
C++
false
false
1,958
cpp
#include "psx_base_buffer.h" #include <malloc.h> #include <memory.h> hh::PSX_Base_Bufer::PSX_Base_Bufer(const std::size_t &size) : __len(size) { __ptr = alloc_mem_ptr(size); } hh::PSX_Base_Bufer::PSX_Base_Bufer(const hh::PSX_Base_Bufer &copy) { __ptr = this->alloc_mem_ptr(copy.size_in_bytes()); this->copy_mem(copy.get(),copy.size_in_bytes()); } hh::PSX_Base_Bufer::PSX_Base_Bufer(PSX_Base_Bufer &&rv_copy) : __len(rv_copy.__len), __ptr(rv_copy.__ptr) { rv_copy.__ptr = NULL; } hh::PSX_Base_Bufer::PSX_Base_Bufer(const std::size_t &size, void *ptr) : __ptr(ptr), __len(size) { } hh::PSX_Base_Bufer::PSX_Base_Bufer(const char *str) { auto len = strlen(str); __len = len; __ptr = malloc(len); memcpy(__ptr,(void*)str,len); } hh::PSX_Base_Bufer &hh::PSX_Base_Bufer::operator =(const hh::PSX_Base_Bufer& copy) { if(this->is_valid()) { this->delete_mem(); } this->alloc_mem_ptr(copy.size_in_bytes()); this->copy_mem(copy.get(),copy.size_in_bytes()); return (*this); } void hh::PSX_Base_Bufer::resize(const std::size_t &len) { if(len > __len) { throw std::out_of_range("error resize buser"); } else { free(__ptr + len); __len = len; } } hh::PSX_Base_Bufer &hh::PSX_Base_Bufer::operator =(hh::PSX_Base_Bufer&& rv_copy) { if(this->is_valid()) { this->delete_mem(); } __ptr = std::move(rv_copy.__ptr); __len = std::move(rv_copy.__len); return (*this); } void* hh::PSX_Base_Bufer::alloc_mem_ptr(const std::size_t &l) { return malloc(l); } hh::PSX_Base_Bufer::~PSX_Base_Bufer() { if(this->is_valid()) { this->delete_mem(); } } bool hh::PSX_Base_Bufer::is_valid(){return __ptr!=NULL;} void hh::PSX_Base_Bufer::copy_mem(const void *src, const std::size_t &len) { memcpy(__ptr,src,len); } void hh::PSX_Base_Bufer::delete_mem() { free(__ptr); __ptr=NULL; }
[ "elpoublo@gmail.com" ]
elpoublo@gmail.com
9ea56a5eb5a6d31a79e7cb5bc9b2b478eeb9401a
c4e43c8200265db38355a027de7f27b6f9508015
/addons/main/script_mod.hpp
defa534ab73d9791bbffee4ab2032dc586b9d8f0
[]
no_license
22ndODST/22ndODST_Modpack
283db70176719310da55cf557cbcc7d6271521ed
b674775f9fd64fdf0bad5c02ee1d7812ee3898dd
refs/heads/master
2016-09-01T16:29:35.833244
2015-12-09T02:02:48
2015-12-09T02:02:48
46,303,509
0
1
null
2015-12-04T22:30:26
2015-11-16T21:21:48
null
UTF-8
C++
false
false
392
hpp
// COMPONENT should be defined in the script_component.hpp and included BEFORE this hpp #define MAINPREFIX z #define PREFIX 22nd #define MAJOR 1 #define MINOR 0 #define PATCHLVL 0 #define BUILD 0 #define VERSION MAJOR.MINOR.PATCHLVL.BUILD #define VERSION_AR MAJOR,MINOR,PATCHLVL,BUILD // MINIMAL required version for the Mod. Components can specify others.. #define REQUIRED_VERSION 1.54
[ "white.nathan14@gmail.com" ]
white.nathan14@gmail.com
d270b033b011e570c26be6d504e68cfd4d84486c
adf798ea50604e5655b54f3a85d849b93f39f1ca
/AR_Detector_SO/app/src/main/jni/GeometryTypes.cpp
f91ed326d1bf540521d653cddac5cab8c50dcb30
[]
no_license
yunjies/AR_Project
3f760c31d23e84689dd69e7cc1be1a3ba92ff57d
0d61fc8853ceb97fe5fb49f99f7a2f007f12bd52
refs/heads/master
2020-09-04T10:26:44.299312
2017-07-27T09:17:54
2017-07-27T09:17:54
94,409,212
0
0
null
null
null
null
UTF-8
C++
false
false
3,042
cpp
#include "GeometryTypes.hpp" Matrix44 Matrix44::getTransposed() const { Matrix44 t; for (int i=0;i<4; i++) for (int j=0;j<4;j++) t.mat[i][j] = mat[j][i]; return t; } Matrix44 Matrix44::identity() { Matrix44 eye; for (int i=0;i<4; i++) for (int j=0;j<4;j++) eye.mat[i][j] = i == j ? 1 : 0; return eye; } Matrix44 Matrix44::getInvertedRT() const { Matrix44 t = identity(); for (int col=0;col<3; col++) { for (int row=0;row<3;row++) { // Transpose rotation component (inversion) t.mat[row][col] = mat[col][row]; } // Inverse translation component t.mat[3][col] = - mat[3][col]; } return t; } Matrix33 Matrix33::identity() { Matrix33 eye; for (int i=0;i<3; i++) for (int j=0;j<3;j++) eye.mat[i][j] = i == j ? 1 : 0; return eye; } Matrix33 Matrix33::getTransposed() const { Matrix33 t; for (int i=0;i<3; i++) for (int j=0;j<3;j++) t.mat[i][j] = mat[j][i]; return t; } Vector3 Vector3::zero() { Vector3 v = { 0,0,0 }; return v; } Vector3 Vector3::operator-() const { Vector3 v = { -data[0],-data[1],-data[2] }; return v; } Transformation::Transformation(): m_rotation(Matrix33::identity()), m_translation(Vector3::zero()) { } Transformation::Transformation(const Matrix33& r, const Vector3& t): m_rotation(r), m_translation(t) { } Matrix33& Transformation::r() { return m_rotation; } Vector3& Transformation::t() { return m_translation; } const Matrix33& Transformation::r() const { return m_rotation; } const Vector3& Transformation::t() const { return m_translation; } Matrix44 Transformation::getMat44() const { //Matrix44 res = Matrix44::identity(); // //for (int row = 0; row<3; row++) //{ // for (int col = 0; col<3; col++) // { // // Copy rotation component // res.mat[row][col] = m_rotation.mat[row][col]; // // } // // // Copy translation component // res.mat[row][3] = m_translation.data[row]; //} // //return res; Matrix44 res = Matrix44::identity(); for (int col = 0; col<3; col++) { for (int row = 0; row<3; row++) { // Copy rotation component res.mat[row][col] = m_rotation.mat[row][col]; } ////Copy translation component res.mat[3][col] = m_translation.data[col]; } return res; } Transformation Transformation::getInverted() const { return Transformation(m_rotation.getTransposed(), -m_translation); } std::string Transformation::getMat44string() const { Matrix44 res = Transformation::getMat44(); std::stringstream ss; for (int col = 0; col<4; col++) { for (int row = 0; row<4; row++) { ss << res.mat[row][col] << "\t"; } } return ss.str(); } std::vector<float> Transformation::getMat44vector() const { Matrix44 res = Transformation::getMat44(); std::vector<float> matrix; for (int col = 0; col<4; col++) { for (int row = 0; row<4; row++) { matrix.push_back(res.mat[row][col]); } } return matrix; }
[ "379739073@qq.com" ]
379739073@qq.com
3a5b2daf4f97e03226f1c97a2f0a53ec87b0358c
ced460e7fc7dab688b8b2c8096c7a51dad708c43
/FlightGo/Listen.h
bba5c214f77ad17d155c32b1cad576b32215e175
[]
no_license
JayceSYH/FlightGo
71c5bd953ab782deb9bac108f29dd95cbd46c348
d5cb68c55ce419d80d7e9ffe953719f99733c6d7
refs/heads/master
2021-01-11T03:58:03.900932
2017-02-22T11:20:07
2017-02-22T11:20:07
71,245,992
1
1
null
null
null
null
UTF-8
C++
false
false
4,711
h
#pragma once #include<list> #include<map> #include<string> #include<functional> #include<algorithm> #include "TemplateTools.h" using namespace std; enum ListenerState { INVALID, VALID }; template <class... Params> class Listener { protected: typedef void(*F)(string event, Params...); typedef std::function<void(string, Params...)> FLambda; FLambda lambda; int generateId() { static int idGenerator = 0; return idGenerator++; } int id; ListenerState state; public: Listener(FLambda lambda) { this->id = generateId(); this->lambda = lambda; this->state = ListenerState::VALID; } Listener() { this->id = generateId(); this->state = ListenerState::VALID; } Listener& operator=(const FLambda& lambda) { this->lambda = lambda; return *this; } operator FLambda() { return this->lambda;; } FLambda& operator *() { return this->lambda; } void operator()() { this->lambda(); } bool operator==(const Listener<Params...>& listener) { return listener.id == this->id; } bool operator!=(Listener<Params...>& listener) { return listener.id != this->id; } void notify(string event,Params... params) { this->lambda(event, unpack(params)...); } int getListenerId() { return this->id; }; void setValid() { this->state = ListenerState::VALID; } void setInvalid() { this->state = ListenerState::INVALID; } bool isValid() { return this->state == ListenerState::VALID; } }; template <class... Params> class Listenable { private: typedef Listener<Params...> T__Listener; map<string, list<T__Listener>> eventListeners; public: virtual Listenable* clone() { return new Listenable<Params...>(*this); }; virtual void addListener(T__Listener listener, string event); virtual void removeListener(T__Listener listener, string event); virtual void removeListener(int listenerId, string event); virtual void removeAll(); virtual void clearInvalid(string event); virtual void notifyListeners(string event, Params... params); virtual bool operator==(Listenable<Params...>& listenable); virtual bool operator!=(Listenable<Params...>& listenable); }; template<class... Params> void Listenable<Params...>::addListener(T__Listener listener, string event) { listener.setValid(); if (eventListeners.find(event) == eventListeners.end()) { auto *listeners = new list<T__Listener>(); listeners->push_back(listener); eventListeners[event] = *listeners; } else { auto& listeners = eventListeners[event]; int thisId = listener.getListenerId(); auto iter = find_if(listeners.begin(), listeners.end(), [thisId](T__Listener lstn)->bool { return lstn.getListenerId() == thisId; }); if (iter != listeners.end()) { *iter = listener; } else { listeners.push_back(listener); eventListeners[event] = listeners; } } } template<class ...Params> inline void Listenable<Params...>::removeListener(T__Listener listener, string event) { removeListener(listener.getListenerId(), event); } template<class ...Params> inline void Listenable<Params...>::removeListener(int listenerId, string event) { auto iter = this->eventListeners.find(event); if (iter != this->eventListeners.end()) { auto listiter = iter->second.begin(); while (listiter != iter->second.end()) { if (listiter->getListenerId() == listenerId) { listiter->setInvalid(); break; } } } } template<class ...Params> inline void Listenable<Params...>::removeAll() { this->eventListeners.clear(); } template<class ...Params> inline void Listenable<Params...>::clearInvalid(string event) { auto iter = eventListeners.find(event); if (iter != eventListeners.end()) { list<T__Listener>& ref = iter->second; auto l_iter = ref.begin(); while ((l_iter = find_if(ref.begin(), ref.end(), [](T__Listener lstn)->bool { return !lstn.isValid(); })) != ref.end()) { ref.erase(l_iter); break; } } } template<class ...Params> inline void Listenable<Params...>::notifyListeners(string event, Params ...params) { clearInvalid(event); if (eventListeners.find(event) != eventListeners.end()) { for (auto listener : eventListeners[event]) { listener.notify(event, unpack(params)...); } } } template<class ...Params> inline bool Listenable<Params...>::operator==(Listenable<Params...>& listenable) { return this == &listenable; } template<class ...Params> inline bool Listenable<Params...>::operator!=(Listenable<Params...>& listenable) { return this != &listenable; } /*************Common Listenable***************/ typedef Listenable<CPoint> ClickListenable; typedef Listenable<UINT> KeyboardListenable; /**************Common Listeners****************/ typedef Listener<CPoint> ClickListener; typedef Listener<UINT> KeyboardListener;
[ "514380599@qq.com" ]
514380599@qq.com
5b012d99b0cb2f66b8cef08b309a723b824fd06e
d75797e0fd2d35135ea5847ed3e9c2c9c0efe562
/src/game/shared/cstrike/bot/bot.cpp
d81a64aadc7f41e8616eb704ab6da4be049ca87a
[]
no_license
GEEKiDoS/cstrike-asw
eb0b754042fe5a60ace2c19c88b56bb3186a406c
89d8cc74f049b56b21833924f02322088ab41e91
refs/heads/master
2020-03-19T17:02:26.505609
2018-06-09T18:02:14
2018-06-09T18:02:14
136,741,568
1
0
null
null
null
null
UTF-8
C++
false
false
2,824
cpp
//========= Copyright ?1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// // Author: Michael S. Booth (mike@turtlerockstudios.com), Leon Hartwig, 2003 #include "cbase.h" #include "basegrenade_shared.h" #include "bot.h" #include "bot_util.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" /// @todo Remove this nasty hack - CreateFakeClient() calls CBot::Spawn, which needs the profile and team const BotProfile *g_botInitProfile = NULL; int g_botInitTeam = 0; // // NOTE: Because CBot had to be templatized, the code was moved into bot.h // //-------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------- ActiveGrenade::ActiveGrenade( CBaseGrenade *grenadeEntity ) { m_entity = grenadeEntity; m_detonationPosition = grenadeEntity->GetAbsOrigin(); m_dieTimestamp = 0.0f; m_radius = HEGrenadeRadius; m_isSmoke = FStrEq( grenadeEntity->GetClassname(), "smokegrenade_projectile" ); if ( m_isSmoke ) { m_radius = SmokeGrenadeRadius; } m_isFlashbang = FStrEq( grenadeEntity->GetClassname(), "flashbang_projectile" ); if ( m_isFlashbang ) { m_radius = FlashbangGrenadeRadius; } } //-------------------------------------------------------------------------------------------------------------- /** * Called when the grenade in the world goes away */ void ActiveGrenade::OnEntityGone( void ) { if (m_isSmoke) { // smoke lingers after grenade is gone const float smokeLingerTime = 4.0f; m_dieTimestamp = gpGlobals->curtime + smokeLingerTime; } m_entity = NULL; } //-------------------------------------------------------------------------------------------------------------- void ActiveGrenade::Update( void ) { if (m_entity != NULL) { m_detonationPosition = m_entity->GetAbsOrigin(); } } //-------------------------------------------------------------------------------------------------------------- /** * Return true if this grenade is valid */ bool ActiveGrenade::IsValid( void ) const { if ( m_isSmoke ) { if ( m_entity == NULL && gpGlobals->curtime > m_dieTimestamp ) { return false; } } else { if ( m_entity == NULL ) { return false; } } return true; } //-------------------------------------------------------------------------------------------------------------- const Vector &ActiveGrenade::GetPosition( void ) const { // smoke grenades can vanish before the smoke itself does - refer to the detonation position if (m_entity == NULL) return GetDetonationPosition(); return m_entity->GetAbsOrigin(); }
[ "sb@sb.csb" ]
sb@sb.csb
fd51811ea5b18581e44350d1c65a5ee68155430a
94873a275343c446e7f357d8a2c5834b248137a5
/Google-Codejam/Google Code Jam/Round 1A 2016/B.cpp
ea8cbcdd8136fd144fbbec5821e4663ebb16d17c
[]
no_license
Shanshan-IC/Code-Practice
0485ed65ae60699d85478d1f15d4726d6f28a893
485c35e97cac03654b060bfb0ea3f129a98caba4
refs/heads/master
2021-01-11T09:12:35.106694
2017-11-25T10:42:50
2017-11-25T10:42:50
77,263,807
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
#include <iostream> #include <unordered_map> #include <vector> #include <algorithm> using namespace std; typedef unordered_map<int,int> mymap; // 思路很简单,出现个数为奇数的则是遗漏的 int main() { freopen("C:\\Users\\Administrator\\Downloads\\B-small-practice.in","r",stdin); freopen("C:\\Users\\Administrator\\Downloads\\B-small-attempt0.out","w",stdout); int num, n, a; cin >> num; mymap m; vector<int> vec; for (int i=0; i<num; i++) { m.clear(); vec.clear(); cout << "Case #" << i+1 << ": "; cin >> n; int k = n * (2 * n - 1); while (k--) { cin >> a; m[a]++; } for (mymap::iterator iter = m.begin(); iter != m.end(); iter++) if (iter->second % 2 !=0) vec.push_back(iter->first); sort(vec.begin(), vec.end()); for (int i=0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; } return 0; }
[ "shanshan.fu15@imperial.ac.uk" ]
shanshan.fu15@imperial.ac.uk