text
stringlengths
54
60.6k
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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. * * $Id$ */ #include <sensor_msgs/PointCloud2.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/kdtree/kdtree_flann.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; std::string default_correspondence_type = "index"; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s source.pcd target.pcd output_intensity.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -correspondence X = the way of selecting the corresponding pair in the target cloud for the current point in the source cloud\n"); print_info (" options are: index = points with identical indices are paired together. Note: both clouds need to have the same number of points\n"); print_info (" nn = source point is paired with its nearest neighbor in the target cloud\n"); print_info (" nnplane = source point is paired with its projection on the plane determined by the nearest neighbor in the target cloud. Note: target cloud needs to contain normals\n"); print_info (" (default: "); print_value ("%s", default_correspondence_type.c_str ()); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; // print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); // print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &cloud_source, const sensor_msgs::PointCloud2::ConstPtr &cloud_target, sensor_msgs::PointCloud2 &output, std::string correspondence_type) { // Estimate TicToc tt; tt.tic (); PointCloud<PointXYZ>::Ptr xyz_source (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_source, *xyz_source); PointCloud<PointXYZ>::Ptr xyz_target (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_target, *xyz_target); PointCloud<PointXYZI>::Ptr output_xyzi (new PointCloud<PointXYZI> ()); output_xyzi->points.resize (xyz_source->points.size ()); output_xyzi->height = cloud_source->height; output_xyzi->width = cloud_source->width; float rmse = 0.0f; if (correspondence_type == "index") { // print_highlight (stderr, "Computing using the equal indices correspondence heuristic.\n"); if (xyz_source->points.size () != xyz_target->points.size ()) { print_error ("Source and target clouds do not have the same number of points.\n"); return; } for (size_t point_i = 0; point_i < xyz_source->points.size (); ++point_i) { float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nn") { // print_highlight (stderr, "Computing using the nearest neighbor correspondence heuristic.\n"); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); tree->nearestKSearch (point_i, 1, nn_indices, nn_distances); size_t point_nn_i = nn_indices.front(); float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_nn_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nnplane") { // print_highlight (stderr, "Computing using the nearest neighbor plane projection correspondence heuristic.\n"); PointCloud<Normal>::Ptr normals_target (new PointCloud<Normal> ()); fromROSMsg (*cloud_target, *normals_target); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); tree->nearestKSearch (point_i, 1, nn_indices, nn_distances); size_t point_nn_i = nn_indices.front(); Eigen::Vector3f normal_target = normals_target->points[point_nn_i].getNormalVector3fMap (), point_source = xyz_source->points[point_i].getVector3fMap (), point_target = xyz_target->points[point_nn_i].getVector3fMap (); float dist = normal_target.dot (point_source - point_target); rmse += dist * dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist * dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else { print_error ("Unrecognized correspondence type. Check legal arguments by using the -h option\n"); return; } toROSMsg (*output_xyzi, output); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds]\n"); print_highlight ("RMSE Error: %f\n", rmse); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); // print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); // print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { // print_info ("Compute the differences between two point clouds and visualizing them as an output intensity cloud. For more information, use: %s -h\n", argv[0]); if (argc < 4) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 3) { print_error ("Need two input PCD files and one output PCD file to continue.\n"); return (-1); } // Command line parsing std::string correspondence_type = default_correspondence_type; parse_argument (argc, argv, "-correspondence", correspondence_type); // Load the first file sensor_msgs::PointCloud2::Ptr cloud_source (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[0]], *cloud_source)) return (-1); // Load the second file sensor_msgs::PointCloud2::Ptr cloud_target (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[1]], *cloud_target)) return (-1); sensor_msgs::PointCloud2 output; // Perform the feature estimation compute (cloud_source, cloud_target, output, correspondence_type); // Output the third file saveCloud (argv[p_file_indices[2]], output); } <commit_msg>compute_cloud_error tool can now handle nan points in the input clouds<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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. * * $Id$ */ #include <sensor_msgs/PointCloud2.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/kdtree/kdtree_flann.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; std::string default_correspondence_type = "index"; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s source.pcd target.pcd output_intensity.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -correspondence X = the way of selecting the corresponding pair in the target cloud for the current point in the source cloud\n"); print_info (" options are: index = points with identical indices are paired together. Note: both clouds need to have the same number of points\n"); print_info (" nn = source point is paired with its nearest neighbor in the target cloud\n"); print_info (" nnplane = source point is paired with its projection on the plane determined by the nearest neighbor in the target cloud. Note: target cloud needs to contain normals\n"); print_info (" (default: "); print_value ("%s", default_correspondence_type.c_str ()); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &cloud_source, const sensor_msgs::PointCloud2::ConstPtr &cloud_target, sensor_msgs::PointCloud2 &output, std::string correspondence_type) { // Estimate TicToc tt; tt.tic (); PointCloud<PointXYZ>::Ptr xyz_source (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_source, *xyz_source); PointCloud<PointXYZ>::Ptr xyz_target (new PointCloud<PointXYZ> ()); fromROSMsg (*cloud_target, *xyz_target); PointCloud<PointXYZI>::Ptr output_xyzi (new PointCloud<PointXYZI> ()); output_xyzi->points.resize (xyz_source->points.size ()); output_xyzi->height = cloud_source->height; output_xyzi->width = cloud_source->width; float rmse = 0.0f; if (correspondence_type == "index") { print_highlight (stderr, "Computing using the equal indices correspondence heuristic.\n"); if (xyz_source->points.size () != xyz_target->points.size ()) { print_error ("Source and target clouds do not have the same number of points.\n"); return; } for (size_t point_i = 0; point_i < xyz_source->points.size (); ++point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; if (!pcl_isfinite (xyz_target->points[point_i].x) || !pcl_isfinite (xyz_target->points[point_i].y) || !pcl_isfinite (xyz_target->points[point_i].z)) continue; float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nn") { print_highlight (stderr, "Computing using the nearest neighbor correspondence heuristic.\n"); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (point_i, 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); float dist = squaredEuclideanDistance (xyz_source->points[point_i], xyz_target->points[point_nn_i]); rmse += dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else if (correspondence_type == "nnplane") { print_highlight (stderr, "Computing using the nearest neighbor plane projection correspondence heuristic.\n"); PointCloud<Normal>::Ptr normals_target (new PointCloud<Normal> ()); fromROSMsg (*cloud_target, *normals_target); KdTreeFLANN<PointXYZ>::Ptr tree (new KdTreeFLANN<PointXYZ> ()); tree->setInputCloud (xyz_target); for (size_t point_i = 0; point_i < xyz_source->points.size (); ++ point_i) { if (!pcl_isfinite (xyz_source->points[point_i].x) || !pcl_isfinite (xyz_source->points[point_i].y) || !pcl_isfinite (xyz_source->points[point_i].z)) continue; std::vector<int> nn_indices (1); std::vector<float> nn_distances (1); if (!tree->nearestKSearch (point_i, 1, nn_indices, nn_distances)) continue; size_t point_nn_i = nn_indices.front(); Eigen::Vector3f normal_target = normals_target->points[point_nn_i].getNormalVector3fMap (), point_source = xyz_source->points[point_i].getVector3fMap (), point_target = xyz_target->points[point_nn_i].getVector3fMap (); float dist = normal_target.dot (point_source - point_target); rmse += dist * dist; output_xyzi->points[point_i].x = xyz_source->points[point_i].x; output_xyzi->points[point_i].y = xyz_source->points[point_i].y; output_xyzi->points[point_i].z = xyz_source->points[point_i].z; output_xyzi->points[point_i].intensity = dist * dist; } rmse = sqrt (rmse / xyz_source->points.size ()); } else { print_error ("Unrecognized correspondence type. Check legal arguments by using the -h option\n"); return; } toROSMsg (*output_xyzi, output); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds]\n"); print_highlight ("RMSE Error: %f\n", rmse); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { print_info ("Compute the differences between two point clouds and visualizing them as an output intensity cloud. For more information, use: %s -h\n", argv[0]); if (argc < 4) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 3) { print_error ("Need two input PCD files and one output PCD file to continue.\n"); return (-1); } // Command line parsing std::string correspondence_type = default_correspondence_type; parse_argument (argc, argv, "-correspondence", correspondence_type); // Load the first file sensor_msgs::PointCloud2::Ptr cloud_source (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[0]], *cloud_source)) return (-1); // Load the second file sensor_msgs::PointCloud2::Ptr cloud_target (new sensor_msgs::PointCloud2 ()); if (!loadCloud (argv[p_file_indices[1]], *cloud_target)) return (-1); sensor_msgs::PointCloud2 output; // Perform the feature estimation compute (cloud_source, cloud_target, output, correspondence_type); // Output the third file saveCloud (argv[p_file_indices[2]], output); } <|endoftext|>
<commit_before>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64 nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64 nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { return false; } void WalletModel::lockCoin(COutPoint& output) { return; } void WalletModel::unlockCoin(COutPoint& output) { return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { return; }<commit_msg>Update walletmodel.cpp<commit_after>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> extern bool fWalletUnlockMintOnly; WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64 nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64 nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } else if(fWalletUnlockMintOnly) { // Relock so the user must give the right passphrase to continue setWalletLocked(true); // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, wallet->mapWallet[outpoint.hash].GetDepthInMainChain()); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { return false; } void WalletModel::lockCoin(COutPoint& output) { return; } void WalletModel::unlockCoin(COutPoint& output) { return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { return; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "shared_realm.hpp" #include "external_commit_helper.hpp" #include "realm_delegate.hpp" #include "schema.hpp" #include "transact_log_handler.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <mutex> using namespace realm; RealmCache Realm::s_global_cache; Realm::Config::Config(const Config& c) : path(c.path) , read_only(c.read_only) , in_memory(c.in_memory) , cache(c.cache) , encryption_key(c.encryption_key) , schema_version(c.schema_version) , migration_function(c.migration_function) { if (c.schema) { schema = std::make_unique<Schema>(*c.schema); } } Realm::Config::~Config() = default; Realm::Config& Realm::Config::operator=(realm::Realm::Config const& c) { if (&c != this) { *this = Config(c); } return *this; } Realm::Realm(Config config) : m_config(std::move(config)) { try { if (m_config.read_only) { m_read_only_group = std::make_unique<Group>(m_config.path, m_config.encryption_key.data(), Group::mode_ReadOnly); m_group = m_read_only_group.get(); } else { m_history = realm::make_client_history(m_config.path, m_config.encryption_key.data()); SharedGroup::DurabilityLevel durability = m_config.in_memory ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full; m_shared_group = std::make_unique<SharedGroup>(*m_history, durability, m_config.encryption_key.data()); } } catch (util::File::PermissionDenied const& ex) { throw RealmFileException(RealmFileException::Kind::PermissionDenied, "Unable to open a realm at path '" + m_config.path + "'. Please use a path where your app has " + (m_config.read_only ? "read" : "read-write") + " permissions."); } catch (util::File::Exists const& ex) { throw RealmFileException(RealmFileException::Kind::Exists, "Unable to open a realm at path '" + m_config.path + "'"); } catch (util::File::AccessError const& ex) { throw RealmFileException(RealmFileException::Kind::AccessError, "Unable to open a realm at path '" + m_config.path + "'"); } catch (IncompatibleLockFile const&) { throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, "Realm file is currently open in another process " "which cannot share access with this process. All processes sharing a single file must be the same architecture."); } } Realm::~Realm() { if (m_notifier) { // might not exist yet if an error occurred during init m_notifier->remove_realm(this); } } Group *Realm::read_group() { if (!m_group) { m_group = &const_cast<Group&>(m_shared_group->begin_read()); } return m_group; } SharedRealm Realm::get_shared_realm(Config config) { if (config.cache) { if (SharedRealm realm = s_global_cache.get_realm(config.path)) { if (realm->config().read_only != config.read_only) { throw MismatchedConfigException("Realm at path already opened with different read permissions."); } if (realm->config().in_memory != config.in_memory) { throw MismatchedConfigException("Realm at path already opened with different inMemory settings."); } if (realm->config().encryption_key != config.encryption_key) { throw MismatchedConfigException("Realm at path already opened with a different encryption key."); } if (realm->config().schema_version != config.schema_version && config.schema_version != ObjectStore::NotVersioned) { throw MismatchedConfigException("Realm at path already opened with different schema version."); } // FIXME - enable schma comparison /*if (realm->config().schema != config.schema) { throw MismatchedConfigException("Realm at path already opened with different schema"); }*/ realm->m_config.migration_function = config.migration_function; return realm; } } SharedRealm realm(new Realm(std::move(config))); auto target_schema = std::move(realm->m_config.schema); auto target_schema_version = realm->m_config.schema_version; realm->m_config.schema_version = ObjectStore::get_schema_version(realm->read_group()); // we want to ensure we are only initializing a single realm at a time static std::mutex s_init_mutex; std::lock_guard<std::mutex> lock(s_init_mutex); if (auto existing = s_global_cache.get_any_realm(realm->config().path)) { // if there is an existing realm at the current path steal its schema/column mapping // FIXME - need to validate that schemas match realm->m_config.schema = std::make_unique<Schema>(*existing->m_config.schema); realm->m_notifier = existing->m_notifier; realm->m_notifier->add_realm(realm.get()); } else { realm->m_notifier = std::make_shared<ExternalCommitHelper>(realm.get()); // otherwise get the schema from the group realm->m_config.schema = std::make_unique<Schema>(ObjectStore::schema_from_group(realm->read_group())); // if a target schema is supplied, verify that it matches or migrate to // it, as neeeded if (target_schema) { if (realm->m_config.read_only) { if (realm->m_config.schema_version == ObjectStore::NotVersioned) { throw UnitializedRealmException("Can't open an un-initialized Realm without a Schema"); } target_schema->validate(); ObjectStore::verify_schema(*realm->m_config.schema, *target_schema, true); realm->m_config.schema = std::move(target_schema); } else { realm->update_schema(std::move(target_schema), target_schema_version); } } } if (config.cache) { s_global_cache.cache_realm(realm, realm->m_thread_id); } return realm; } bool Realm::update_schema(std::unique_ptr<Schema> schema, uint64_t version) { schema->validate(); bool needs_update = !m_config.read_only && (m_config.schema_version != version || ObjectStore::needs_update(*m_config.schema, *schema)); if (!needs_update) { ObjectStore::verify_schema(*m_config.schema, *schema, m_config.read_only); m_config.schema = std::move(schema); m_config.schema_version = version; return false; } // Store the old config/schema for the migration function, and update // our schema to the new one auto old_schema = std::move(m_config.schema); Config old_config(m_config); old_config.read_only = true; old_config.schema = std::move(old_schema); m_config.schema = std::move(schema); m_config.schema_version = version; auto migration_function = [&](Group*, Schema&) { SharedRealm old_realm(new Realm(old_config)); auto updated_realm = shared_from_this(); m_config.migration_function(old_realm, updated_realm); }; try { // update and migrate begin_transaction(); bool changed = ObjectStore::update_realm_with_schema(read_group(), *old_config.schema, version, *m_config.schema, migration_function); commit_transaction(); return changed; } catch (...) { if (is_in_transaction()) { cancel_transaction(); } m_config.schema_version = old_config.schema_version; m_config.schema = std::move(old_config.schema); throw; } } static void check_read_write(Realm *realm) { if (realm->config().read_only) { throw InvalidTransactionException("Can't perform transactions on read-only Realms."); } } void Realm::verify_thread() const { if (m_thread_id != std::this_thread::get_id()) { throw IncorrectThreadException("Realm accessed from incorrect thread."); } } void Realm::begin_transaction() { check_read_write(this); verify_thread(); if (m_in_transaction) { throw InvalidTransactionException("The Realm is already in a write transaction"); } // make sure we have a read transaction read_group(); transaction::begin(*m_shared_group, *m_history, m_delegate.get()); m_in_transaction = true; } void Realm::commit_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't commit a non-existing write transaction"); } m_in_transaction = false; transaction::commit(*m_shared_group, *m_history, m_delegate.get()); m_notifier->notify_others(); } void Realm::cancel_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't cancel a non-existing write transaction"); } m_in_transaction = false; transaction::cancel(*m_shared_group, *m_history, m_delegate.get()); } void Realm::invalidate() { verify_thread(); check_read_write(this); if (m_in_transaction) { cancel_transaction(); } if (!m_group) { return; } m_shared_group->end_read(); m_group = nullptr; } bool Realm::compact() { verify_thread(); if (m_config.read_only) { throw InvalidTransactionException("Can't compact a read-only Realm"); } if (m_in_transaction) { throw InvalidTransactionException("Can't compact a Realm within a write transaction"); } Group* group = read_group(); for (auto &object_schema : *m_config.schema) { ObjectStore::table_for_object_type(group, object_schema.name)->optimize(); } m_shared_group->end_read(); m_group = nullptr; return m_shared_group->compact(); } void Realm::notify() { verify_thread(); if (m_shared_group->has_changed()) { // Throws if (m_auto_refresh) { if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else if (m_delegate) { m_delegate->did_change({}, {}); } } else if (m_delegate) { m_delegate->changes_available(); } } } bool Realm::refresh() { verify_thread(); check_read_write(this); // can't be any new changes if we're in a write transaction if (m_in_transaction) { return false; } // advance transaction if database has changed if (!m_shared_group->has_changed()) { // Throws return false; } if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else { // Create the read transaction read_group(); } return true; } uint64_t Realm::get_schema_version(const realm::Realm::Config &config) { if (auto existing_realm = s_global_cache.get_any_realm(config.path)) { return existing_realm->config().schema_version; } return ObjectStore::get_schema_version(Realm(config).read_group()); } SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter == path_iter->second.end()) { return SharedRealm(); } return thread_iter->second.lock(); } SharedRealm RealmCache::get_any_realm(const std::string &path) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.begin(); while (thread_iter != path_iter->second.end()) { if (auto realm = thread_iter->second.lock()) { return realm; } path_iter->second.erase(thread_iter++); } return SharedRealm(); } void RealmCache::remove(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return; } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter != path_iter->second.end()) { path_iter->second.erase(thread_iter); } if (path_iter->second.size() == 0) { m_cache.erase(path_iter); } } void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(realm->config().path); if (path_iter == m_cache.end()) { m_cache.emplace(realm->config().path, std::map<std::thread::id, WeakRealm>{{thread_id, realm}}); } else { path_iter->second.emplace(thread_id, realm); } } void RealmCache::clear() { std::lock_guard<std::mutex> lock(m_mutex); m_cache.clear(); } <commit_msg>Send changes_available() even if autorefresh is enabled<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "shared_realm.hpp" #include "external_commit_helper.hpp" #include "realm_delegate.hpp" #include "schema.hpp" #include "transact_log_handler.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <mutex> using namespace realm; RealmCache Realm::s_global_cache; Realm::Config::Config(const Config& c) : path(c.path) , read_only(c.read_only) , in_memory(c.in_memory) , cache(c.cache) , encryption_key(c.encryption_key) , schema_version(c.schema_version) , migration_function(c.migration_function) { if (c.schema) { schema = std::make_unique<Schema>(*c.schema); } } Realm::Config::~Config() = default; Realm::Config& Realm::Config::operator=(realm::Realm::Config const& c) { if (&c != this) { *this = Config(c); } return *this; } Realm::Realm(Config config) : m_config(std::move(config)) { try { if (m_config.read_only) { m_read_only_group = std::make_unique<Group>(m_config.path, m_config.encryption_key.data(), Group::mode_ReadOnly); m_group = m_read_only_group.get(); } else { m_history = realm::make_client_history(m_config.path, m_config.encryption_key.data()); SharedGroup::DurabilityLevel durability = m_config.in_memory ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full; m_shared_group = std::make_unique<SharedGroup>(*m_history, durability, m_config.encryption_key.data()); } } catch (util::File::PermissionDenied const& ex) { throw RealmFileException(RealmFileException::Kind::PermissionDenied, "Unable to open a realm at path '" + m_config.path + "'. Please use a path where your app has " + (m_config.read_only ? "read" : "read-write") + " permissions."); } catch (util::File::Exists const& ex) { throw RealmFileException(RealmFileException::Kind::Exists, "Unable to open a realm at path '" + m_config.path + "'"); } catch (util::File::AccessError const& ex) { throw RealmFileException(RealmFileException::Kind::AccessError, "Unable to open a realm at path '" + m_config.path + "'"); } catch (IncompatibleLockFile const&) { throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, "Realm file is currently open in another process " "which cannot share access with this process. All processes sharing a single file must be the same architecture."); } } Realm::~Realm() { if (m_notifier) { // might not exist yet if an error occurred during init m_notifier->remove_realm(this); } } Group *Realm::read_group() { if (!m_group) { m_group = &const_cast<Group&>(m_shared_group->begin_read()); } return m_group; } SharedRealm Realm::get_shared_realm(Config config) { if (config.cache) { if (SharedRealm realm = s_global_cache.get_realm(config.path)) { if (realm->config().read_only != config.read_only) { throw MismatchedConfigException("Realm at path already opened with different read permissions."); } if (realm->config().in_memory != config.in_memory) { throw MismatchedConfigException("Realm at path already opened with different inMemory settings."); } if (realm->config().encryption_key != config.encryption_key) { throw MismatchedConfigException("Realm at path already opened with a different encryption key."); } if (realm->config().schema_version != config.schema_version && config.schema_version != ObjectStore::NotVersioned) { throw MismatchedConfigException("Realm at path already opened with different schema version."); } // FIXME - enable schma comparison /*if (realm->config().schema != config.schema) { throw MismatchedConfigException("Realm at path already opened with different schema"); }*/ realm->m_config.migration_function = config.migration_function; return realm; } } SharedRealm realm(new Realm(std::move(config))); auto target_schema = std::move(realm->m_config.schema); auto target_schema_version = realm->m_config.schema_version; realm->m_config.schema_version = ObjectStore::get_schema_version(realm->read_group()); // we want to ensure we are only initializing a single realm at a time static std::mutex s_init_mutex; std::lock_guard<std::mutex> lock(s_init_mutex); if (auto existing = s_global_cache.get_any_realm(realm->config().path)) { // if there is an existing realm at the current path steal its schema/column mapping // FIXME - need to validate that schemas match realm->m_config.schema = std::make_unique<Schema>(*existing->m_config.schema); realm->m_notifier = existing->m_notifier; realm->m_notifier->add_realm(realm.get()); } else { realm->m_notifier = std::make_shared<ExternalCommitHelper>(realm.get()); // otherwise get the schema from the group realm->m_config.schema = std::make_unique<Schema>(ObjectStore::schema_from_group(realm->read_group())); // if a target schema is supplied, verify that it matches or migrate to // it, as neeeded if (target_schema) { if (realm->m_config.read_only) { if (realm->m_config.schema_version == ObjectStore::NotVersioned) { throw UnitializedRealmException("Can't open an un-initialized Realm without a Schema"); } target_schema->validate(); ObjectStore::verify_schema(*realm->m_config.schema, *target_schema, true); realm->m_config.schema = std::move(target_schema); } else { realm->update_schema(std::move(target_schema), target_schema_version); } } } if (config.cache) { s_global_cache.cache_realm(realm, realm->m_thread_id); } return realm; } bool Realm::update_schema(std::unique_ptr<Schema> schema, uint64_t version) { schema->validate(); bool needs_update = !m_config.read_only && (m_config.schema_version != version || ObjectStore::needs_update(*m_config.schema, *schema)); if (!needs_update) { ObjectStore::verify_schema(*m_config.schema, *schema, m_config.read_only); m_config.schema = std::move(schema); m_config.schema_version = version; return false; } // Store the old config/schema for the migration function, and update // our schema to the new one auto old_schema = std::move(m_config.schema); Config old_config(m_config); old_config.read_only = true; old_config.schema = std::move(old_schema); m_config.schema = std::move(schema); m_config.schema_version = version; auto migration_function = [&](Group*, Schema&) { SharedRealm old_realm(new Realm(old_config)); auto updated_realm = shared_from_this(); m_config.migration_function(old_realm, updated_realm); }; try { // update and migrate begin_transaction(); bool changed = ObjectStore::update_realm_with_schema(read_group(), *old_config.schema, version, *m_config.schema, migration_function); commit_transaction(); return changed; } catch (...) { if (is_in_transaction()) { cancel_transaction(); } m_config.schema_version = old_config.schema_version; m_config.schema = std::move(old_config.schema); throw; } } static void check_read_write(Realm *realm) { if (realm->config().read_only) { throw InvalidTransactionException("Can't perform transactions on read-only Realms."); } } void Realm::verify_thread() const { if (m_thread_id != std::this_thread::get_id()) { throw IncorrectThreadException("Realm accessed from incorrect thread."); } } void Realm::begin_transaction() { check_read_write(this); verify_thread(); if (m_in_transaction) { throw InvalidTransactionException("The Realm is already in a write transaction"); } // make sure we have a read transaction read_group(); transaction::begin(*m_shared_group, *m_history, m_delegate.get()); m_in_transaction = true; } void Realm::commit_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't commit a non-existing write transaction"); } m_in_transaction = false; transaction::commit(*m_shared_group, *m_history, m_delegate.get()); m_notifier->notify_others(); } void Realm::cancel_transaction() { check_read_write(this); verify_thread(); if (!m_in_transaction) { throw InvalidTransactionException("Can't cancel a non-existing write transaction"); } m_in_transaction = false; transaction::cancel(*m_shared_group, *m_history, m_delegate.get()); } void Realm::invalidate() { verify_thread(); check_read_write(this); if (m_in_transaction) { cancel_transaction(); } if (!m_group) { return; } m_shared_group->end_read(); m_group = nullptr; } bool Realm::compact() { verify_thread(); if (m_config.read_only) { throw InvalidTransactionException("Can't compact a read-only Realm"); } if (m_in_transaction) { throw InvalidTransactionException("Can't compact a Realm within a write transaction"); } Group* group = read_group(); for (auto &object_schema : *m_config.schema) { ObjectStore::table_for_object_type(group, object_schema.name)->optimize(); } m_shared_group->end_read(); m_group = nullptr; return m_shared_group->compact(); } void Realm::notify() { verify_thread(); if (m_shared_group->has_changed()) { // Throws if (m_delegate) { m_delegate->changes_available(); } if (m_auto_refresh) { if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else if (m_delegate) { m_delegate->did_change({}, {}); } } } } bool Realm::refresh() { verify_thread(); check_read_write(this); // can't be any new changes if we're in a write transaction if (m_in_transaction) { return false; } // advance transaction if database has changed if (!m_shared_group->has_changed()) { // Throws return false; } if (m_group) { transaction::advance(*m_shared_group, *m_history, m_delegate.get()); } else { // Create the read transaction read_group(); } return true; } uint64_t Realm::get_schema_version(const realm::Realm::Config &config) { if (auto existing_realm = s_global_cache.get_any_realm(config.path)) { return existing_realm->config().schema_version; } return ObjectStore::get_schema_version(Realm(config).read_group()); } SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter == path_iter->second.end()) { return SharedRealm(); } return thread_iter->second.lock(); } SharedRealm RealmCache::get_any_realm(const std::string &path) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return SharedRealm(); } auto thread_iter = path_iter->second.begin(); while (thread_iter != path_iter->second.end()) { if (auto realm = thread_iter->second.lock()) { return realm; } path_iter->second.erase(thread_iter++); } return SharedRealm(); } void RealmCache::remove(const std::string &path, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(path); if (path_iter == m_cache.end()) { return; } auto thread_iter = path_iter->second.find(thread_id); if (thread_iter != path_iter->second.end()) { path_iter->second.erase(thread_iter); } if (path_iter->second.size() == 0) { m_cache.erase(path_iter); } } void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) { std::lock_guard<std::mutex> lock(m_mutex); auto path_iter = m_cache.find(realm->config().path); if (path_iter == m_cache.end()) { m_cache.emplace(realm->config().path, std::map<std::thread::id, WeakRealm>{{thread_id, realm}}); } else { path_iter->second.emplace(thread_id, realm); } } void RealmCache::clear() { std::lock_guard<std::mutex> lock(m_mutex); m_cache.clear(); } <|endoftext|>
<commit_before>/** * Copyright 2010 Google 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. */ // Copyright 2006 Google Inc. All Rights Reserved. // Author: [email protected] (Daniel Peng) #include "webutil/html/htmltagenum.h" #include "base/macros.h" #include "base/stringprintf.h" const char* HtmlTagEnumNames[] = { "Unknown", "A", "Abbr", "Acronym", "Address", "Applet", "Area", "B", "Base", "Basefont", "Bdo", "Big", "Blockquote", "Body", "Br", "Button", "Caption", "Center", "Cite", "Code", "Col", "Colgroup", "Dd", "Del", "Dfn", "Dir", "Div", "Dl", "Dt", "Em", "Fieldset", "Font", "Form", "Frame", "Frameset", "H1", "H2", "H3", "H4", "H5", "H6", "Head", "Hr", "Html", "I", "Iframe", "Img", "Input", "Ins", "Isindex", "Kbd", "Label", "Legend", "Li", "Link", "Map", "Menu", "Meta", "Noframes", "Noscript", "Object", "Ol", "Optgroup", "Option", "P", "Param", "Pre", "Q", "S", "Samp", "Script", "Select", "Small", "Span", "Strike", "Strong", "Style", "Sub", "Sup", "Table", "Tbody", "Td", "Textarea", "Tfoot", "Th", "Thead", "Title", "Tr", "Tt", "U", "Ul", "Var", // Empty tag "ZeroLength", // Used in repository/lexer/html_lexer.cc "!--", "Blink", // Used in repository/parsers/base/handler-parser.cc "Embed", "Marquee", // Legacy backwards-compatible tags mentioned in HTML5. "Nobr", "Wbr", "Bgsound", "Image", "Listing", "Noembed", "Plaintext", "Spacer", "Xmp", // From Netscape Navigator 4.0 "Ilayer", "Keygen", "Layer", "Multicol", "Nolayer", "Server", // !doctype "!Doctype", // Legacy tag used mostly by Russian sites. "Noindex", // Old style comments, "!Comment", // New tags in HTML5. "Article", "Aside", "Audio", "Bdi", "Canvas", "Command", "Datalist", "Details", "Figcaption", "Figure", "Footer", "Header", "Hgroup", "Mark", "Meter", "Nav", "Output", "Progress", "Rp", "Rt", "Ruby", "Section", "Source", "Summary", "Time", "Track", "Video", }; COMPILE_ASSERT(arraysize(HtmlTagEnumNames) == kHtmlTagBuiltinMax, ForgotToAddTagToHtmlTagEnumNames); const char* HtmlTagName(HtmlTagEnum tag) { if (tag < kHtmlTagBuiltinMax) { return HtmlTagEnumNames[tag]; } else { return NULL; } } string HtmlTagNameOrUnknown(int i) { if (i < kHtmlTagBuiltinMax) { return HtmlTagEnumNames[i]; } else { return StringPrintf("UNKNOWN%d", i); } } <commit_msg>Fix negative number error condition. (from rdm)<commit_after>/** * Copyright 2010 Google 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. */ // Copyright 2006 Google Inc. All Rights Reserved. // Author: [email protected] (Daniel Peng) #include "webutil/html/htmltagenum.h" #include "base/macros.h" #include "base/stringprintf.h" const char* HtmlTagEnumNames[] = { "Unknown", "A", "Abbr", "Acronym", "Address", "Applet", "Area", "B", "Base", "Basefont", "Bdo", "Big", "Blockquote", "Body", "Br", "Button", "Caption", "Center", "Cite", "Code", "Col", "Colgroup", "Dd", "Del", "Dfn", "Dir", "Div", "Dl", "Dt", "Em", "Fieldset", "Font", "Form", "Frame", "Frameset", "H1", "H2", "H3", "H4", "H5", "H6", "Head", "Hr", "Html", "I", "Iframe", "Img", "Input", "Ins", "Isindex", "Kbd", "Label", "Legend", "Li", "Link", "Map", "Menu", "Meta", "Noframes", "Noscript", "Object", "Ol", "Optgroup", "Option", "P", "Param", "Pre", "Q", "S", "Samp", "Script", "Select", "Small", "Span", "Strike", "Strong", "Style", "Sub", "Sup", "Table", "Tbody", "Td", "Textarea", "Tfoot", "Th", "Thead", "Title", "Tr", "Tt", "U", "Ul", "Var", // Empty tag "ZeroLength", // Used in repository/lexer/html_lexer.cc "!--", "Blink", // Used in repository/parsers/base/handler-parser.cc "Embed", "Marquee", // Legacy backwards-compatible tags mentioned in HTML5. "Nobr", "Wbr", "Bgsound", "Image", "Listing", "Noembed", "Plaintext", "Spacer", "Xmp", // From Netscape Navigator 4.0 "Ilayer", "Keygen", "Layer", "Multicol", "Nolayer", "Server", // !doctype "!Doctype", // Legacy tag used mostly by Russian sites. "Noindex", // Old style comments, "!Comment", // New tags in HTML5. "Article", "Aside", "Audio", "Bdi", "Canvas", "Command", "Datalist", "Details", "Figcaption", "Figure", "Footer", "Header", "Hgroup", "Mark", "Meter", "Nav", "Output", "Progress", "Rp", "Rt", "Ruby", "Section", "Source", "Summary", "Time", "Track", "Video", }; COMPILE_ASSERT(arraysize(HtmlTagEnumNames) == kHtmlTagBuiltinMax, ForgotToAddTagToHtmlTagEnumNames); const char* HtmlTagName(HtmlTagEnum tag) { if (tag < kHtmlTagBuiltinMax) { return HtmlTagEnumNames[tag]; } else { return NULL; } } string HtmlTagNameOrUnknown(int i) { if (i >= 0 && i < kHtmlTagBuiltinMax) { return HtmlTagEnumNames[i]; } else { return StringPrintf("UNKNOWN%d", i); } } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/translate/upgrade_graph.h" namespace tensorflow { Status GenerateResourceSharedNameIfEmpty(Graph& graph, FunctionLibraryDefinition& flib_def) { auto is_resource_op_with_empty_shared_name = [](const NodeDef& node_def, const OpDef& op_def) { // Only upgrade when it is a resource handle op. if (op_def.output_arg().size() != 1 || op_def.output_arg(0).type() != tensorflow::DT_RESOURCE) return false; // If the OpDef has "use_node_name_sharing" field, then it is valid to use // node names as shared names. if (!std::any_of(op_def.attr().begin(), op_def.attr().end(), [](const auto& attr_def) { return attr_def.name() == "use_node_name_sharing" && attr_def.type() == "bool"; })) return false; if (!std::any_of(op_def.attr().begin(), op_def.attr().end(), [](const auto& attr_def) { return attr_def.name() == "shared_name" && attr_def.type() == "string"; })) return false; auto iter = node_def.attr().find("shared_name"); if (iter == node_def.attr().end()) return true; return iter->second.s().empty(); }; // Upgrade nodes in the graph. for (auto* node : graph.nodes()) { if (is_resource_op_with_empty_shared_name(node->def(), node->op_def())) { node->AddAttr("shared_name", node->name()); } } // Upgrade nodes in the functions. auto func_names = flib_def.ListFunctionNames(); for (const auto& func_name : func_names) { const FunctionDef* orig = flib_def.Find(func_name); DCHECK(orig); auto copy = *orig; for (auto& node_def : *copy.mutable_node_def()) { const OpDef* op_def = nullptr; TF_RETURN_IF_ERROR(flib_def.LookUpOpDef(node_def.op(), &op_def)); if (is_resource_op_with_empty_shared_name(node_def, *op_def)) { // Use the concat of function name and node name for such ops in a // function as the shared_name. "@" is used as the separator because it // is not allowed in the function name or the node name. (*node_def.mutable_attr())["shared_name"].set_s( absl::StrCat(node_def.name(), "@", func_name)); } } TF_RETURN_IF_ERROR(flib_def.ReplaceFunction(func_name, copy)); } return tensorflow::Status::OK(); } } // namespace tensorflow <commit_msg>Remove the requirement of return resource handle when generating shared_name if it is empty.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/translate/upgrade_graph.h" namespace tensorflow { Status GenerateResourceSharedNameIfEmpty(Graph& graph, FunctionLibraryDefinition& flib_def) { auto is_resource_op_with_empty_shared_name = [](const NodeDef& node_def, const OpDef& op_def) { // If the OpDef has "use_node_name_sharing" field, then it is valid to use // node names as shared names. if (!std::any_of(op_def.attr().begin(), op_def.attr().end(), [](const auto& attr_def) { return attr_def.name() == "use_node_name_sharing" && attr_def.type() == "bool"; })) return false; if (!std::any_of(op_def.attr().begin(), op_def.attr().end(), [](const auto& attr_def) { return attr_def.name() == "shared_name" && attr_def.type() == "string"; })) return false; auto iter = node_def.attr().find("shared_name"); if (iter == node_def.attr().end()) return true; return iter->second.s().empty(); }; // Upgrade nodes in the graph. for (auto* node : graph.nodes()) { if (is_resource_op_with_empty_shared_name(node->def(), node->op_def())) { node->AddAttr("shared_name", node->name()); } } // Upgrade nodes in the functions. auto func_names = flib_def.ListFunctionNames(); for (const auto& func_name : func_names) { const FunctionDef* orig = flib_def.Find(func_name); DCHECK(orig); auto copy = *orig; for (auto& node_def : *copy.mutable_node_def()) { const OpDef* op_def = nullptr; TF_RETURN_IF_ERROR(flib_def.LookUpOpDef(node_def.op(), &op_def)); if (is_resource_op_with_empty_shared_name(node_def, *op_def)) { // Use the concat of function name and node name for such ops in a // function as the shared_name. "@" is used as the separator because it // is not allowed in the function name or the node name. (*node_def.mutable_attr())["shared_name"].set_s( absl::StrCat(node_def.name(), "@", func_name)); } } TF_RETURN_IF_ERROR(flib_def.ReplaceFunction(func_name, copy)); } return tensorflow::Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before><commit_msg>Added in smooth scrolling for TabMenu, going to the right needs adjustment.<commit_after><|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "routing/routing_callbacks.hpp" #include "routing/routing_integration_tests/routing_test_tools.hpp" #include "geometry/mercator.hpp" #include "base/math.hpp" using namespace integration; using namespace routing; using namespace routing::turns; UNIT_TEST(RussiaMoscowSevTushinoParkPreferingBicycleWay) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.87445, 37.43711), {0., 0.}, MercatorBounds::FromLatLon(55.87203, 37.44274), 460.0); } UNIT_TEST(RussiaMoscowNahimovskyLongRoute) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66151, 37.63320), {0., 0.}, MercatorBounds::FromLatLon(55.67695, 37.56220), 5670.0); } UNIT_TEST(RussiaDomodedovoSteps) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.44010, 37.77416), {0., 0.}, MercatorBounds::FromLatLon(55.43975, 37.77272), 100.0); } UNIT_TEST(SwedenStockholmCyclewayPriority) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(59.33151, 18.09347), {0., 0.}, MercatorBounds::FromLatLon(59.33052, 18.09391), 113.0); } // Note. If the closest to start or finish road has "bicycle=no" tag the closest road where // it's allowed to ride bicycle will be found. UNIT_TEST(NetherlandsAmsterdamBicycleNo) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.32716, 5.05932), {0., 0.}, MercatorBounds::FromLatLon(52.32587, 5.06121), 363.4); } UNIT_TEST(NetherlandsAmsterdamBicycleYes) { TRouteResult const routeResult = CalculateRoute(GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.32872, 5.07527), {0.0, 0.0}, MercatorBounds::FromLatLon(52.33853, 5.08941)); Route const & route = *routeResult.first; RouterResultCode const result = routeResult.second; TEST_EQUAL(result, RouterResultCode::NoError, ()); TEST(base::AlmostEqualAbs(route.GetTotalTimeSec(), 334.69, 1.0), (route.GetTotalTimeSec())); } // This test on tag cycleway=opposite for a streets which have oneway=yes. // It means bicycles may go in the both directions. UNIT_TEST(NetherlandsAmsterdamSingelStCyclewayOpposite) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.37571, 4.88591), {0., 0.}, MercatorBounds::FromLatLon(52.37736, 4.88744), 212.8); } UNIT_TEST(RussiaMoscowKashirskoe16ToCapLongRoute) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66230, 37.63214), {0., 0.}, MercatorBounds::FromLatLon(55.68927, 37.70356), 7075.0); } // No pass through service road in Russia UNIT_TEST(RussiaMoscowNoServicePassThrough) { TRouteResult route = integration::CalculateRoute(integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66230, 37.63214), {0., 0.}, MercatorBounds::FromLatLon(55.68895, 37.70286)); TEST_EQUAL(route.second, RouterResultCode::RouteNotFound, ()); } // TODO: This test doesn't pass because routing::RouteWeight::operator< // prefer roads with less number of barriers. It will be more useful to consider // barriers only with access=no/private/etc tag. //UNIT_TEST(RussiaKerchStraitFerryRoute) //{ // CalculateRouteAndTestRouteLength( // GetVehicleComponents(VehicleType::Bicycle), // MercatorBounds::FromLatLon(45.4167, 36.7658), {0.0, 0.0}, // MercatorBounds::FromLatLon(45.3653, 36.6161), 18000.0); //} // Test on building bicycle route past ferry. UNIT_TEST(SwedenStockholmBicyclePastFerry) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(59.4725, 18.51355), {0.0, 0.0}, MercatorBounds::FromLatLon(59.32967, 18.075), 66161.2); } UNIT_TEST(CrossMwmKaliningradRegionToLiepaja) { integration::CalculateRouteAndTestRouteLength( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.15414, 20.85378), {0., 0.}, MercatorBounds::FromLatLon(56.51119, 21.01847), 192000); } // Test on riding up from Adeje (sea level) to Vilaflor (altitude 1400 meters). UNIT_TEST(SpainTenerifeAdejeVilaflor) { integration::CalculateRouteAndTestRouteTime( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(28.11984, -16.72592), {0.0, 0.0}, MercatorBounds::FromLatLon(28.15865, -16.63704), 18019.6 /* expectedTimeSeconds */); } // Test on riding down from Vilaflor (altitude 1400 meters) to Adeje (sea level). UNIT_TEST(SpainTenerifeVilaflorAdeje) { integration::CalculateRouteAndTestRouteTime( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(28.15865, -16.63704), {0.0, 0.0}, MercatorBounds::FromLatLon(28.11984, -16.72592), 8868.36 /* expectedTimeSeconds */); } <commit_msg>[routing] Adding routing integration tests on passing through living_street and service roads for bicycle in Russia.<commit_after>#include "testing/testing.hpp" #include "routing/routing_callbacks.hpp" #include "routing/routing_integration_tests/routing_test_tools.hpp" #include "geometry/mercator.hpp" #include "base/math.hpp" using namespace integration; using namespace routing; using namespace routing::turns; UNIT_TEST(RussiaMoscowSevTushinoParkPreferingBicycleWay) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.87445, 37.43711), {0., 0.}, MercatorBounds::FromLatLon(55.87203, 37.44274), 460.0); } UNIT_TEST(RussiaMoscowNahimovskyLongRoute) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66151, 37.63320), {0., 0.}, MercatorBounds::FromLatLon(55.67695, 37.56220), 5670.0); } UNIT_TEST(RussiaDomodedovoSteps) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.44010, 37.77416), {0., 0.}, MercatorBounds::FromLatLon(55.43975, 37.77272), 100.0); } UNIT_TEST(SwedenStockholmCyclewayPriority) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(59.33151, 18.09347), {0., 0.}, MercatorBounds::FromLatLon(59.33052, 18.09391), 113.0); } // Note. If the closest to start or finish road has "bicycle=no" tag the closest road where // it's allowed to ride bicycle will be found. UNIT_TEST(NetherlandsAmsterdamBicycleNo) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.32716, 5.05932), {0., 0.}, MercatorBounds::FromLatLon(52.32587, 5.06121), 363.4); } UNIT_TEST(NetherlandsAmsterdamBicycleYes) { TRouteResult const routeResult = CalculateRoute(GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.32872, 5.07527), {0.0, 0.0}, MercatorBounds::FromLatLon(52.33853, 5.08941)); Route const & route = *routeResult.first; RouterResultCode const result = routeResult.second; TEST_EQUAL(result, RouterResultCode::NoError, ()); TEST(base::AlmostEqualAbs(route.GetTotalTimeSec(), 334.69, 1.0), (route.GetTotalTimeSec())); } // This test on tag cycleway=opposite for a streets which have oneway=yes. // It means bicycles may go in the both directions. UNIT_TEST(NetherlandsAmsterdamSingelStCyclewayOpposite) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(52.37571, 4.88591), {0., 0.}, MercatorBounds::FromLatLon(52.37736, 4.88744), 212.8); } UNIT_TEST(RussiaMoscowKashirskoe16ToCapLongRoute) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66230, 37.63214), {0., 0.}, MercatorBounds::FromLatLon(55.68927, 37.70356), 7075.0); } // Passing through living_street and service are allowed in Russia UNIT_TEST(RussiaMoscowServicePassThrough1) { TRouteResult route = integration::CalculateRoute(integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.66230, 37.63214), {0., 0.}, MercatorBounds::FromLatLon(55.68895, 37.70286)); TEST_EQUAL(route.second, RouterResultCode::NoError, ()); } UNIT_TEST(RussiaMoscowServicePassThrough2) { TRouteResult route = integration::CalculateRoute(integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.69038, 37.70015), {0., 0.}, MercatorBounds::FromLatLon(55.69123, 37.6953)); TEST_EQUAL(route.second, RouterResultCode::NoError, ()); } UNIT_TEST(RussiaMoscowServicePassThrough3) { TRouteResult route = integration::CalculateRoute(integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.79649, 37.53738), {0., 0.}, MercatorBounds::FromLatLon(55.79618, 37.54071)); TEST_EQUAL(route.second, RouterResultCode::NoError, ()); } // TODO: This test doesn't pass because routing::RouteWeight::operator< // prefer roads with less number of barriers. It will be more useful to consider // barriers only with access=no/private/etc tag. //UNIT_TEST(RussiaKerchStraitFerryRoute) //{ // CalculateRouteAndTestRouteLength( // GetVehicleComponents(VehicleType::Bicycle), // MercatorBounds::FromLatLon(45.4167, 36.7658), {0.0, 0.0}, // MercatorBounds::FromLatLon(45.3653, 36.6161), 18000.0); //} // Test on building bicycle route past ferry. UNIT_TEST(SwedenStockholmBicyclePastFerry) { CalculateRouteAndTestRouteLength( GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(59.4725, 18.51355), {0.0, 0.0}, MercatorBounds::FromLatLon(59.32967, 18.075), 66161.2); } UNIT_TEST(CrossMwmKaliningradRegionToLiepaja) { integration::CalculateRouteAndTestRouteLength( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(55.15414, 20.85378), {0., 0.}, MercatorBounds::FromLatLon(56.51119, 21.01847), 192000); } // Test on riding up from Adeje (sea level) to Vilaflor (altitude 1400 meters). UNIT_TEST(SpainTenerifeAdejeVilaflor) { integration::CalculateRouteAndTestRouteTime( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(28.11984, -16.72592), {0.0, 0.0}, MercatorBounds::FromLatLon(28.15865, -16.63704), 18019.6 /* expectedTimeSeconds */); } // Test on riding down from Vilaflor (altitude 1400 meters) to Adeje (sea level). UNIT_TEST(SpainTenerifeVilaflorAdeje) { integration::CalculateRouteAndTestRouteTime( integration::GetVehicleComponents(VehicleType::Bicycle), MercatorBounds::FromLatLon(28.15865, -16.63704), {0.0, 0.0}, MercatorBounds::FromLatLon(28.11984, -16.72592), 8868.36 /* expectedTimeSeconds */); } <|endoftext|>
<commit_before><commit_msg>tidying<commit_after><|endoftext|>
<commit_before><commit_msg>quotient_info.hpp: extra template parameters<commit_after><|endoftext|>
<commit_before>// $Id: parameterSection.C,v 1.16 2001/03/12 00:50:35 amoll Exp $ #include <BALL/FORMAT/parameterSection.h> #include <BALL/FORMAT/parameters.h> using namespace std; namespace BALL { const String ParameterSection::UNDEFINED = "(UNDEFINED)"; ParameterSection::ParameterSection() throw() : section_name_(""), format_line_(""), section_entries_(), variable_names_(), entries_(0), keys_(0), number_of_variables_(0), version_(0), valid_(false) { } ParameterSection::ParameterSection(const ParameterSection& parameter_section) throw() : section_name_(parameter_section.section_name_), format_line_(parameter_section.format_line_), section_entries_(parameter_section.section_entries_), variable_names_(parameter_section.variable_names_), entries_(parameter_section.entries_), keys_(parameter_section.keys_), number_of_variables_(parameter_section.number_of_variables_), version_(parameter_section.version_), valid_(parameter_section.valid_) { } ParameterSection::~ParameterSection() throw() { clear(); } void ParameterSection::clear() throw() { // clear the section name section_name_ = ""; format_line_ = ""; // destroy all hash maps section_entries_.clear(); variable_names_.clear(); // clear all allocated entries entries_.clear(); // clear all keys keys_.clear(); // delete the version array version_.clear(); // clear the number of entries/variables number_of_variables_ = 0; // tag this instance as invalid valid_ = false; } const String& ParameterSection::getSectionName() const throw() { return section_name_; } bool ParameterSection::extractSection(Parameters& parameters, const String& section_name) throw() { if (!parameters.isValid()) { return false; } // this instance is only valid if extractSection works valid_ = false; // store the section name section_name_ = section_name; INIFile& ini_file = parameters.getParameterFile(); // check for the existence of the required section if (!ini_file.hasSection(section_name) || ini_file.getSectionLength(section_name) == 0) { return false; } // if section has the length 0, we are finished if (ini_file.getSectionLength(section_name) == 0) { Log.info() << "ParameterSectionFile " << ini_file.getFilename() << " Section " << section_name << "isEmpty." << endl; return true; } // ================================================================ // loop over all lines and store the format line // skip all comment and options lines // count the number of non-comment lines // count non-comment lines only int number_of_lines = 0; String line; Size first_line = ini_file.getSectionFirstLine(section_name); Size last_line = ini_file.getSectionLastLine(section_name); for (Position i = first_line; i <= last_line; i++) { // get the line and remove leading white spaces if (ini_file.getLine(i) == 0) { Log.error() << "Error in call to INIFile::getLine(), i = " << i << " , File: << " << ini_file.getFilename() << endl; return false; } line = *ini_file.getLine(i); line.trimLeft(); // skip all empty lines, comments and option lines if (line.isEmpty() || (line[0] == ';') || (line[0] == '!') || (line[0] == '#') || (line[0] == '@')) { // comment lines start with "!" or ";" or "#" // option lines start with "@" continue; } // extract format line: the first non-comment/non-option line if (number_of_lines == 0) { format_line_ = line; } // count non-comment lines number_of_lines++; } // =========================================================================== // interpret the format line // f contains the fields resulting from a splitQuoted of the format line vector<String> f; Size number_of_fields = format_line_.split(f, String::CHARACTER_CLASS__WHITESPACE); if (number_of_fields == 0 || number_of_fields > 20) { Log.error() << "ParameterSection::extractSection: error reading section " << section_name << " of file " << ini_file.getFilename() << ": wrong number of fields in the format line: " << number_of_fields << endl; Log.error() << "FORMAT: " << format_line_ << endl; return false; } // Initialisations: // keys is an array containing the fields that will be assembled to the line key Index keys[ParameterSection::MAX_FIELDS]; Size number_of_keys = 0; // variables is an array containing the fields that represent variables Index variables[ParameterSection::MAX_FIELDS]; Size number_of_variables = 0; // clear the old contents of variable_names_ variable_names_.clear(); // check every field definition for (Position i = 0; i < (Position)number_of_fields; i++) { if (f[i].hasPrefix("key:")) { keys[number_of_keys++] = (Index)i; continue; } if (f[i].hasPrefix("value:")) { // check whether a variable name was given String variable_name(f[i].after(":", 0)); if (variable_name.isEmpty()) { Log.error() << "ParameterSection::extractSection: error while reading section " << section_name << ": empty variable name: " << f[i] << endl; continue; } if (variable_names_.has(variable_name)) { Log.error() << "ParameterSection::extractSection: error while reading section " << section_name << ": duplicate variable name: " << f[i] << endl; continue; } // correct definition: store it. variable_names_[variable_name] = (Index)number_of_variables; variables[number_of_variables++] = (Index)i; } } if (number_of_keys == 0) { return false; } // format line looks ok // ====================================================================== // now extract all non-comment lines // true, if each line contains version information // indicated by a variable definition named "ver" bool check_version(variable_names_.has("ver")); // store for faster access number_of_variables_ = variable_names_.size(); // allocate space for all entries entries_.clear(); entries_.resize(number_of_lines * number_of_variables); // clear all former contest of the keys_ array keys_.clear(); section_entries_.clear(); number_of_lines = -1; // skip format line for (Position i = first_line; i <= last_line; i++) { line = *ini_file.getLine(i); line.trimLeft(); // if line is empty or is a comment line, nothing to be done if ((line.isEmpty()) || (line[0] == ';') || (line[0] == '!') || (line[0] == '#')) { continue; } // options are of the form "@option=value" if (line[0] == '@') { // remove the leading '@' line.erase(0, 1); // insert the option String option_key = line.before("="); String option_value = line.after("="); options.set(option_key, option_value); continue; } number_of_lines++; // skip format line if (number_of_lines == 0) { continue; } // now split the line... number_of_fields = line.splitQuoted(f,String::CHARACTER_CLASS__WHITESPACE, "\"'"); // assemble the keys String key; for (Size j = 0; j < number_of_keys; j++) { key.append(f[keys[j]]); if (j != number_of_keys - 1) { key.append(" "); } } // check whether we have already read this key if (check_version && section_entries_.has(key)) { // yes, we do - compare version numbers float old_version = entries_[section_entries_[key] * number_of_variables_ + variable_names_["ver"]].toFloat(); float new_version = f[variables[variable_names_["ver"]]].toFloat(); if (old_version > new_version) { // key is ignored because a newer version already exists continue; } if (old_version == new_version) { Log.warn() << "ParameterSection: repeated entry with same version number in line " << number_of_lines << " of section [" << section_name << "] " << endl << " in file " << ini_file.getFilename() << ": " << line << endl; continue; } } // no version checking // if this key is new, remember it! if (!section_entries_.has(key)) { // add the key to the array of keys keys_.push_back(key); // insert the key into the hash map section_entries_[key] = number_of_lines; } // copy all variable fields to the corresponding array for (Position j = 0; j < (Position)number_of_variables; j++) { if ((Position)variables[j] < f.size()) { entries_[number_of_lines * number_of_variables_ + j] = f[variables[j]]; } } } valid_ = true; return true; } bool ParameterSection::has(const String& key, const String& variable) const throw() { return section_entries_.has(key) && variable_names_.has(variable); } bool ParameterSection::has(const String& key) const throw() { return section_entries_.has(key); } const String& ParameterSection::getValue(const String& key, const String& variable) const throw() { // check whether the entry exists if (!section_entries_.has(key) || !variable_names_.has(variable)) { return UNDEFINED; } // return the value return entries_[section_entries_[key] * number_of_variables_ + variable_names_[variable]]; } const String& ParameterSection::getValue(Size key_index, Size variable_index) const throw() { // check whether the entry exists if ((key_index < keys_.size()) && (variable_index < number_of_variables_)) { // return the section entry corresponding to the key return entries_[(section_entries_[keys_[key_index]]) * number_of_variables_ + variable_index]; } return UNDEFINED; } const String& ParameterSection::getKey(Position key_index) const throw() { // check whether the entry exists if ((key_index >= section_entries_.size())) { return UNDEFINED; } // return the value return keys_[key_index]; } Size ParameterSection::getNumberOfKeys() const throw() { return keys_.size(); } Size ParameterSection::getNumberOfVariables() const throw() { return number_of_variables_; } bool ParameterSection::hasVariable(const String& variable) const throw() { return variable_names_.has(variable); } Position ParameterSection::getColumnIndex(const String& variable) const throw() { if (variable_names_.has(variable)) { return variable_names_[variable]; } return INVALID_POSITION; } const ParameterSection& ParameterSection::operator = (const ParameterSection& section) throw() { options = section.options; section_name_ = section.section_name_; format_line_ = section.format_line_; section_entries_ = section.section_entries_; variable_names_ = section.variable_names_; entries_ = section.entries_; keys_ = section.keys_; number_of_variables_ = section.number_of_variables_; version_ = section.version_; valid_ = section.valid_; return *this; } bool ParameterSection::isValid() const throw() { return valid_; } bool ParameterSection::operator == (const ParameterSection& parameter_section) const throw() { return ( (options == parameter_section.options) && (section_name_ == parameter_section.section_name_) && (format_line_ == parameter_section.format_line_) && (section_entries_ == parameter_section.section_entries_) && (variable_names_ == parameter_section.variable_names_) && (entries_ == parameter_section.entries_) && (keys_ == parameter_section.keys_) && (number_of_variables_ == parameter_section.number_of_variables_) && (version_ == parameter_section.version_) && (valid_ == parameter_section.valid_) ); } } // namespace BALL <commit_msg>adapted to changes in INIFile<commit_after>// $Id: parameterSection.C,v 1.17 2001/04/08 23:30:25 amoll Exp $ #include <BALL/FORMAT/parameterSection.h> #include <BALL/FORMAT/parameters.h> using namespace std; namespace BALL { const String ParameterSection::UNDEFINED = "(UNDEFINED)"; ParameterSection::ParameterSection() throw() : section_name_(""), format_line_(""), section_entries_(), variable_names_(), entries_(0), keys_(0), number_of_variables_(0), version_(0), valid_(false) { } ParameterSection::ParameterSection(const ParameterSection& parameter_section) throw() : section_name_(parameter_section.section_name_), format_line_(parameter_section.format_line_), section_entries_(parameter_section.section_entries_), variable_names_(parameter_section.variable_names_), entries_(parameter_section.entries_), keys_(parameter_section.keys_), number_of_variables_(parameter_section.number_of_variables_), version_(parameter_section.version_), valid_(parameter_section.valid_) { } ParameterSection::~ParameterSection() throw() { clear(); } void ParameterSection::clear() throw() { // clear the section name section_name_ = ""; format_line_ = ""; // destroy all hash maps section_entries_.clear(); variable_names_.clear(); // clear all allocated entries entries_.clear(); // clear all keys keys_.clear(); // delete the version array version_.clear(); // clear the number of entries/variables number_of_variables_ = 0; // tag this instance as invalid valid_ = false; } const String& ParameterSection::getSectionName() const throw() { return section_name_; } bool ParameterSection::extractSection(Parameters& parameters, const String& section_name) throw() { if (!parameters.isValid()) { return false; } // this instance is only valid if extractSection works valid_ = false; // store the section name section_name_ = section_name; INIFile& ini_file = parameters.getParameterFile(); // check for the existence of the required section if (!ini_file.hasSection(section_name)) { return false; } // if section has the length 0, we are finished if (ini_file.getSectionLength(section_name) == 0) { Log.info() << "ParameterSectionFile " << ini_file.getFilename() << " Section " << section_name << "isEmpty." << endl; return true; } // ================================================================ // loop over all lines and store the format line // skip all comment and options lines // count the number of non-comment lines // count non-comment lines only int number_of_lines = 0; String line; INIFile::LineIterator it = ini_file.getSectionFirstLine(section_name); for (; +it ; ++it) { // get the line and remove leading white spaces const INIFile::LineIterator& cit(it); String line(*cit); line.trimLeft(); // skip all empty lines, comments and option lines if (line.isEmpty() || (line[0] == ';') || (line[0] == '!') || (line[0] == '#') || (line[0] == '@')) { // comment lines start with "!" or ";" or "#" // option lines start with "@" continue; } // extract format line: the first non-comment/non-option line if (number_of_lines == 0) { format_line_ = line; } // count non-comment lines number_of_lines++; } // =========================================================================== // interpret the format line // f contains the fields resulting from a splitQuoted of the format line vector<String> f; Size number_of_fields = format_line_.split(f, String::CHARACTER_CLASS__WHITESPACE); if (number_of_fields == 0 || number_of_fields > 20) { Log.error() << "ParameterSection::extractSection: error reading section " << section_name << " of file " << ini_file.getFilename() << ": wrong number of fields in the format line: " << number_of_fields << endl; Log.error() << "FORMAT: " << format_line_ << endl; return false; } // Initialisations: // keys is an array containing the fields that will be assembled to the line key Index keys[ParameterSection::MAX_FIELDS]; Size number_of_keys = 0; // variables is an array containing the fields that represent variables Index variables[ParameterSection::MAX_FIELDS]; Size number_of_variables = 0; // clear the old contents of variable_names_ variable_names_.clear(); // check every field definition for (Position i = 0; i < (Position)number_of_fields; i++) { if (f[i].hasPrefix("key:")) { keys[number_of_keys++] = (Index)i; continue; } if (f[i].hasPrefix("value:")) { // check whether a variable name was given String variable_name(f[i].after(":", 0)); if (variable_name.isEmpty()) { Log.error() << "ParameterSection::extractSection: error while reading section " << section_name << ": empty variable name: " << f[i] << endl; continue; } if (variable_names_.has(variable_name)) { Log.error() << "ParameterSection::extractSection: error while reading section " << section_name << ": duplicate variable name: " << f[i] << endl; continue; } // correct definition: store it. variable_names_[variable_name] = (Index)number_of_variables; variables[number_of_variables++] = (Index)i; } } if (number_of_keys == 0) { return false; } // format line looks ok // ====================================================================== // now extract all non-comment lines // true, if each line contains version information // indicated by a variable definition named "ver" bool check_version(variable_names_.has("ver")); // store for faster access number_of_variables_ = variable_names_.size(); // allocate space for all entries entries_.clear(); entries_.resize(number_of_lines * number_of_variables); // clear all former contest of the keys_ array keys_.clear(); section_entries_.clear(); number_of_lines = -1; // skip format line it = ini_file.getSectionFirstLine(section_name); for (; +it ; ++it) { const INIFile::LineIterator& cit(it); line = *cit; line.trimLeft(); // if line is empty or is a comment line, nothing to be done if ((line.isEmpty()) || (line[0] == ';') || (line[0] == '!') || (line[0] == '#')) { continue; } // options are of the form "@option=value" if (line[0] == '@') { // remove the leading '@' line.erase(0, 1); // insert the option String option_key = line.before("="); String option_value = line.after("="); options.set(option_key, option_value); continue; } number_of_lines++; // skip format line if (number_of_lines == 0) { continue; } // now split the line... number_of_fields = line.splitQuoted(f,String::CHARACTER_CLASS__WHITESPACE, "\"'"); // assemble the keys String key; for (Size j = 0; j < number_of_keys; j++) { key.append(f[keys[j]]); if (j != number_of_keys - 1) { key.append(" "); } } // check whether we have already read this key if (check_version && section_entries_.has(key)) { // yes, we do - compare version numbers float old_version = entries_[section_entries_[key] * number_of_variables_ + variable_names_["ver"]].toFloat(); float new_version = f[variables[variable_names_["ver"]]].toFloat(); if (old_version > new_version) { // key is ignored because a newer version already exists continue; } if (old_version == new_version) { Log.warn() << "ParameterSection: repeated entry with same version number in line " << number_of_lines << " of section [" << section_name << "] " << endl << " in file " << ini_file.getFilename() << ": " << line << endl; continue; } } // no version checking // if this key is new, remember it! if (!section_entries_.has(key)) { // add the key to the array of keys keys_.push_back(key); // insert the key into the hash map section_entries_[key] = number_of_lines; } // copy all variable fields to the corresponding array for (Position j = 0; j < (Position)number_of_variables; j++) { if ((Position)variables[j] < f.size()) { entries_[number_of_lines * number_of_variables_ + j] = f[variables[j]]; } } } valid_ = true; return true; } bool ParameterSection::has(const String& key, const String& variable) const throw() { return section_entries_.has(key) && variable_names_.has(variable); } bool ParameterSection::has(const String& key) const throw() { return section_entries_.has(key); } const String& ParameterSection::getValue(const String& key, const String& variable) const throw() { // check whether the entry exists if (!section_entries_.has(key) || !variable_names_.has(variable)) { return UNDEFINED; } // return the value return entries_[section_entries_[key] * number_of_variables_ + variable_names_[variable]]; } const String& ParameterSection::getValue(Size key_index, Size variable_index) const throw() { // check whether the entry exists if ((key_index < keys_.size()) && (variable_index < number_of_variables_)) { // return the section entry corresponding to the key return entries_[(section_entries_[keys_[key_index]]) * number_of_variables_ + variable_index]; } return UNDEFINED; } const String& ParameterSection::getKey(Position key_index) const throw() { // check whether the entry exists if ((key_index >= section_entries_.size())) { return UNDEFINED; } // return the value return keys_[key_index]; } Size ParameterSection::getNumberOfKeys() const throw() { return keys_.size(); } Size ParameterSection::getNumberOfVariables() const throw() { return number_of_variables_; } bool ParameterSection::hasVariable(const String& variable) const throw() { return variable_names_.has(variable); } Position ParameterSection::getColumnIndex(const String& variable) const throw() { if (variable_names_.has(variable)) { return variable_names_[variable]; } return INVALID_POSITION; } const ParameterSection& ParameterSection::operator = (const ParameterSection& section) throw() { options = section.options; section_name_ = section.section_name_; format_line_ = section.format_line_; section_entries_ = section.section_entries_; variable_names_ = section.variable_names_; entries_ = section.entries_; keys_ = section.keys_; number_of_variables_ = section.number_of_variables_; version_ = section.version_; valid_ = section.valid_; return *this; } bool ParameterSection::isValid() const throw() { return valid_; } bool ParameterSection::operator == (const ParameterSection& parameter_section) const throw() { return ( (options == parameter_section.options) && (section_name_ == parameter_section.section_name_) && (format_line_ == parameter_section.format_line_) && (section_entries_ == parameter_section.section_entries_) && (variable_names_ == parameter_section.variable_names_) && (entries_ == parameter_section.entries_) && (keys_ == parameter_section.keys_) && (number_of_variables_ == parameter_section.number_of_variables_) && (version_ == parameter_section.version_) && (valid_ == parameter_section.valid_) ); } } // namespace BALL <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: handleinteractionrequest.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: sb $ $Date: 2001-07-13 12:48:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX #include "ucbhelper/handleinteractionrequest.hxx" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_ #include "com/sun/star/task/XInteractionAbort.hpp" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include "com/sun/star/task/XInteractionHandler.hpp" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_ #include "com/sun/star/task/XInteractionRetry.hpp" #endif #ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_ #include "com/sun/star/ucb/CommandFailedException.hpp" #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_ #include "com/sun/star/ucb/XCommandEnvironment.hpp" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include "com/sun/star/uno/RuntimeException.hpp" #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include "cppuhelper/exc_hlp.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include "osl/diagnose.h" #endif #ifndef _RTL_USTRING_HXX_ #include "rtl/ustring.hxx" #endif #ifndef _UCBHELPER_INTERACTIONREQUEST_HXX #include "ucbhelper/interactionrequest.hxx" #endif #ifndef _UCBHELPER_SIMPLEAUTHENTICATIONREQUEST_HXX #include "ucbhelper/simpleauthenticationrequest.hxx" #endif #ifndef _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX #include "ucbhelper/simpleinteractionrequest.hxx" #endif #ifndef INCLUDED_UTILITY #include <utility> #define INCLUDED_UTILITY #endif using namespace com::sun; namespace { void handle(star::uno::Reference< star::task::XInteractionRequest > const & rRequest, star::uno::Reference< star::ucb::XCommandEnvironment > const & rEnvironment) SAL_THROW((star::uno::Exception)) { OSL_ENSURE(rRequest.is(), "specification violation"); star::uno::Reference< star::task::XInteractionHandler > xHandler; if (rEnvironment.is()) xHandler = rEnvironment->getInteractionHandler(); if (!xHandler.is()) cppu::throwException(rRequest->getRequest()); xHandler->handle(rRequest.get()); } } namespace ucbhelper { sal_Int32 handleInteractionRequest( rtl::Reference< ucbhelper::SimpleInteractionRequest > const & rRequest, star::uno::Reference< star::ucb::XCommandEnvironment > const & rEnvironment, bool bThrowOnAbort) SAL_THROW((star::uno::Exception)) { handle(rRequest.get(), rEnvironment); sal_Int32 nResponse = rRequest->getResponse(); switch (nResponse) { case ucbhelper::CONTINUATION_UNKNOWN: cppu::throwException(rRequest->getRequest()); break; case ucbhelper::CONTINUATION_ABORT: if (bThrowOnAbort) throw star::ucb::CommandFailedException( rtl::OUString(), 0, rRequest->getRequest()); break; } return nResponse; } std::pair< sal_Int32, rtl::Reference< ucbhelper::InteractionSupplyAuthentication > > handleInteractionRequest( rtl::Reference< ucbhelper::SimpleAuthenticationRequest > const & rRequest, com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > const & rEnvironment, bool bThrowOnAbort) SAL_THROW((com::sun::star::uno::Exception)) { handle(rRequest.get(), rEnvironment); rtl::Reference< ucbhelper::InteractionContinuation > xContinuation(rRequest->getSelection()); if (star::uno::Reference< star::task::XInteractionAbort >( xContinuation.get(), star::uno::UNO_QUERY). is()) if (bThrowOnAbort) throw star::ucb::CommandFailedException( rtl::OUString(), 0, rRequest->getRequest()); else return std::make_pair( ucbhelper::CONTINUATION_ABORT, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >()); else if (star::uno::Reference< star::task::XInteractionRetry >( xContinuation.get(), star::uno::UNO_QUERY). is()) return std::make_pair( ucbhelper::CONTINUATION_ABORT, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >()); else return std::make_pair( ucbhelper::CONTINUATION_UNKNOWN, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >( rRequest->getAuthenticationSupplier())); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.1.170); FILE MERGED 2005/09/05 13:13:56 rt 1.1.170.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: handleinteractionrequest.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:37:59 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX #include "ucbhelper/handleinteractionrequest.hxx" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_ #include "com/sun/star/task/XInteractionAbort.hpp" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include "com/sun/star/task/XInteractionHandler.hpp" #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_ #include "com/sun/star/task/XInteractionRetry.hpp" #endif #ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_ #include "com/sun/star/ucb/CommandFailedException.hpp" #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_ #include "com/sun/star/ucb/XCommandEnvironment.hpp" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include "com/sun/star/uno/RuntimeException.hpp" #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include "cppuhelper/exc_hlp.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include "osl/diagnose.h" #endif #ifndef _RTL_USTRING_HXX_ #include "rtl/ustring.hxx" #endif #ifndef _UCBHELPER_INTERACTIONREQUEST_HXX #include "ucbhelper/interactionrequest.hxx" #endif #ifndef _UCBHELPER_SIMPLEAUTHENTICATIONREQUEST_HXX #include "ucbhelper/simpleauthenticationrequest.hxx" #endif #ifndef _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX #include "ucbhelper/simpleinteractionrequest.hxx" #endif #ifndef INCLUDED_UTILITY #include <utility> #define INCLUDED_UTILITY #endif using namespace com::sun; namespace { void handle(star::uno::Reference< star::task::XInteractionRequest > const & rRequest, star::uno::Reference< star::ucb::XCommandEnvironment > const & rEnvironment) SAL_THROW((star::uno::Exception)) { OSL_ENSURE(rRequest.is(), "specification violation"); star::uno::Reference< star::task::XInteractionHandler > xHandler; if (rEnvironment.is()) xHandler = rEnvironment->getInteractionHandler(); if (!xHandler.is()) cppu::throwException(rRequest->getRequest()); xHandler->handle(rRequest.get()); } } namespace ucbhelper { sal_Int32 handleInteractionRequest( rtl::Reference< ucbhelper::SimpleInteractionRequest > const & rRequest, star::uno::Reference< star::ucb::XCommandEnvironment > const & rEnvironment, bool bThrowOnAbort) SAL_THROW((star::uno::Exception)) { handle(rRequest.get(), rEnvironment); sal_Int32 nResponse = rRequest->getResponse(); switch (nResponse) { case ucbhelper::CONTINUATION_UNKNOWN: cppu::throwException(rRequest->getRequest()); break; case ucbhelper::CONTINUATION_ABORT: if (bThrowOnAbort) throw star::ucb::CommandFailedException( rtl::OUString(), 0, rRequest->getRequest()); break; } return nResponse; } std::pair< sal_Int32, rtl::Reference< ucbhelper::InteractionSupplyAuthentication > > handleInteractionRequest( rtl::Reference< ucbhelper::SimpleAuthenticationRequest > const & rRequest, com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > const & rEnvironment, bool bThrowOnAbort) SAL_THROW((com::sun::star::uno::Exception)) { handle(rRequest.get(), rEnvironment); rtl::Reference< ucbhelper::InteractionContinuation > xContinuation(rRequest->getSelection()); if (star::uno::Reference< star::task::XInteractionAbort >( xContinuation.get(), star::uno::UNO_QUERY). is()) if (bThrowOnAbort) throw star::ucb::CommandFailedException( rtl::OUString(), 0, rRequest->getRequest()); else return std::make_pair( ucbhelper::CONTINUATION_ABORT, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >()); else if (star::uno::Reference< star::task::XInteractionRetry >( xContinuation.get(), star::uno::UNO_QUERY). is()) return std::make_pair( ucbhelper::CONTINUATION_ABORT, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >()); else return std::make_pair( ucbhelper::CONTINUATION_UNKNOWN, rtl::Reference< ucbhelper::InteractionSupplyAuthentication >( rRequest->getAuthenticationSupplier())); } } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // 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 <https://www.gnu.org/licenses/>. // #include "client/ui/frame_qimage.h" #include <QPixmap> namespace client { namespace { constexpr int kBytesPerPixel = 4; } // namespace FrameQImage::FrameQImage(QImage&& img) : Frame(base::Size(img.size().width(), img.size().height()), base::PixelFormat::ARGB(), img.bytesPerLine(), img.bits(), nullptr), image_(std::move(img)) { // Nothing } // static std::unique_ptr<FrameQImage> FrameQImage::create(const base::Size& size) { if (size.isEmpty()) return nullptr; return std::unique_ptr<FrameQImage>( new FrameQImage(QImage(size.width(), size.height(), QImage::Format_RGB32))); } // static std::unique_ptr<FrameQImage> FrameQImage::create(const QPixmap& pixmap) { return std::unique_ptr<FrameQImage>(new FrameQImage(pixmap.toImage())); } // static std::unique_ptr<FrameQImage> FrameQImage::create(QImage&& image) { return std::unique_ptr<FrameQImage>(new FrameQImage(std::move(image))); } } // namespace client <commit_msg>Removed unused code.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // 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 <https://www.gnu.org/licenses/>. // #include "client/ui/frame_qimage.h" #include <QPixmap> namespace client { FrameQImage::FrameQImage(QImage&& img) : Frame(base::Size(img.size().width(), img.size().height()), base::PixelFormat::ARGB(), img.bytesPerLine(), img.bits(), nullptr), image_(std::move(img)) { // Nothing } // static std::unique_ptr<FrameQImage> FrameQImage::create(const base::Size& size) { if (size.isEmpty()) return nullptr; return std::unique_ptr<FrameQImage>( new FrameQImage(QImage(size.width(), size.height(), QImage::Format_RGB32))); } // static std::unique_ptr<FrameQImage> FrameQImage::create(const QPixmap& pixmap) { return std::unique_ptr<FrameQImage>(new FrameQImage(pixmap.toImage())); } // static std::unique_ptr<FrameQImage> FrameQImage::create(QImage&& image) { return std::unique_ptr<FrameQImage>(new FrameQImage(std::move(image))); } } // namespace client <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/socks5_stream.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { void socks5_stream::name_lookup(asio::error_code const& e, tcp::resolver::iterator i , boost::shared_ptr<handler_type> h) { if (e || i == tcp::resolver::iterator()) { (*h)(e); asio::error_code ec; close(ec); return; } m_sock.async_connect(i->endpoint(), boost::bind( &socks5_stream::connected, this, _1, h)); } void socks5_stream::connected(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; // send SOCKS5 authentication methods m_buffer.resize(m_user.empty()?3:4); char* p = &m_buffer[0]; write_uint8(5, p); // SOCKS VERSION 5 if (m_user.empty()) { write_uint8(1, p); // 1 authentication method (no auth) write_uint8(0, p); // no authentication } else { write_uint8(2, p); // 2 authentication methods write_uint8(0, p); // no authentication write_uint8(2, p); // username/password } asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake1, this, _1, h)); } void socks5_stream::handshake1(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(2); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake2, this, _1, h)); } void socks5_stream::handshake2(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; char* p = &m_buffer[0]; int version = read_uint8(p); int method = read_uint8(p); if (version < 5) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } if (method == 0) { socks_connect(h); } else if (method == 2) { if (m_user.empty()) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } // start sub-negotiation m_buffer.resize(m_user.size() + m_password.size() + 3); char* p = &m_buffer[0]; write_uint8(1, p); write_uint8(m_user.size(), p); write_string(m_user, p); write_uint8(m_password.size(), p); write_string(m_password, p); asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake3, this, _1, h)); } else { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } } void socks5_stream::handshake3(asio::error_code const& e , boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(2); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake4, this, _1, h)); } void socks5_stream::handshake4(asio::error_code const& e , boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; char* p = &m_buffer[0]; int version = read_uint8(p); int status = read_uint8(p); if (version != 1) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } if (status != 0) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } std::vector<char>().swap(m_buffer); (*h)(e); } void socks5_stream::socks_connect(boost::shared_ptr<handler_type> h) { using namespace libtorrent::detail; // send SOCKS5 connect command m_buffer.resize(6 + (m_remote_endpoint.address().is_v4()?4:16)); char* p = &m_buffer[0]; write_uint8(5, p); // SOCKS VERSION 5 write_uint8(1, p); // CONNECT command write_uint8(0, p); // reserved write_uint8(m_remote_endpoint.address().is_v4()?1:4, p); // address type write_address(m_remote_endpoint.address(), p); write_uint16(m_remote_endpoint.port(), p); TORRENT_ASSERT(p - &m_buffer[0] == int(m_buffer.size())); asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect1, this, _1, h)); } void socks5_stream::connect1(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(6 + 4); // assume an IPv4 address asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect2, this, _1, h)); } void socks5_stream::connect2(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; // send SOCKS5 connect command char* p = &m_buffer[0]; int version = read_uint8(p); if (version < 5) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } int response = read_uint8(p); if (response != 0) { asio::error_code e = asio::error::fault; switch (response) { case 1: e = asio::error::fault; break; case 2: e = asio::error::no_permission; break; case 3: e = asio::error::network_unreachable; break; case 4: e = asio::error::host_unreachable; break; case 5: e = asio::error::connection_refused; break; case 6: e = asio::error::timed_out; break; case 7: e = asio::error::operation_not_supported; break; case 8: e = asio::error::address_family_not_supported; break; } (*h)(e); asio::error_code ec; close(ec); return; } p += 1; // reserved int atyp = read_uint8(p); // we ignore the proxy IP it was bound to if (atyp == 1) { std::vector<char>().swap(m_buffer); (*h)(e); return; } int skip_bytes = 0; if (atyp == 4) { skip_bytes = 12; } else if (atyp == 3) { skip_bytes = read_uint8(p) - 3; } else { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } m_buffer.resize(skip_bytes); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect3, this, _1, h)); } void socks5_stream::connect3(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } std::vector<char>().swap(m_buffer); (*h)(e); } } <commit_msg>fixed bug in socks5 implementation when using user/pass authentication<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/socks5_stream.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { void socks5_stream::name_lookup(asio::error_code const& e, tcp::resolver::iterator i , boost::shared_ptr<handler_type> h) { if (e || i == tcp::resolver::iterator()) { (*h)(e); asio::error_code ec; close(ec); return; } m_sock.async_connect(i->endpoint(), boost::bind( &socks5_stream::connected, this, _1, h)); } void socks5_stream::connected(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; // send SOCKS5 authentication methods m_buffer.resize(m_user.empty()?3:4); char* p = &m_buffer[0]; write_uint8(5, p); // SOCKS VERSION 5 if (m_user.empty()) { write_uint8(1, p); // 1 authentication method (no auth) write_uint8(0, p); // no authentication } else { write_uint8(2, p); // 2 authentication methods write_uint8(0, p); // no authentication write_uint8(2, p); // username/password } asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake1, this, _1, h)); } void socks5_stream::handshake1(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(2); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake2, this, _1, h)); } void socks5_stream::handshake2(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; char* p = &m_buffer[0]; int version = read_uint8(p); int method = read_uint8(p); if (version < 5) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } if (method == 0) { socks_connect(h); } else if (method == 2) { if (m_user.empty()) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } // start sub-negotiation m_buffer.resize(m_user.size() + m_password.size() + 3); char* p = &m_buffer[0]; write_uint8(1, p); write_uint8(m_user.size(), p); write_string(m_user, p); write_uint8(m_password.size(), p); write_string(m_password, p); asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake3, this, _1, h)); } else { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } } void socks5_stream::handshake3(asio::error_code const& e , boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(2); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::handshake4, this, _1, h)); } void socks5_stream::handshake4(asio::error_code const& e , boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; char* p = &m_buffer[0]; int version = read_uint8(p); int status = read_uint8(p); if (version != 1) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } if (status != 0) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } std::vector<char>().swap(m_buffer); socks_connect(h); } void socks5_stream::socks_connect(boost::shared_ptr<handler_type> h) { using namespace libtorrent::detail; // send SOCKS5 connect command m_buffer.resize(6 + (m_remote_endpoint.address().is_v4()?4:16)); char* p = &m_buffer[0]; write_uint8(5, p); // SOCKS VERSION 5 write_uint8(1, p); // CONNECT command write_uint8(0, p); // reserved write_uint8(m_remote_endpoint.address().is_v4()?1:4, p); // address type write_address(m_remote_endpoint.address(), p); write_uint16(m_remote_endpoint.port(), p); TORRENT_ASSERT(p - &m_buffer[0] == int(m_buffer.size())); asio::async_write(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect1, this, _1, h)); } void socks5_stream::connect1(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } m_buffer.resize(6 + 4); // assume an IPv4 address asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect2, this, _1, h)); } void socks5_stream::connect2(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } using namespace libtorrent::detail; // send SOCKS5 connect command char* p = &m_buffer[0]; int version = read_uint8(p); if (version < 5) { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } int response = read_uint8(p); if (response != 0) { asio::error_code e = asio::error::fault; switch (response) { case 1: e = asio::error::fault; break; case 2: e = asio::error::no_permission; break; case 3: e = asio::error::network_unreachable; break; case 4: e = asio::error::host_unreachable; break; case 5: e = asio::error::connection_refused; break; case 6: e = asio::error::timed_out; break; case 7: e = asio::error::operation_not_supported; break; case 8: e = asio::error::address_family_not_supported; break; } (*h)(e); asio::error_code ec; close(ec); return; } p += 1; // reserved int atyp = read_uint8(p); // we ignore the proxy IP it was bound to if (atyp == 1) { std::vector<char>().swap(m_buffer); (*h)(e); return; } int skip_bytes = 0; if (atyp == 4) { skip_bytes = 12; } else if (atyp == 3) { skip_bytes = read_uint8(p) - 3; } else { (*h)(asio::error::operation_not_supported); asio::error_code ec; close(ec); return; } m_buffer.resize(skip_bytes); asio::async_read(m_sock, asio::buffer(m_buffer) , boost::bind(&socks5_stream::connect3, this, _1, h)); } void socks5_stream::connect3(asio::error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); asio::error_code ec; close(ec); return; } std::vector<char>().swap(m_buffer); (*h)(e); } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QDebug> #include "akonadi.h" #include "akonadiconnection.h" #include "storagebackend.h" #include "storage/datastore.h" #include "storage/entity.h" #include "create.h" #include "response.h" using namespace Akonadi; Create::Create(): Handler() { } Create::~Create() { } bool Create::handleLine(const QByteArray& line ) { // parse out the reference name and mailbox name const int startOfCommand = line.indexOf( ' ' ) + 1; const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1; QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) ); // strip off a trailing '/' if ( !mailbox.isEmpty() && mailbox[0] == '/' ) mailbox = mailbox.right( mailbox.size() - 1 ); // Responses: // OK - create completed // NO - create failure: can't create mailbox with that name // BAD - command unknown or arguments invalid Response response; response.setTag( tag() ); response.setSuccess(); response.setString( "Completed" ); emit responseAvailable( response ); deleteLater(); return true; if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) { response.setError(); response.setString( "Invalid argument" ); emit responseAvailable( response ); deleteLater(); return true; } DataStore *db = connection()->storageBackend(); const int startOfLocation = mailbox.indexOf( '/' ); const QByteArray resourceName = mailbox.left( startOfLocation ); const QByteArray locationName = mailbox.mid( startOfLocation ); //qDebug() << "Create: " << locationName // << " in resource: " << resourceName; Resource resource = db->getResourceByName( resourceName ); // first check whether location already exists if ( db->getLocationByName( resource, locationName ).isValid() ) { response.setFailure(); response.setString( "A folder with that name does already exist"); emit responseAvailable( response ); deleteLater(); return true; } // we have to create all superior hierarchical folders, so look for the // starting point QList<QByteArray> foldersToCreate; foldersToCreate.append( locationName ); for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 ); endOfSupFolder > 0; endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) { // check whether the superior hierarchical folder exists if ( ! db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) { // the superior folder does not exist, so it has to be created foldersToCreate.prepend( locationName.left( endOfSupFolder ) ); } else { // the superior folder exists, so we can stop here break; } } // now we try to create all necessary folders // first check whether the existing superior folder can contain subfolders const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' ); if ( endOfSupFolder > 0 ) { bool canContainSubfolders = false; const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() ); foreach ( MimeType m, mimeTypes ) { if ( m.getMimeType().toLower() == "directory/inode" ) { canContainSubfolders = true; break; } } if ( !canContainSubfolders ) { response.setFailure(); response.setString( "Superior folder cannot contain subfolders" ); emit responseAvailable( response ); deleteLater(); return true; } } // everything looks good, now we create the folders foreach ( QByteArray folderName, foldersToCreate ) { int locationId = 0; db->appendLocation( folderName, resource, &locationId ); db->appendMimeTypeForLocation( locationId, "directory/inode" ); // FIXME add more MIME types } response.setSuccess(); response.setString( "Completed" ); emit responseAvailable( response ); deleteLater(); return true; } <commit_msg>Remove dummy shortcut.<commit_after>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <QDebug> #include "akonadi.h" #include "akonadiconnection.h" #include "storagebackend.h" #include "storage/datastore.h" #include "storage/entity.h" #include "create.h" #include "response.h" using namespace Akonadi; Create::Create(): Handler() { } Create::~Create() { } bool Create::handleLine(const QByteArray& line ) { // parse out the reference name and mailbox name const int startOfCommand = line.indexOf( ' ' ) + 1; const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1; QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) ); // strip off a trailing '/' if ( !mailbox.isEmpty() && mailbox[0] == '/' ) mailbox = mailbox.right( mailbox.size() - 1 ); // Responses: // OK - create completed // NO - create failure: can't create mailbox with that name // BAD - command unknown or arguments invalid Response response; response.setTag( tag() ); if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) { response.setError(); response.setString( "Invalid argument" ); emit responseAvailable( response ); deleteLater(); return true; } DataStore *db = connection()->storageBackend(); const int startOfLocation = mailbox.indexOf( '/' ); const QByteArray resourceName = mailbox.left( startOfLocation ); const QByteArray locationName = mailbox.mid( startOfLocation ); //qDebug() << "Create: " << locationName // << " in resource: " << resourceName; Resource resource = db->getResourceByName( resourceName ); // first check whether location already exists if ( db->getLocationByName( resource, locationName ).isValid() ) { response.setFailure(); response.setString( "A folder with that name does already exist"); emit responseAvailable( response ); deleteLater(); return true; } // we have to create all superior hierarchical folders, so look for the // starting point QList<QByteArray> foldersToCreate; foldersToCreate.append( locationName ); for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 ); endOfSupFolder > 0; endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) { // check whether the superior hierarchical folder exists if ( ! db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) { // the superior folder does not exist, so it has to be created foldersToCreate.prepend( locationName.left( endOfSupFolder ) ); } else { // the superior folder exists, so we can stop here break; } } // now we try to create all necessary folders // first check whether the existing superior folder can contain subfolders const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' ); if ( endOfSupFolder > 0 ) { bool canContainSubfolders = false; const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() ); foreach ( MimeType m, mimeTypes ) { if ( m.getMimeType().toLower() == "directory/inode" ) { canContainSubfolders = true; break; } } if ( !canContainSubfolders ) { response.setFailure(); response.setString( "Superior folder cannot contain subfolders" ); emit responseAvailable( response ); deleteLater(); return true; } } // everything looks good, now we create the folders foreach ( QByteArray folderName, foldersToCreate ) { int locationId = 0; db->appendLocation( folderName, resource, &locationId ); db->appendMimeTypeForLocation( locationId, "directory/inode" ); // FIXME add more MIME types } response.setSuccess(); response.setString( "Completed" ); emit responseAvailable( response ); deleteLater(); return true; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include "balancer.hpp" static void print_stats(int); #define STATS_PERIOD 5s static Balancer* balancer = nullptr; #define NET_INCOMING 1 #define NET_OUTGOING 2 void Service::start() { auto& inc = net::Super_stack::get<net::IP4>(NET_INCOMING); auto& out = net::Super_stack::get<net::IP4>(NET_OUTGOING); out.tcp().set_MSL(15s); balancer = new Balancer(inc, 80, out); Timers::periodic(1s, STATS_PERIOD, print_stats); } /// statistics /// #include <timers> #include <ctime> using namespace std::chrono; static std::string now() { auto tnow = time(0); auto* curtime = localtime(&tnow); char buff[48]; int len = strftime(buff, sizeof(buff), "%c", curtime); return std::string(buff, len); } static void print_heap_info() { static intptr_t last = 0; // show information on heap status, to discover leaks etc. auto heap_begin = OS::heap_begin(); auto heap_end = OS::heap_end(); auto heap_usage = OS::heap_usage(); intptr_t heap_size = heap_end - heap_begin; auto diff = heap_size - last; printf("Heap size %lu Kb diff %ld (%ld Kb) usage %lu kB\n", heap_size / 1024, diff, diff / 1024, heap_usage / 1024); last = (int32_t) heap_size; } template <int N, typename T> struct rolling_avg { std::deque<T> values; void push(T value) { if (values.size() >= N) values.pop_front(); values.push_back(value); } double avg() const { double ps = 0.0; if (values.empty()) return ps; for (auto v : values) ps += v; return ps / values.size(); } }; void print_stats(int) { static int64_t last = 0; const auto& nodes = balancer->nodes; auto totals = nodes.total_sessions(); int growth = totals - last; last = totals; printf("*** [%s] ***\n", now().c_str()); printf("Total %ld (%+d) Sess %d Wait %d TO %d - Pool %d C.Att %d Err %d\n", totals, growth, nodes.open_sessions(), balancer->wait_queue(), nodes.timed_out_sessions(), nodes.pool_size(), nodes.pool_connecting(), balancer->connect_throws()); // node information int n = 0; for (auto& node : nodes) { printf("[%s %s P=%d C=%d] ", node.address().to_string().c_str(), (node.is_active() ? "ONL" : "OFF"), node.pool_size(), node.connection_attempts()); if (++n == 2) { n = 0; printf("\n"); } } if (n > 0) printf("\n"); // heap statistics print_heap_info(); } <commit_msg>Enable stack sampling and CPU usage metering<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <profile> #include "balancer.hpp" static void print_stats(int); #define STATS_PERIOD 5s static Balancer* balancer = nullptr; #define NET_INCOMING 1 #define NET_OUTGOING 2 void Service::start() {} void Service::ready() { auto& inc = net::Super_stack::get<net::IP4>(NET_INCOMING); auto& out = net::Super_stack::get<net::IP4>(NET_OUTGOING); out.tcp().set_MSL(15s); balancer = new Balancer(inc, 80, out); Timers::periodic(1s, STATS_PERIOD, print_stats); StackSampler::begin(); StackSampler::set_mode(StackSampler::MODE_CURRENT); } /// statistics /// #include <timers> #include <ctime> using namespace std::chrono; static std::string now() { auto tnow = time(0); auto* curtime = localtime(&tnow); char buff[48]; int len = strftime(buff, sizeof(buff), "%c", curtime); return std::string(buff, len); } static void print_heap_info() { static intptr_t last = 0; // show information on heap status, to discover leaks etc. auto heap_begin = OS::heap_begin(); auto heap_end = OS::heap_end(); auto heap_usage = OS::heap_usage(); intptr_t heap_size = heap_end - heap_begin; auto diff = heap_size - last; printf("Heap size %lu Kb diff %ld (%ld Kb) usage %lu kB\n", heap_size / 1024, diff, diff / 1024, heap_usage / 1024); last = (int32_t) heap_size; } template <int N, typename T> struct rolling_avg { std::deque<T> values; void push(T value) { if (values.size() >= N) values.pop_front(); values.push_back(value); } double avg() const { double ps = 0.0; if (values.empty()) return ps; for (auto v : values) ps += v; return ps / values.size(); } }; void print_stats(int) { static int64_t last = 0; const auto& nodes = balancer->nodes; auto totals = nodes.total_sessions(); int growth = totals - last; last = totals; printf("*** [%s] ***\n", now().c_str()); printf("Total %ld (%+d) Sess %d Wait %d TO %d - Pool %d C.Att %d Err %d\n", totals, growth, nodes.open_sessions(), balancer->wait_queue(), nodes.timed_out_sessions(), nodes.pool_size(), nodes.pool_connecting(), balancer->connect_throws()); // node information int n = 0; for (auto& node : nodes) { printf("[%s %s P=%d C=%d] ", node.address().to_string().c_str(), (node.is_active() ? "ONL" : "OFF"), node.pool_size(), node.connection_attempts()); if (++n == 2) { n = 0; printf("\n"); } } if (n > 0) printf("\n"); // CPU-usage statistics static uint64_t last_total = 0, last_asleep = 0; uint64_t tdiff = StackSampler::samples_total() - last_total; last_total = StackSampler::samples_total(); uint64_t adiff = StackSampler::samples_asleep() - last_asleep; last_asleep = StackSampler::samples_asleep(); double asleep = adiff / (double) tdiff; static rolling_avg<5, double> asleep_avg; asleep_avg.push(asleep); printf("CPU usage: %.2f%% Idle: %.2f%% Avg. usage: %.2f%% Idle: %.2f%%\n", (1.0 - asleep) * 100.0, asleep * 100.0, (1.0 - asleep_avg.avg()) * 100.0, asleep_avg.avg() * 100.0); // heap statistics print_heap_info(); // stack sampling StackSampler::print(3); } <|endoftext|>
<commit_before>/* * RandomSplitterTest.cpp * Tests RandomSplitter * Copyright 2017 Wojciech Wilgierz 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 <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include "Spectre.libClassifier/RandomSplitter.h" #include "Spectre.libGenetic/DataTypes.h" namespace { using namespace ::testing; using namespace Spectre::libClassifier; TEST(RandomSplitterInitializationTest, correct_dataset_opencv_initialization) { EXPECT_NO_THROW(RandomSplitter(0.7)); } class RandomSplitterTest : public ::testing::Test { public: RandomSplitterTest() :dataset(data, labels), randomSplitter(training, seed) {} protected: const Spectre::libGenetic::Seed seed = 1; const double training = 0.7; const std::vector<DataType> data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.9f, 0.8f }; // @gmrukwa: We're assuming labels are unique in tests below const std::vector<Label> labels{ 3, 7, 14, 2, 12, 5, 8, 4, 19, 11 }; const OpenCvDataset dataset; RandomSplitter randomSplitter; void SetUp() override { randomSplitter = RandomSplitter(training, seed); } }; TEST_F(RandomSplitterTest, split_dataset) { const auto result = randomSplitter.split(dataset); EXPECT_EQ(result.trainingSet.size() + result.testSet.size(), labels.size()); } TEST_F(RandomSplitterTest, check_size_of_splitted_vectors) { const auto result = randomSplitter.split(dataset); EXPECT_EQ(result.trainingSet.size(), data.size()*training); EXPECT_EQ(result.testSet.size(), data.size()- data.size()*training); } TEST_F(RandomSplitterTest, splits_differently_for_different_seeds) { randomSplitter = RandomSplitter(training, seed); const auto first = randomSplitter.split(dataset); randomSplitter = RandomSplitter(training, seed + 1); const auto second = randomSplitter.split(dataset); for (auto i = 0u; i < first.trainingSet.size(); ++i) { if(first.trainingSet.GetSampleMetadata(i) != second.trainingSet.GetSampleMetadata(i)) { SUCCEED(); } } FAIL() << "Outputs for different seeds are exactly the same."; } } <commit_msg>Introduce consistence test for splitter<commit_after>/* * RandomSplitterTest.cpp * Tests RandomSplitter * Copyright 2017 Wojciech Wilgierz 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 <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include "Spectre.libClassifier/RandomSplitter.h" #include "Spectre.libGenetic/DataTypes.h" namespace { using namespace ::testing; using namespace Spectre::libClassifier; TEST(RandomSplitterInitializationTest, correct_dataset_opencv_initialization) { EXPECT_NO_THROW(RandomSplitter(0.7)); } class RandomSplitterTest : public ::testing::Test { public: RandomSplitterTest() :dataset(data, labels), randomSplitter(training, seed) {} protected: const Spectre::libGenetic::Seed seed = 1; const double training = 0.7; const std::vector<DataType> data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.9f, 0.8f }; // @gmrukwa: We're assuming labels are unique in tests below const std::vector<Label> labels{ 3, 7, 14, 2, 12, 5, 8, 4, 19, 11 }; const OpenCvDataset dataset; RandomSplitter randomSplitter; void SetUp() override { randomSplitter = RandomSplitter(training, seed); } }; TEST_F(RandomSplitterTest, split_dataset) { const auto result = randomSplitter.split(dataset); EXPECT_EQ(result.trainingSet.size() + result.testSet.size(), labels.size()); } TEST_F(RandomSplitterTest, check_size_of_splitted_vectors) { const auto result = randomSplitter.split(dataset); EXPECT_EQ(result.trainingSet.size(), data.size()*training); EXPECT_EQ(result.testSet.size(), data.size()- data.size()*training); } TEST_F(RandomSplitterTest, splits_differently_for_different_seeds) { randomSplitter = RandomSplitter(training, seed); const auto first = randomSplitter.split(dataset); randomSplitter = RandomSplitter(training, seed + 1); const auto second = randomSplitter.split(dataset); for (auto i = 0u; i < first.trainingSet.size(); ++i) { if(first.trainingSet.GetSampleMetadata(i) != second.trainingSet.GetSampleMetadata(i)) { SUCCEED(); } } FAIL() << "Outputs for different seeds are exactly the same."; } TEST_F(RandomSplitterTest, splits_consistently_for_the_same_seed) { randomSplitter = RandomSplitter(training, seed); const auto first = randomSplitter.split(dataset); randomSplitter = RandomSplitter(training, seed); const auto second = randomSplitter.split(dataset); for (auto i = 0u; i < first.trainingSet.size(); ++i) { if (first.trainingSet.GetSampleMetadata(i) != second.trainingSet.GetSampleMetadata(i)) { FAIL() << "Outputs for the same seeds differ."; } } } } <|endoftext|>
<commit_before><commit_msg>support bypassing frame-ancestors CSP in Node frame<commit_after><|endoftext|>
<commit_before><commit_msg>Use base::WindowImpl instead of CWindowImpl to remove a dependency on ATL.<commit_after><|endoftext|>
<commit_before>// Copyright 2013 Mirus Project // 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 <term/terminal_.hpp> namespace mirus { namespace io { // terminal sizes const size_t VGA_WIDTH = 80; const size_t VGA_HEIGHT = 24; // term info size_t terminal_row; size_t terminal_column; uint8_t _terminal_color; uint16_t* terminal_buffer; void terminal::putentry(char c, terminal_color color, size_t x, size_t y) { const size_t index = y * VGA_WIDTH + x; terminal_buffer[index] = terminal::make_vga_entry(c, color); } void terminal::putchar(char c) { if (c == '\r') { terminal_row++; terminal_color = 0; } else if (c == '\b') { terminal_color--; terminal::putentry(' ', _terminal_color, terminal_column, terminal_row); } else { terminal::putentry(c, _terminal_color, terminal_column, terminal_row); } terminal::move_cursor(); } void terminal::putchar(char c, terminal_color color) { terminal_color oldcolor = _terminal_color; terminal::set_color(color); terminal::putchar(c); terminal::set_color(oldcolor); } void terminal::writestring(const char* data) { size_t datalen = strlen(data); for (size_t i = 0; i < datalen; i++) { // TODO: do we really need this? // if (data[i] == '\r') // { // terminal_row++; // terminal_column = 0; // } // else if (data[i] == '\b') // { // terminal_column--; // terminal::putentry(' ', _terminal_color, terminal_column, terminal_row); // } // else // { // terminal::putchar(data[i]); // } terminal::putchar(data[i]); } } void terminal::writestring(const char* data, terminal_color color) { terminal::putchar(data[i], color); } void terminal::clear() { for (int i = 0; i < 80 * 25; i++) { terminal_buffer[i] = 0; } // Move the hardware cursor back to the start. terminal_row = 0; terminal_column = 0; terminal::move_cursor(); } void terminal::clear(terminal_color color) { for (int i = 0; i < 80 * 25; i++) { terminal::putchar(' ', color); } // Move the hardware cursor back to the start. terminal_row = 0; terminal_column = 0; terminal::move_cursor(); } void terminal::scroll() { } void terminal::move_cursor() { unsigned temp; // Index = [(y * width) + x] temp = terminal_row * 80 + terminal_column; mirus::outb(0x3D4, 14); mirus::outb(0x3D5, temp >> 8); mirus::outb(0x3D4, 15); mirus::outb(0x3D5, temp); } terminal_color terminal::make_color(vga_color fg, vga_color bg) { return fg | bg << 4; } uint16_t terminal::make_vga_entry(char c, terminal_color color) { uint16_t c16 = c; uint16_t color16 = color; return c16 | color16 << 8; } terminal_color terminal::set_color(terminal_color color) { _terminal_color = color; } void terminal::initilize() { terminal_row = 0; terminal_column = 0; _terminal_color = terminal::make_color(COLOR_WHITE, COLOR_BLACK); terminal_buffer = static_cast<uint16_t*>0xb8000; terminal::clear(); } } }<commit_msg>fixed a few errors...<commit_after>// Copyright 2013 Mirus Project // 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 <term/terminal_.hpp> namespace mirus { namespace io { // terminal sizes const size_t VGA_WIDTH = 80; const size_t VGA_HEIGHT = 24; // term info size_t terminal_row; size_t terminal_column; uint8_t _terminal_color; uint16_t* terminal_buffer; void terminal::putentry(char c, terminal_color color, size_t x, size_t y) { const size_t index = y * VGA_WIDTH + x; terminal_buffer[index] = terminal::make_vga_entry(c, color); } void terminal::putchar(char c) { if (c == '\r') { terminal_row++; _terminal_color = 0; } else if (c == '\b') { _terminal_color--; terminal::putentry(' ', _terminal_color, terminal_column, terminal_row); } else { terminal::putentry(c, _terminal_color, terminal_column, terminal_row); } terminal::move_cursor(); } void terminal::putchar(char c, terminal_color color) { terminal_color oldcolor = _terminal_color; terminal::set_color(color); terminal::putchar(c); terminal::set_color(oldcolor); } void terminal::writestring(const char* data) { size_t datalen = strlen(data); for (size_t i = 0; i < datalen; i++) { // TODO: do we really need this? // if (data[i] == '\r') // { // terminal_row++; // terminal_column = 0; // } // else if (data[i] == '\b') // { // terminal_column--; // terminal::putentry(' ', _terminal_color, terminal_column, terminal_row); // } // else // { // terminal::putchar(data[i]); // } terminal::putchar(data[i]); } } void terminal::writestring(const char* data, terminal_color color) { terminal::putchar(data, color); } void terminal::clear() { for (int i = 0; i < 80 * 25; i++) { terminal_buffer[i] = 0; } // Move the hardware cursor back to the start. terminal_row = 0; terminal_column = 0; terminal::move_cursor(); } void terminal::clear(terminal_color color) { for (int i = 0; i < 80 * 25; i++) { terminal::putchar(' ', color); } // Move the hardware cursor back to the start. terminal_row = 0; terminal_column = 0; terminal::move_cursor(); } void terminal::scroll() { } void terminal::move_cursor() { unsigned temp; // Index = [(y * width) + x] temp = terminal_row * 80 + terminal_column; mirus::outb(0x3D4, 14); mirus::outb(0x3D5, temp >> 8); mirus::outb(0x3D4, 15); mirus::outb(0x3D5, temp); } terminal_color terminal::make_color(vga_color fg, vga_color bg) { return fg | bg << 4; } uint16_t terminal::make_vga_entry(char c, terminal_color color) { uint16_t c16 = c; uint16_t color16 = color; return c16 | color16 << 8; } terminal_color terminal::set_color(terminal_color color) { _terminal_color = color; } void terminal::initilize() { terminal_row = 0; terminal_column = 0; _terminal_color = terminal::make_color(COLOR_WHITE, COLOR_BLACK); terminal_buffer = static_cast<uint16_t*>0xb8000; terminal::clear(); } } } <|endoftext|>
<commit_before><commit_msg>trying to make this fit in gcc-4.6s little brain<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkInterpolateTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkImage.h" #include "itkIndex.h" #include "itkSize.h" #include "itkLinearInterpolateFunction.h" typedef itk::Index<3> IndexType; typedef itk::Size<3> SizeType; typedef itk::Image<unsigned short, 3> ImageType; typedef itk::LinearInterpolateFunction<ImageType> InterpolatorType; int main( int argc, char *argv[]) { int flag = 0; /* Did this test program work? */ std::cerr << "Testing image interpolation methods:\n"; /* Define the image size and physical coordinates */ SizeType size = {{20, 40, 80}}; double origin [3] = { 0.5, 0.5, 0.5}; double spacing[3] = { 0.1, 0.05 , 0.025}; /* Allocate a simple test image */ ImageType::Pointer image = ImageType::New(); ImageType::RegionType region; region.SetSize(size); image->SetLargestPossibleRegion(region); image->SetBufferedRegion(region); image->Allocate(); /* Set origin and spacing of physical coordinates */ image->SetOrigin(origin); image->SetSpacing(spacing); /* Initialize the image contents */ IndexType index; for (int slice = 0; slice < 80; slice++) { index[2] = slice; for (int row = 0; row < 40; row++) { index[1] = row; for (int col = 0; col < 20; col++) { index[0] = col; image->SetPixel(index, slice+row+col); } } } /* Create and initialize the interpolator */ InterpolatorType::Pointer interp = InterpolatorType::New(); interp->SetInputImage(image); /* Test evaluation at integer coordinates */ std::cerr << "Evaluate at integer coordinates: "; IndexType idx = {{10, 20,40}}; double value1 = interp->Evaluate(idx); std::cerr << value1 << std::endl; if (value1 != 70) { std::cerr << "*** Error: correct value is 70" << std::endl; flag = 1; } /* Test evaluation at non-integer coordinates */ std::cerr << "Evaluate at non-integer coordinates: "; double point[3] = {5.25, 12.5, 42.0}; double value2 = interp->Evaluate(point); std::cerr << value2 << std::endl; if (value2 != 59.75) { std::cerr << "*** Error: correct value is 59.75" << std::endl; flag = 1; } /* Return results of test */ if (flag != 0) { std::cerr << "*** Some test failed" << std::endl; return flag; } else { std::cerr << "All tests successfully passed" << std::endl; return 0; } } <commit_msg>ENH: Modified to sent testing results to stdout rather than stderr; this prevents the test driver from incorrectly deciding that the test failed.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkInterpolateTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkImage.h" #include "itkIndex.h" #include "itkSize.h" #include "itkLinearInterpolateFunction.h" typedef itk::Index<3> IndexType; typedef itk::Size<3> SizeType; typedef itk::Image<unsigned short, 3> ImageType; typedef itk::LinearInterpolateFunction<ImageType> InterpolatorType; int main( int argc, char *argv[]) { int flag = 0; /* Did this test program work? */ std::cout << "Testing image interpolation methods:\n"; /* Define the image size and physical coordinates */ SizeType size = {{20, 40, 80}}; double origin [3] = { 0.5, 0.5, 0.5}; double spacing[3] = { 0.1, 0.05 , 0.025}; /* Allocate a simple test image */ ImageType::Pointer image = ImageType::New(); ImageType::RegionType region; region.SetSize(size); image->SetLargestPossibleRegion(region); image->SetBufferedRegion(region); image->Allocate(); /* Set origin and spacing of physical coordinates */ image->SetOrigin(origin); image->SetSpacing(spacing); /* Initialize the image contents */ IndexType index; for (int slice = 0; slice < 80; slice++) { index[2] = slice; for (int row = 0; row < 40; row++) { index[1] = row; for (int col = 0; col < 20; col++) { index[0] = col; image->SetPixel(index, slice+row+col); } } } /* Create and initialize the interpolator */ InterpolatorType::Pointer interp = InterpolatorType::New(); interp->SetInputImage(image); // FIXME: Add trial evaluations near the border and outside the image /* Test evaluation at integer coordinates */ std::cout << "Evaluate at integer coordinates: "; IndexType idx = {{10, 20,40}}; double value1 = interp->Evaluate(idx); std::cout << value1 << std::endl; if (value1 != 70) { std::cout << "*** Error: correct value is 70" << std::endl; flag = 1; } /* Test evaluation at non-integer coordinates */ std::cout << "Evaluate at non-integer coordinates: "; double point[3] = {5.25, 12.5, 42.0}; double value2 = interp->Evaluate(point); std::cout << value2 << std::endl; if (value2 != 59.75) { std::cout << "*** Error: correct value is 59.75" << std::endl; flag = 1; } /* Return results of test */ if (flag != 0) { std::cout << "*** Some test failed" << std::endl; return flag; } else { std::cout << "All tests successfully passed" << std::endl; return 0; } } <|endoftext|>
<commit_before>#include "AudioSymLoader.h" #include "GUM_Audio.h" #include <sprite2/AudioSymbol.h> #include <uniaudio/AudioContext.h> namespace gum { AudioSymLoader::AudioSymLoader(s2::AudioSymbol* sym) : m_sym(sym) { if (m_sym) { m_sym->AddReference(); } } AudioSymLoader::~AudioSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AudioSymLoader::Load(const std::string& filepath) { if (!m_sym) { return; } ua::AudioContext* ctx = gum::Audio::Instance()->GetContext(); ua::Source* source = ctx->CreateSource(filepath, true); m_sym->SetSource(source); } }<commit_msg>[FIXED] audio sym ref<commit_after>#include "AudioSymLoader.h" #include "GUM_Audio.h" #include <sprite2/AudioSymbol.h> #include <uniaudio/AudioContext.h> #include <uniaudio/Source.h> namespace gum { AudioSymLoader::AudioSymLoader(s2::AudioSymbol* sym) : m_sym(sym) { if (m_sym) { m_sym->AddReference(); } } AudioSymLoader::~AudioSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AudioSymLoader::Load(const std::string& filepath) { if (!m_sym) { return; } ua::AudioContext* ctx = gum::Audio::Instance()->GetContext(); ua::Source* source = ctx->CreateSource(filepath, true); m_sym->SetSource(source); source->RemoveReference(); } }<|endoftext|>
<commit_before>// Copyright 2017 Google 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 <string> #include <vector> #include "base/flags.h" #include "base/init.h" #include "base/logging.h" #include "base/macros.h" #include "dragnn/core/interfaces/component.h" #include "dragnn/protos/spec.pb.h" #include "file/file.h" #include "frame/object.h" #include "frame/serialization.h" #include "frame/store.h" #include "nlp/document/document.h" #include "nlp/parser/parser-action.h" #include "nlp/parser/trainer/feature.h" #include "nlp/parser/trainer/sempar-component.h" #include "nlp/parser/trainer/shared-resources.h" #include "string/strcat.h" #include "tensorflow/core/platform/protobuf.h" using sling::File; using sling::FileDecoder; using sling::Object; using sling::Store; using sling::StrCat; using sling::nlp::Document; using sling::nlp::ParserAction; using sling::nlp::SemparComponent; using sling::nlp::SemparFeature; using sling::nlp::SharedResources; using syntaxnet::dragnn::Component; using syntaxnet::dragnn::ComponentSpec; using syntaxnet::dragnn::InputBatchCache; using syntaxnet::dragnn::MasterSpec; using tensorflow::protobuf::TextFormat; DEFINE_string(spec, "/tmp/sempar_out/master_spec", "Path to master spec."); DEFINE_string(documents, "/tmp/foobar/doc.?", "Train documents file pattern."); std::vector<int32> indices; std::vector<int64> ids; std::vector<float> weights; int32 *AllocateIndices(int n) { indices.clear(); indices.resize(n); return indices.data(); } int64 *AllocateIds(int n) { ids.clear(); ids.resize(n); return ids.data(); } float *AllocateWeights(int n) { weights.clear(); weights.resize(n); return weights.data(); } int main(int argc, char **argv) { sling::InitProgram(&argc, &argv); CHECK(!FLAGS_spec.empty()); CHECK(!FLAGS_documents.empty()); LOG(INFO) << "Reading spec from " << FLAGS_spec; string contents; CHECK_OK(File::ReadContents(FLAGS_spec, &contents)); MasterSpec spec; CHECK(TextFormat::ParseFromString(contents, &spec)); std::vector<Component *> components; string global_store_path; string action_table_path; for (const auto &component_spec : spec.component()) { LOG(INFO) << "Making/initializing " << component_spec.name(); auto *component = Component::Create(component_spec.backend().registered_name()); component->InitializeComponent(component_spec); components.emplace_back(component); if (global_store_path.empty()) { global_store_path = SemparFeature::GetResource(component_spec, "commons"); } if (action_table_path.empty()) { action_table_path = SemparFeature::GetResource(component_spec, "action-table"); } } LOG(INFO) << "Made & initialized " << components.size() << " components"; CHECK(!global_store_path.empty()); CHECK(!action_table_path.empty()); SharedResources resources; resources.LoadGlobalStore(global_store_path); resources.LoadActionTable(action_table_path); std::vector<string> document_files; CHECK_OK(File::Match(FLAGS_documents, &document_files)); std::vector<string> kept_files; std::vector<string> kept_text; for (const string &file : document_files) { Store local(resources.global); FileDecoder decoder(&local, file); Object top = decoder.Decode(); if (!top.invalid()) { kept_files.emplace_back(file); Document doc(top.AsFrame()); kept_text.emplace_back(doc.PhraseText(0, doc.num_tokens())); } } LOG(INFO) << "Will process " << kept_files.size() << " docs out of " << document_files.size() << " input files"; for (int i = 0; i < kept_files.size(); ++i) { LOG(INFO) << string(80, '*') << "\n"; LOG(INFO) << "Processing doc: " << kept_text[i]; string contents; CHECK_OK(File::ReadContents(kept_files[i], &contents)); std::vector<string> input; input.push_back(contents); InputBatchCache input_data(input); int cidx = 0; for (Component *c : components) { SemparComponent *sc = static_cast<SemparComponent *>(c); CHECK(sc != nullptr); sc->InitializeData({} /* parent states */, 1 /* beam size */, &input_data); CHECK(sc->IsReady()); sc->InitializeTracing(); const auto &cproto = spec.component(cidx); string name = StrCat(cproto.name(), " (shift_only=", sc->shift_only(), ", left_to_right=", sc->left_to_right(), ")"); LOG(INFO) << "Component: " << name; while (!sc->IsTerminal()) { for (int channel = 0; channel < cproto.fixed_feature_size(); ++channel) { int fixed_features = sc->GetFixedFeatures(AllocateIndices, AllocateIds, AllocateWeights, channel); LOG(INFO) << fixed_features << " fixed features for channel " << cproto.fixed_feature(channel).fml(); } for (int channel = 0; channel < cproto.linked_feature_size(); ++channel) { auto linked_features = sc->GetRawLinkFeatures(channel); LOG(INFO) << linked_features.size() << " linked features for channel " << cproto.linked_feature(channel).fml(); sc->AddTranslatedLinkFeaturesToTrace(linked_features, channel); } std::vector<std::vector<int>> oracles = c->GetOracleLabels(); CHECK_EQ(oracles.size(), 1); CHECK_EQ(oracles[0].size(), 1); if (!sc->shift_only()) { const ParserAction &action = resources.table.Action(oracles[0][0]); LOG(INFO) << "Next gold : " << action.ToString(resources.global); } else { CHECK_EQ(oracles[0][0], 0); LOG(INFO) << "Next gold : SHIFT (shift-only system)"; } c->AdvanceFromOracle(); } const auto trace_protos = sc->GetTraceProtos(); CHECK_EQ(trace_protos.size(), 1); CHECK_EQ(trace_protos[0].size(), 1); LOG(INFO) << "Trace proto: " << trace_protos[0][0].DebugString(); cidx++; } } for (Component *c : components) delete c; return 0; } <commit_msg>Use ComputeSession in sempar-component-test.cc<commit_after>// Copyright 2017 Google 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 <string> #include <vector> #include "base/flags.h" #include "base/init.h" #include "base/logging.h" #include "base/macros.h" #include "dragnn/core/compute_session.h" #include "dragnn/core/compute_session_pool.h" #include "dragnn/core/interfaces/component.h" #include "dragnn/protos/spec.pb.h" #include "file/file.h" #include "frame/object.h" #include "frame/serialization.h" #include "frame/store.h" #include "nlp/document/document.h" #include "nlp/parser/parser-action.h" #include "nlp/parser/trainer/feature.h" #include "nlp/parser/trainer/sempar-component.h" #include "nlp/parser/trainer/shared-resources.h" #include "string/strcat.h" #include "tensorflow/core/platform/protobuf.h" using sling::File; using sling::FileDecoder; using sling::Object; using sling::Store; using sling::StrCat; using sling::nlp::Document; using sling::nlp::ParserAction; using sling::nlp::SemparComponent; using sling::nlp::SemparFeature; using sling::nlp::SharedResources; using syntaxnet::dragnn::Component; using syntaxnet::dragnn::ComponentSpec; using syntaxnet::dragnn::ComputeSession; using syntaxnet::dragnn::ComputeSessionPool; using syntaxnet::dragnn::GridPoint; using syntaxnet::dragnn::InputBatchCache; using syntaxnet::dragnn::MasterSpec; using tensorflow::protobuf::TextFormat; DEFINE_string(spec, "/tmp/sempar_out/master_spec", "Path to master spec."); DEFINE_string(documents, "/tmp/foobar/doc.?", "Train documents file pattern."); std::vector<int32> indices; std::vector<int64> ids; std::vector<float> weights; int32 *AllocateIndices(int n) { indices.clear(); indices.resize(n); return indices.data(); } int64 *AllocateIds(int n) { ids.clear(); ids.resize(n); return ids.data(); } float *AllocateWeights(int n) { weights.clear(); weights.resize(n); return weights.data(); } int main(int argc, char **argv) { sling::InitProgram(&argc, &argv); CHECK(!FLAGS_spec.empty()); CHECK(!FLAGS_documents.empty()); LOG(INFO) << "Reading spec from " << FLAGS_spec; string contents; CHECK_OK(File::ReadContents(FLAGS_spec, &contents)); MasterSpec spec; CHECK(TextFormat::ParseFromString(contents, &spec)); GridPoint empty_grid_point; ComputeSessionPool pool(spec, empty_grid_point); auto session = pool.GetSession(); session->SetTracing(true); std::vector<Component *> components; string global_store_path; string action_table_path; for (const auto &component_spec : spec.component()) { LOG(INFO) << "Making/initializing " << component_spec.name(); //auto *component = Component::Create(component_spec.backend().registered_name()); //component->InitializeComponent(component_spec); //components.emplace_back(component); if (global_store_path.empty()) { global_store_path = SemparFeature::GetResource(component_spec, "commons"); } if (action_table_path.empty()) { action_table_path = SemparFeature::GetResource(component_spec, "action-table"); } } //LOG(INFO) << "Made & initialized " << components.size() << " components"; CHECK(!global_store_path.empty()); CHECK(!action_table_path.empty()); SharedResources resources; resources.LoadGlobalStore(global_store_path); resources.LoadActionTable(action_table_path); std::vector<string> document_files; CHECK_OK(File::Match(FLAGS_documents, &document_files)); std::vector<string> kept_files; std::vector<string> kept_text; for (const string &file : document_files) { Store local(resources.global); FileDecoder decoder(&local, file); Object top = decoder.Decode(); if (!top.invalid()) { kept_files.emplace_back(file); Document doc(top.AsFrame()); kept_text.emplace_back(doc.PhraseText(0, doc.num_tokens())); } } LOG(INFO) << "Will process " << kept_files.size() << " docs out of " << document_files.size() << " input files"; for (int i = 0; i < kept_files.size(); ++i) { LOG(INFO) << string(80, '*') << "\n"; LOG(INFO) << "Processing doc: " << kept_text[i]; string contents; CHECK_OK(File::ReadContents(kept_files[i], &contents)); std::vector<string> input; input.push_back(contents); session->SetInputData(input); for (int cidx = 0; cidx < spec.component_size(); ++cidx) { const string &name = spec.component(cidx).name(); session->InitializeComponentData(name, 1 /* max beam size */); while (!session->IsTerminal(name)) { for (int c = 0; c < spec.component(cidx).linked_feature_size(); ++c) { session->GetTranslatedLinkFeatures(name, c); } for (int c = 0; c < spec.component(cidx).fixed_feature_size(); ++c) { session->GetInputFeatures( name, AllocateIndices, AllocateIds, AllocateWeights, c); } session->AdvanceFromOracle(name); } } const auto trace_protos = session->GetTraceProtos(); CHECK_EQ(trace_protos.size(), 1); LOG(INFO) << "Trace proto: " << trace_protos[0].DebugString(); } for (Component *c : components) delete c; return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: style.cpp // Purpose: Implementation of wxExStyle class // Author: Anton van Wezenbeek // Created: 2010-02-08 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/log.h> #include <wx/stc/stc.h> #include <wx/tokenzr.h> #include <wx/extension/style.h> #include <wx/extension/lexers.h> wxExStyle::wxExStyle(const wxXmlNode* node) : m_No() , m_Value() { if (node != NULL) { Set(node); } } wxExStyle::wxExStyle(const wxString& no, const wxString& value) : m_Value(value) { SetNo(no); } void wxExStyle::Apply(wxStyledTextCtrl* stc) const { // Do not assert if m_No is empty, // if we do not have lexers, then the default style is empty, // but still will be applied here. for ( std::vector<int>::const_iterator it = m_No.begin(); it != m_No.end(); ++it) { stc->StyleSetSpec(*it, m_Value); } } bool wxExStyle::IsDefault() const { for ( std::vector<int>::const_iterator it = m_No.begin(); it != m_No.end(); ++it) { if (*it == wxSTC_STYLE_DEFAULT) { return true; } } return false; } void wxExStyle::Set(const wxXmlNode* node) { SetNo(wxExLexers::Get()->ApplyMacro(node->GetAttribute("no", "0"))); wxString content = node->GetNodeContent().Strip(wxString::both); std::map<wxString, wxString>::const_iterator it = wxExLexers::Get()->GetMacrosStyle().find(content); if (it != wxExLexers::Get()->GetMacrosStyle().end()) { content = it->second; } m_Value = content; } void wxExStyle::SetNo(const wxString& no) { wxStringTokenizer no_fields(no, ","); // Collect each single no in the vector. while (no_fields.HasMoreTokens()) { const wxString single = wxExLexers::Get()->ApplyMacro(no_fields.GetNextToken()); if (single.IsNumber()) { m_No.push_back(atoi(single.c_str())); } else { wxLogError(_("Illegal style: %s"), single.c_str()); } } } <commit_msg>removed temp variable<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: style.cpp // Purpose: Implementation of wxExStyle class // Author: Anton van Wezenbeek // Created: 2010-02-08 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/log.h> #include <wx/stc/stc.h> #include <wx/tokenzr.h> #include <wx/extension/style.h> #include <wx/extension/lexers.h> wxExStyle::wxExStyle(const wxXmlNode* node) : m_No() , m_Value() { if (node != NULL) { Set(node); } } wxExStyle::wxExStyle(const wxString& no, const wxString& value) : m_Value(value) { SetNo(no); } void wxExStyle::Apply(wxStyledTextCtrl* stc) const { // Do not assert if m_No is empty, // if we do not have lexers, then the default style is empty, // but still will be applied here. for ( std::vector<int>::const_iterator it = m_No.begin(); it != m_No.end(); ++it) { stc->StyleSetSpec(*it, m_Value); } } bool wxExStyle::IsDefault() const { for ( std::vector<int>::const_iterator it = m_No.begin(); it != m_No.end(); ++it) { if (*it == wxSTC_STYLE_DEFAULT) { return true; } } return false; } void wxExStyle::Set(const wxXmlNode* node) { SetNo(wxExLexers::Get()->ApplyMacro(node->GetAttribute("no", "0"))); m_Value = node->GetNodeContent().Strip(wxString::both); std::map<wxString, wxString>::const_iterator it = wxExLexers::Get()->GetMacrosStyle().find(m_Value); if (it != wxExLexers::Get()->GetMacrosStyle().end()) { m_Value = it->second; } } void wxExStyle::SetNo(const wxString& no) { wxStringTokenizer no_fields(no, ","); // Collect each single no in the vector. while (no_fields.HasMoreTokens()) { const wxString single = wxExLexers::Get()->ApplyMacro(no_fields.GetNextToken()); if (single.IsNumber()) { m_No.push_back(atoi(single.c_str())); } else { wxLogError(_("Illegal style: %s"), single.c_str()); } } } <|endoftext|>
<commit_before>/* * ipop-project * Copyright 2016, University of Florida * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if defined (_IPOP_LINUX) #include "tapdev_lnx.h" #include "tincan_exception.h" namespace tincan { namespace linux { static const char * const TUN_PATH = "/dev/net/tun"; TapDevLnx::TapDevLnx() : fd_(-1), ip4_config_skt_(-1), is_good_(false) {} TapDevLnx::~TapDevLnx() {} void TapDevLnx::Open( const TapDescriptor & tap_desc) { string emsg("The Tap device open operation failed - "); //const char* tap_name = tap_desc.interface_name; if((fd_ = open(TUN_PATH, O_RDWR)) < 0) throw TCEXCEPT(emsg.c_str()); ifr_.ifr_flags = IFF_TAP | IFF_NO_PI; if(tap_desc.interface_name.length() >= IFNAMSIZ) { emsg.append("the name length is longer than maximum allowed."); throw TCEXCEPT(emsg.c_str()); } strncpy(ifr_.ifr_name, tap_desc.interface_name.c_str(), tap_desc.interface_name.length()); //create the device if(ioctl(fd_, TUNSETIFF, (void *)&ifr_) < 0) { emsg.append("the device could not be created."); throw TCEXCEPT(emsg.c_str()); } //create a socket to be used when retrieving mac address from the kernel if((ip4_config_skt_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { emsg.append("a socket bind failed."); throw TCEXCEPT(emsg.c_str()); } if((ioctl(ip4_config_skt_, SIOCGIFHWADDR, &ifr_)) < 0) { emsg.append("retrieving the device mac address failed"); throw TCEXCEPT(emsg.c_str()); } memcpy(mac_.data(), ifr_.ifr_hwaddr.sa_data, 6); SetIpv4Addr(tap_desc.Ip4.c_str(), tap_desc.prefix4); if(!tap_desc.mtu4) Mtu(576); else Mtu(tap_desc.mtu4); is_good_ = true; } void TapDevLnx::Close() { close(fd_); } void TapDevLnx::SetIpv4Addr( const char* ipaddr, unsigned int prefix_len) { string emsg("The Tap device Set IP4 Address operation failed"); struct sockaddr_in socket_address = { .sin_family = AF_INET,.sin_port = 0 }; if(inet_pton(AF_INET, ipaddr, &socket_address.sin_addr) != 1) { emsg.append(" - the provided IP4 address could not be resolved."); throw TCEXCEPT(emsg.c_str()); } //wrap sockaddr_in struct to sockaddr struct, which is used conventionaly for system calls memcpy(&ifr_.ifr_addr, &socket_address, sizeof(struct sockaddr)); //copies ipv4 address to my my_ipv4. ipv4 address starts at sa_data[2] //and terminates at sa_data[5] memcpy(ip4_.data(), &ifr_.ifr_addr.sa_data[2], 4); //configure tap device with a ipv4 address if(ioctl(ip4_config_skt_, SIOCSIFADDR, &ifr_) < 0) { throw TCEXCEPT(emsg.c_str()); } //get subnet mask intoi network byte order from int representation PlenToIpv4Mask(prefix_len, &ifr_.ifr_netmask); //configure the tap device with a netmask if(ioctl(ip4_config_skt_, SIOCSIFNETMASK, &ifr_) < 0) { LOG_F(LS_VERBOSE) << " failed to set ipv4 netmask on tap device"; } } void TapDevLnx::PlenToIpv4Mask( unsigned int prefix_len, struct sockaddr * writeback) { uint32_t net_mask_int = ~(0u) << (32 - prefix_len); net_mask_int = htonl(net_mask_int); struct sockaddr_in netmask = { .sin_family = AF_INET, .sin_port = 0 }; struct in_addr netmask_addr = { .s_addr = net_mask_int }; netmask.sin_addr = netmask_addr; //wrap sockaddr_in into sock_addr struct memcpy(writeback, &netmask, sizeof(struct sockaddr)); } /** * Given some flags to enable and disable, reads the current flags for the * network device, and then ensures the high bits in enable are also high in * ifr_flags, and the high bits in disable are low in ifr_flags. The results are * then written back. For a list of valid flags, read the "SIOCGIFFLAGS, * SIOCSIFFLAGS" section of the 'man netdevice' page. You can pass `(short)0` if * you don't want to enable or disable any flags. */ void TapDevLnx::SetFlags( short enable, short disable) { string emsg("The TAP device set flags operation failed"); if(ioctl(ip4_config_skt_, SIOCGIFFLAGS, &ifr_) < 0) { throw TCEXCEPT(emsg.c_str()); } //set or unset the right flags ifr_.ifr_flags |= enable; ifr_.ifr_flags &= ~disable; //write back the modified flag states if(ioctl(ip4_config_skt_, SIOCSIFFLAGS, &ifr_) < 0) throw TCEXCEPT(emsg.c_str()); } uint32_t TapDevLnx::Read(AsyncIo& aio_rd) { if(!is_good_) return 1; //indicates a failure to setup async operation TapPayload *tp_ = new TapPayload; tp_->aio_ = &aio_rd; reader_.Post(RTC_FROM_HERE, this, MSGID_READ, tp_); return 0; } uint32_t TapDevLnx::Write(AsyncIo& aio_wr) { if(!is_good_) return 1; //indicates a failure to setup async operation TapPayload *tp_ = new TapPayload; tp_->aio_ = &aio_wr; writer_.Post(RTC_FROM_HERE, this, MSGID_WRITE, tp_); return 0; } void TapDevLnx::Mtu(uint16_t mtu) { ifr_.ifr_mtu = mtu; if(ioctl(ip4_config_skt_, SIOCSIFMTU, &ifr_) < 0) { throw TCEXCEPT("The TAP Device set MTU operation failed."); } } uint16_t TapDevLnx::TapDevLnx::Mtu() { return ifr_.ifr_mtu; } MacAddressType TapDevLnx::MacAddress() { return mac_; } /** * Sets and unsets some common flags used on a TAP device, namely, it sets the * IFF_NOARP flag, and unsets IFF_MULTICAST and IFF_BROADCAST. Notably, if * IFF_NOARP is not set, when using an IPv6 TAP, applications will have trouble * routing their data through the TAP device (Because they'd expect an ARP * response, which we aren't really willing to provide). */ void TapDevLnx::Up() { SetFlags(IFF_UP | IFF_RUNNING, 0); reader_.Start(); writer_.Start(); } void TapDevLnx::Down() { //TODO: set the appropriate flags SetFlags(0, IFF_UP | IFF_RUNNING); LOG_F(LS_INFO) << "TAP DOWN"; } void TapDevLnx::OnMessage(Message * msg) { switch(msg->message_id) { case MSGID_READ: { AsyncIo* aio_read = ((TapPayload*)msg->pdata)->aio_; int nread = read(fd_, aio_read->BufferToTransfer(), aio_read->BytesToTransfer()); if(nread < 0) { LOG_F(LS_WARNING) << "A TAP Read operation failed."; aio_read->good_ = false; } else { aio_read->good_ = true; aio_read->BytesTransferred(nread); read_completion_(aio_read); } } break; case MSGID_WRITE: { AsyncIo* aio_write = ((TapPayload*)msg->pdata)->aio_; int nwrite = write(fd_, aio_write->BufferToTransfer(), aio_write->BytesToTransfer()); if(nwrite < 0) { LOG_F(LS_WARNING) << "A TAP Write operation failed."; aio_write->good_ = false; } else { aio_write->good_ = true; aio_write->BytesTransferred(nwrite); write_completion_(aio_write); } } break; } } IP4AddressType TapDevLnx::Ip4() { return ip4_; } } // linux } // tincan #endif // _IPOP_LINUX <commit_msg>Update for tap descriptor<commit_after>/* * ipop-project * Copyright 2016, University of Florida * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if defined (_IPOP_LINUX) #include "tapdev_lnx.h" #include "tincan_exception.h" namespace tincan { namespace linux { static const char * const TUN_PATH = "/dev/net/tun"; TapDevLnx::TapDevLnx() : fd_(-1), ip4_config_skt_(-1), is_good_(false) {} TapDevLnx::~TapDevLnx() {} void TapDevLnx::Open( const TapDescriptor & tap_desc) { string emsg("The Tap device open operation failed - "); //const char* tap_name = tap_desc.name; if((fd_ = open(TUN_PATH, O_RDWR)) < 0) throw TCEXCEPT(emsg.c_str()); ifr_.ifr_flags = IFF_TAP | IFF_NO_PI; if(tap_desc.name.length() >= IFNAMSIZ) { emsg.append("the name length is longer than maximum allowed."); throw TCEXCEPT(emsg.c_str()); } strncpy(ifr_.ifr_name, tap_desc.name.c_str(), tap_desc.name.length()); //create the device if(ioctl(fd_, TUNSETIFF, (void *)&ifr_) < 0) { emsg.append("the device could not be created."); throw TCEXCEPT(emsg.c_str()); } //create a socket to be used when retrieving mac address from the kernel if((ip4_config_skt_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { emsg.append("a socket bind failed."); throw TCEXCEPT(emsg.c_str()); } if((ioctl(ip4_config_skt_, SIOCGIFHWADDR, &ifr_)) < 0) { emsg.append("retrieving the device mac address failed"); throw TCEXCEPT(emsg.c_str()); } memcpy(mac_.data(), ifr_.ifr_hwaddr.sa_data, 6); SetIpv4Addr(tap_desc.ip4.c_str(), tap_desc.prefix4); if(!tap_desc.mtu4) Mtu(576); else Mtu(tap_desc.mtu4); is_good_ = true; } void TapDevLnx::Close() { close(fd_); } void TapDevLnx::SetIpv4Addr( const char* ipaddr, unsigned int prefix_len) { string emsg("The Tap device Set IP4 Address operation failed"); struct sockaddr_in socket_address = { .sin_family = AF_INET,.sin_port = 0 }; if(inet_pton(AF_INET, ipaddr, &socket_address.sin_addr) != 1) { emsg.append(" - the provided IP4 address could not be resolved."); throw TCEXCEPT(emsg.c_str()); } //wrap sockaddr_in struct to sockaddr struct, which is used conventionaly for system calls memcpy(&ifr_.ifr_addr, &socket_address, sizeof(struct sockaddr)); //copies ipv4 address to my my_ipv4. ipv4 address starts at sa_data[2] //and terminates at sa_data[5] memcpy(ip4_.data(), &ifr_.ifr_addr.sa_data[2], 4); //configure tap device with a ipv4 address if(ioctl(ip4_config_skt_, SIOCSIFADDR, &ifr_) < 0) { throw TCEXCEPT(emsg.c_str()); } //get subnet mask intoi network byte order from int representation PlenToIpv4Mask(prefix_len, &ifr_.ifr_netmask); //configure the tap device with a netmask if(ioctl(ip4_config_skt_, SIOCSIFNETMASK, &ifr_) < 0) { LOG_F(LS_VERBOSE) << " failed to set ipv4 netmask on tap device"; } } void TapDevLnx::PlenToIpv4Mask( unsigned int prefix_len, struct sockaddr * writeback) { uint32_t net_mask_int = ~(0u) << (32 - prefix_len); net_mask_int = htonl(net_mask_int); struct sockaddr_in netmask = { .sin_family = AF_INET, .sin_port = 0 }; struct in_addr netmask_addr = { .s_addr = net_mask_int }; netmask.sin_addr = netmask_addr; //wrap sockaddr_in into sock_addr struct memcpy(writeback, &netmask, sizeof(struct sockaddr)); } /** * Given some flags to enable and disable, reads the current flags for the * network device, and then ensures the high bits in enable are also high in * ifr_flags, and the high bits in disable are low in ifr_flags. The results are * then written back. For a list of valid flags, read the "SIOCGIFFLAGS, * SIOCSIFFLAGS" section of the 'man netdevice' page. You can pass `(short)0` if * you don't want to enable or disable any flags. */ void TapDevLnx::SetFlags( short enable, short disable) { string emsg("The TAP device set flags operation failed"); if(ioctl(ip4_config_skt_, SIOCGIFFLAGS, &ifr_) < 0) { throw TCEXCEPT(emsg.c_str()); } //set or unset the right flags ifr_.ifr_flags |= enable; ifr_.ifr_flags &= ~disable; //write back the modified flag states if(ioctl(ip4_config_skt_, SIOCSIFFLAGS, &ifr_) < 0) throw TCEXCEPT(emsg.c_str()); } uint32_t TapDevLnx::Read(AsyncIo& aio_rd) { if(!is_good_) return 1; //indicates a failure to setup async operation TapPayload *tp_ = new TapPayload; tp_->aio_ = &aio_rd; reader_.Post(RTC_FROM_HERE, this, MSGID_READ, tp_); return 0; } uint32_t TapDevLnx::Write(AsyncIo& aio_wr) { if(!is_good_) return 1; //indicates a failure to setup async operation TapPayload *tp_ = new TapPayload; tp_->aio_ = &aio_wr; writer_.Post(RTC_FROM_HERE, this, MSGID_WRITE, tp_); return 0; } void TapDevLnx::Mtu(uint16_t mtu) { ifr_.ifr_mtu = mtu; if(ioctl(ip4_config_skt_, SIOCSIFMTU, &ifr_) < 0) { throw TCEXCEPT("The TAP Device set MTU operation failed."); } } uint16_t TapDevLnx::TapDevLnx::Mtu() { return ifr_.ifr_mtu; } MacAddressType TapDevLnx::MacAddress() { return mac_; } /** * Sets and unsets some common flags used on a TAP device, namely, it sets the * IFF_NOARP flag, and unsets IFF_MULTICAST and IFF_BROADCAST. Notably, if * IFF_NOARP is not set, when using an IPv6 TAP, applications will have trouble * routing their data through the TAP device (Because they'd expect an ARP * response, which we aren't really willing to provide). */ void TapDevLnx::Up() { SetFlags(IFF_UP | IFF_RUNNING, 0); reader_.Start(); writer_.Start(); } void TapDevLnx::Down() { //TODO: set the appropriate flags SetFlags(0, IFF_UP | IFF_RUNNING); LOG_F(LS_INFO) << "TAP DOWN"; } void TapDevLnx::OnMessage(Message * msg) { switch(msg->message_id) { case MSGID_READ: { AsyncIo* aio_read = ((TapPayload*)msg->pdata)->aio_; int nread = read(fd_, aio_read->BufferToTransfer(), aio_read->BytesToTransfer()); if(nread < 0) { LOG_F(LS_WARNING) << "A TAP Read operation failed."; aio_read->good_ = false; } else { aio_read->good_ = true; aio_read->BytesTransferred(nread); read_completion_(aio_read); } } break; case MSGID_WRITE: { AsyncIo* aio_write = ((TapPayload*)msg->pdata)->aio_; int nwrite = write(fd_, aio_write->BufferToTransfer(), aio_write->BytesToTransfer()); if(nwrite < 0) { LOG_F(LS_WARNING) << "A TAP Write operation failed."; aio_write->good_ = false; } else { aio_write->good_ = true; aio_write->BytesTransferred(nwrite); write_completion_(aio_write); } } break; } } IP4AddressType TapDevLnx::Ip4() { return ip4_; } } // linux } // tincan #endif // _IPOP_LINUX <|endoftext|>
<commit_before> #pragma once #include <type_traits> #include <ostream> #include "geometry/hilbert.hpp" #include "quantities/named_quantities.hpp" namespace principia { namespace geometry { namespace internal_complexification { using quantities::Difference; using quantities::Product; using quantities::Quotient; using quantities::Sum; template<typename Vector> class Complexification { public: Complexification() = default; template<typename V, typename = std::enable_if_t<std::is_convertible_v<V, Vector>>> Complexification(V const& real_part); // NOLINT explicit Complexification(Vector const& real_part, Vector const& imaginary_part); Vector const& real_part() const; Vector const& imaginary_part() const; Complexification Conjugate() const; typename Hilbert<Vector>::InnerProductType Norm²() const; template<typename R> Complexification& operator+=(R const& right); template<typename R> Complexification& operator-=(R const& right); template<typename R> Complexification& operator*=(R const& right); template<typename R> Complexification& operator/=(R const& right); private: Vector real_part_{}; Vector imaginary_part_{}; }; template<typename Vector> bool operator==(Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename Vector> bool operator!=(Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename Vector> Complexification<Vector> operator+(Complexification<Vector> const& right); template<typename Vector> Complexification<Vector> operator-(Complexification<Vector> const& right); template<typename L, typename Vector> Complexification<Sum<L, Vector>> operator+( L const& left, Complexification<Vector> const& right); template<typename Vector, typename R> Complexification<Sum<Vector, R>> operator+( Complexification<Vector> const& left, R const& right); template<typename Vector> Complexification<Vector> operator+( Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename L, typename Vector> Complexification<Difference<L, Vector>> operator-( L const& left, Complexification<Vector> const& right); template<typename Vector, typename R> Complexification<Difference<Vector, R>> operator-( Complexification<Vector> const& left, R const& right); template<typename Vector> Complexification<Vector> operator-( Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename L, typename RVector> Complexification<Product<L, RVector>> operator*( L const& left, Complexification<RVector> const& right); template<typename LVector, typename R> Complexification<Product<LVector, R>> operator*( Complexification<LVector> const& left, R const& right); // TODO(egg): Numerical analysis. template<typename LVector, typename RVector> Complexification<Product<LVector, RVector>> operator*( Complexification<LVector> const& left, Complexification<RVector> const& right); // TODO(egg): Numerical analysis. template<typename L, typename RVector> Complexification<Quotient<L, RVector>> operator/( L const& left, Complexification<RVector> const& right); template<typename LVector, typename R> Complexification<Quotient<LVector, R>> operator/( Complexification<LVector> const& left, R const& right); // TODO(egg): Numerical analysis. template<typename LVector, typename RVector> Complexification<Quotient<LVector, RVector>> operator/( Complexification<LVector> const& left, Complexification<RVector> const& right); template<typename Vector> std::ostream& operator<<(std::ostream& out, Complexification<Vector> const& z); } // namespace internal_complexification using internal_complexification::Complexification; } // namespace geometry } // namespace principia #include "geometry/complexification_body.hpp" <commit_msg>Moar lint.<commit_after> #pragma once #include <type_traits> #include <ostream> #include "geometry/hilbert.hpp" #include "quantities/named_quantities.hpp" namespace principia { namespace geometry { namespace internal_complexification { using quantities::Difference; using quantities::Product; using quantities::Quotient; using quantities::Sum; template<typename Vector> class Complexification { public: Complexification() = default; template<typename V, typename = std::enable_if_t<std::is_convertible_v<V, Vector>>> Complexification(V const& real_part); // NOLINT(runtime/explicit) explicit Complexification(Vector const& real_part, Vector const& imaginary_part); Vector const& real_part() const; Vector const& imaginary_part() const; Complexification Conjugate() const; typename Hilbert<Vector>::InnerProductType Norm²() const; template<typename R> Complexification& operator+=(R const& right); template<typename R> Complexification& operator-=(R const& right); template<typename R> Complexification& operator*=(R const& right); template<typename R> Complexification& operator/=(R const& right); private: Vector real_part_{}; Vector imaginary_part_{}; }; template<typename Vector> bool operator==(Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename Vector> bool operator!=(Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename Vector> Complexification<Vector> operator+(Complexification<Vector> const& right); template<typename Vector> Complexification<Vector> operator-(Complexification<Vector> const& right); template<typename L, typename Vector> Complexification<Sum<L, Vector>> operator+( L const& left, Complexification<Vector> const& right); template<typename Vector, typename R> Complexification<Sum<Vector, R>> operator+( Complexification<Vector> const& left, R const& right); template<typename Vector> Complexification<Vector> operator+( Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename L, typename Vector> Complexification<Difference<L, Vector>> operator-( L const& left, Complexification<Vector> const& right); template<typename Vector, typename R> Complexification<Difference<Vector, R>> operator-( Complexification<Vector> const& left, R const& right); template<typename Vector> Complexification<Vector> operator-( Complexification<Vector> const& left, Complexification<Vector> const& right); template<typename L, typename RVector> Complexification<Product<L, RVector>> operator*( L const& left, Complexification<RVector> const& right); template<typename LVector, typename R> Complexification<Product<LVector, R>> operator*( Complexification<LVector> const& left, R const& right); // TODO(egg): Numerical analysis. template<typename LVector, typename RVector> Complexification<Product<LVector, RVector>> operator*( Complexification<LVector> const& left, Complexification<RVector> const& right); // TODO(egg): Numerical analysis. template<typename L, typename RVector> Complexification<Quotient<L, RVector>> operator/( L const& left, Complexification<RVector> const& right); template<typename LVector, typename R> Complexification<Quotient<LVector, R>> operator/( Complexification<LVector> const& left, R const& right); // TODO(egg): Numerical analysis. template<typename LVector, typename RVector> Complexification<Quotient<LVector, RVector>> operator/( Complexification<LVector> const& left, Complexification<RVector> const& right); template<typename Vector> std::ostream& operator<<(std::ostream& out, Complexification<Vector> const& z); } // namespace internal_complexification using internal_complexification::Complexification; } // namespace geometry } // namespace principia #include "geometry/complexification_body.hpp" <|endoftext|>
<commit_before>/* * SlideRenderer.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SlideRenderer.hpp" #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/StringUtils.hpp> #include <core/json/Json.hpp> #include <core/markdown/Markdown.hpp> #include <session/SessionModuleContext.hpp> #include "SlideParser.hpp" #include "SlideMediaRenderer.hpp" #include "SlideNavigationList.hpp" using namespace core; namespace session { namespace modules { namespace presentation { namespace { std::string commandsAsJsonArray(const Slide& slide) { json::Array commandsJsonArray; std::vector<Command> commands = slide.commands(); BOOST_FOREACH(const Command& command, commands) { commandsJsonArray.push_back(command.asJson()); } std::ostringstream ostr; json::write(commandsJsonArray, ostr); return ostr.str(); } Error renderMarkdown(const std::string& content, std::string* pHTML) { markdown::Extensions extensions; markdown::HTMLOptions htmlOptions; return markdown::markdownToHTML(content, extensions, htmlOptions, pHTML); } Error slideMarkdownToHtml(const Slide& slide, std::string* pHTML) { // render the markdown Error error = renderMarkdown(slide.content(), pHTML); if (error) return error; // look for an <hr/> splitting the html into columns const std::string kHRTag = "<hr/>"; std::size_t hrLoc = pHTML->find(kHRTag); if (hrLoc != std::string::npos) { std::string columnOne = pHTML->substr(0, hrLoc); std::string columnTwo; if (pHTML->length() > (columnOne.length() + kHRTag.length())) columnTwo = pHTML->substr(hrLoc + kHRTag.length()); // now render two divs with the columns pHTML->clear(); std::ostringstream ostr; ostr << "<div class=\"column1\">" << columnOne << "</div>"; ostr << "<div class=\"column2\">" << columnTwo << "</div>"; *pHTML = ostr.str(); } return Success(); } } // anonymous namespace Error renderSlides(const SlideDeck& slideDeck, std::string* pSlides, std::string* pRevealConfig, std::string* pInitActions, std::string* pSlideActions) { // render the slides to HTML and slide commands to case statements std::ostringstream ostr, ostrRevealConfig, ostrInitActions, ostrSlideActions; // track json version of slide list SlideNavigationList navigationList; // now the slides std::string cmdPad(8, ' '); int slideNumber = 0; for (size_t i=0; i<slideDeck.slides().size(); i++) { // slide const Slide& slide = slideDeck.slides().at(i); // is this the first slide? bool isFirstSlide = (i == 0); // if this is the first slide then set the navigation type from it if (isFirstSlide) navigationList.setNavigationType(slide.navigation()); // track in list navigationList.add(slide); ostr << "<section"; if (!slide.id().empty()) ostr << " id=\"" << slide.id() << "\""; // get the slide type std::string type = isFirstSlide ? "section" : slide.type(); // add the state if there is a type if (!type.empty()) ostr << " data-state=\"" << type << "\""; // end section tag ostr << ">" << std::endl; // show the title with the appropriate header if (isFirstSlide || slide.showTitle()) { std::string hTag; if (isFirstSlide) hTag = "h1"; else if (type == "section" || type == "sub-section") hTag = "h2"; else hTag = "h3"; ostr << "<" << hTag << ">" << string_utils::htmlEscape(slide.title()) << "</" << hTag << ">"; } // if this is slide one then render author and date if they are included if (isFirstSlide) { ostr << "<p>"; if (!slide.author().empty()) { ostr << string_utils::htmlEscape(slide.author()); if (!slide.date().empty()) ostr << "<br/>"; } if (!slide.date().empty()) ostr << string_utils::htmlEscape(slide.date()); ostr << "</p>" << std::endl; } // render markdown std::string htmlContent; Error error = slideMarkdownToHtml(slide, &htmlContent); if (error) return error; // render content ostr << htmlContent << std::endl; // setup vectors for reveal config and init actions std::vector<std::string> revealConfig; std::vector<std::string> initActions; // setup a vector of js actions to take when the slide loads // (we always take the action of adding any embedded commands) std::vector<std::string> slideActions; slideActions.push_back("cmds = " + commandsAsJsonArray(slide)); // get at commands std::vector<AtCommand> atCommands = slide.atCommands(); // render video if specified std::string video = slide.video(); if (!video.empty()) { renderMedia("video", slideNumber, slideDeck.baseDir(), video, atCommands, ostr, &initActions, &slideActions); } // render audio if specified std::string audio = slide.audio(); if (!audio.empty()) { renderMedia("audio", slideNumber, slideDeck.baseDir(), audio, atCommands, ostr, &initActions, &slideActions); } ostr << "</section>" << std::endl; // reveal config actions BOOST_FOREACH(const std::string& config, revealConfig) { ostrRevealConfig << config << "," << std::endl; } // javascript actions to take on slide deck init BOOST_FOREACH(const std::string& jsAction, initActions) { ostrInitActions << jsAction << ";" << std::endl; } // javascript actions to take on slide load ostrSlideActions << cmdPad << "case " << slideNumber << ":" << std::endl; BOOST_FOREACH(const std::string& jsAction, slideActions) { ostrSlideActions << cmdPad << " " << jsAction << ";" << std::endl; } ostrSlideActions << std::endl << cmdPad << " break;" << std::endl; // increment slide number slideNumber++; } // init slide list as part of actions navigationList.complete(); ostrInitActions << navigationList.asCall() << std::endl; *pSlides = ostr.str(); *pRevealConfig = ostrRevealConfig.str(); *pInitActions = ostrInitActions.str(); *pSlideActions = ostrSlideActions.str(); return Success(); } } // namespace presentation } // namespace modules } // namesapce session <commit_msg>factor out div wrap<commit_after>/* * SlideRenderer.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SlideRenderer.hpp" #include <boost/foreach.hpp> #include <boost/format.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/StringUtils.hpp> #include <core/json/Json.hpp> #include <core/markdown/Markdown.hpp> #include <session/SessionModuleContext.hpp> #include "SlideParser.hpp" #include "SlideMediaRenderer.hpp" #include "SlideNavigationList.hpp" using namespace core; namespace session { namespace modules { namespace presentation { namespace { std::string commandsAsJsonArray(const Slide& slide) { json::Array commandsJsonArray; std::vector<Command> commands = slide.commands(); BOOST_FOREACH(const Command& command, commands) { commandsJsonArray.push_back(command.asJson()); } std::ostringstream ostr; json::write(commandsJsonArray, ostr); return ostr.str(); } Error renderMarkdown(const std::string& content, std::string* pHTML) { markdown::Extensions extensions; markdown::HTMLOptions htmlOptions; return markdown::markdownToHTML(content, extensions, htmlOptions, pHTML); } std::string divWrap(const std::string& className, const std::string& contents) { boost::format fmt("\n<div class=\"%1%\">\n%2%\n</div>\n"); return boost::str(fmt % className % contents); } Error slideMarkdownToHtml(const Slide& slide, std::string* pHTML) { // render the markdown Error error = renderMarkdown(slide.content(), pHTML); if (error) return error; // look for an <hr/> splitting the html into columns const std::string kHRTag = "<hr/>"; std::size_t hrLoc = pHTML->find(kHRTag); if (hrLoc != std::string::npos) { std::string column1 = pHTML->substr(0, hrLoc); std::string column2; if (pHTML->length() > (column1.length() + kHRTag.length())) column2 = pHTML->substr(hrLoc + kHRTag.length()); // now render two divs with the columns pHTML->clear(); std::ostringstream ostr; ostr << divWrap("column1", column1); ostr << divWrap("column2", column2); *pHTML = ostr.str(); } // see if we have an image, and if so whether it is standalone, // above text, or below text else { } return Success(); } } // anonymous namespace Error renderSlides(const SlideDeck& slideDeck, std::string* pSlides, std::string* pRevealConfig, std::string* pInitActions, std::string* pSlideActions) { // render the slides to HTML and slide commands to case statements std::ostringstream ostr, ostrRevealConfig, ostrInitActions, ostrSlideActions; // track json version of slide list SlideNavigationList navigationList; // now the slides std::string cmdPad(8, ' '); int slideNumber = 0; for (size_t i=0; i<slideDeck.slides().size(); i++) { // slide const Slide& slide = slideDeck.slides().at(i); // is this the first slide? bool isFirstSlide = (i == 0); // if this is the first slide then set the navigation type from it if (isFirstSlide) navigationList.setNavigationType(slide.navigation()); // track in list navigationList.add(slide); ostr << "<section"; if (!slide.id().empty()) ostr << " id=\"" << slide.id() << "\""; // get the slide type std::string type = isFirstSlide ? "section" : slide.type(); // add the state if there is a type if (!type.empty()) ostr << " data-state=\"" << type << "\""; // end section tag ostr << ">" << std::endl; // show the title with the appropriate header if (isFirstSlide || slide.showTitle()) { std::string hTag; if (isFirstSlide) hTag = "h1"; else if (type == "section" || type == "sub-section") hTag = "h2"; else hTag = "h3"; ostr << "<" << hTag << ">" << string_utils::htmlEscape(slide.title()) << "</" << hTag << ">"; } // if this is slide one then render author and date if they are included if (isFirstSlide) { ostr << "<p>"; if (!slide.author().empty()) { ostr << string_utils::htmlEscape(slide.author()); if (!slide.date().empty()) ostr << "<br/>"; } if (!slide.date().empty()) ostr << string_utils::htmlEscape(slide.date()); ostr << "</p>" << std::endl; } // render markdown std::string htmlContent; Error error = slideMarkdownToHtml(slide, &htmlContent); if (error) return error; // render content ostr << htmlContent << std::endl; // setup vectors for reveal config and init actions std::vector<std::string> revealConfig; std::vector<std::string> initActions; // setup a vector of js actions to take when the slide loads // (we always take the action of adding any embedded commands) std::vector<std::string> slideActions; slideActions.push_back("cmds = " + commandsAsJsonArray(slide)); // get at commands std::vector<AtCommand> atCommands = slide.atCommands(); // render video if specified std::string video = slide.video(); if (!video.empty()) { renderMedia("video", slideNumber, slideDeck.baseDir(), video, atCommands, ostr, &initActions, &slideActions); } // render audio if specified std::string audio = slide.audio(); if (!audio.empty()) { renderMedia("audio", slideNumber, slideDeck.baseDir(), audio, atCommands, ostr, &initActions, &slideActions); } ostr << "</section>" << std::endl; // reveal config actions BOOST_FOREACH(const std::string& config, revealConfig) { ostrRevealConfig << config << "," << std::endl; } // javascript actions to take on slide deck init BOOST_FOREACH(const std::string& jsAction, initActions) { ostrInitActions << jsAction << ";" << std::endl; } // javascript actions to take on slide load ostrSlideActions << cmdPad << "case " << slideNumber << ":" << std::endl; BOOST_FOREACH(const std::string& jsAction, slideActions) { ostrSlideActions << cmdPad << " " << jsAction << ";" << std::endl; } ostrSlideActions << std::endl << cmdPad << " break;" << std::endl; // increment slide number slideNumber++; } // init slide list as part of actions navigationList.complete(); ostrInitActions << navigationList.asCall() << std::endl; *pSlides = ostr.str(); *pRevealConfig = ostrRevealConfig.str(); *pInitActions = ostrInitActions.str(); *pSlideActions = ostrSlideActions.str(); return Success(); } } // namespace presentation } // namespace modules } // namesapce session <|endoftext|>
<commit_before>// // Target.hpp // Clock Signal // // Created by Thomas Harte on 03/06/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #ifndef Analyser_Static_Macintosh_Target_h #define Analyser_Static_Macintosh_Target_h namespace Analyser { namespace Static { namespace Macintosh { struct Target: public ::Analyser::Static::Target { enum class Model { Mac128k, Mac512k, Mac512ke, MacPlus }; Model model = Model::Mac128k; }; } } } #endif /* Analyser_Static_Macintosh_Target_h */ <commit_msg>Switches to testing against the Mac Plus ROM.<commit_after>// // Target.hpp // Clock Signal // // Created by Thomas Harte on 03/06/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #ifndef Analyser_Static_Macintosh_Target_h #define Analyser_Static_Macintosh_Target_h namespace Analyser { namespace Static { namespace Macintosh { struct Target: public ::Analyser::Static::Target { enum class Model { Mac128k, Mac512k, Mac512ke, MacPlus }; Model model = Model::Mac512ke; }; } } } #endif /* Analyser_Static_Macintosh_Target_h */ <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief 菊水電源インターフェース・クラス @n ※0.14 mA 以下の電流を測定出来ない為、停電流源による下駄を @n 履かせている。@n その為、起動時に定電流源の基準を測定している。 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <boost/format.hpp> #include "utils/serial_win32.hpp" #include "utils/fixed_fifo.hpp" #include "utils/input.hpp" #include "utils/string_utils.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 菊水電源インターフェース・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class kikusui { device::serial_win32& serial_; typedef utils::fixed_fifo<char, 1024> FIFO; FIFO fifo_; enum class task { idle, state, ///< 菊水の電源が接続されているか? refc, ///< 下駄を履かせた分の基準電流の測定 refc_wait, refc_sync, volt, curr, }; task task_; float volt_; float curr_; uint32_t volt_id_; uint32_t curr_id_; uint32_t loop_; bool timeout_; uint32_t refc_wait_; float refc_; std::string rt_; std::string idn_; bool get_text_() { while(fifo_.length() > 0) { auto ch = fifo_.get(); if(ch == '\n') { return true; } else if(ch != '\r') { rt_ += ch; } } return false; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// kikusui(device::serial_win32& serial) : serial_(serial), fifo_(), task_(task::idle), volt_(0.0f), curr_(0.0f), volt_id_(0), curr_id_(0), loop_(0), timeout_(false), refc_wait_(0), refc_(0.0f), idn_() { } //-----------------------------------------------------------------// /*! @brief 開始 */ //-----------------------------------------------------------------// void start() { std::string s = "INST:NSEL 6;*IDN?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::state; loop_ = 60; // *IDN? time out 1 sec } //-----------------------------------------------------------------// /*! @brief IDN の取得 @return IDN */ //-----------------------------------------------------------------// const std::string& get_idn() const { return idn_; } //-----------------------------------------------------------------// /*! @brief 停止 */ //-----------------------------------------------------------------// void stop() { std::string s = "CURR 0 A\r\n"; serial_.write(s.c_str(), s.size()); s = "VOLT 0 V\r\n"; serial_.write(s.c_str(), s.size()); s = "OUTP 0\r\n"; serial_.write(s.c_str(), s.size()); } //-----------------------------------------------------------------// /*! @brief 出力設定 @param[in] ena 許可の場合「true」 */ //-----------------------------------------------------------------// void set_output(bool ena) { std::string s; if(ena) { s = "OUTP 1\r\n"; } else { s = "OUTP 0\r\n"; } serial_.write(s.c_str(), s.size()); // std::cout << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電圧設定 @param[in] volt 設定電圧 @param[in] curr 最大電流 */ //-----------------------------------------------------------------// void set_volt(float volt, float curr) { auto s = (boost::format("CURR %5.4f A;VOLT %5.4f V\r\n") % (curr + refc_) % volt).str(); serial_.write(s.c_str(), s.size()); // std::cout << "VOLT: " << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電流設定 @param[in] curr 設定電流 @param[in] volt 最大電圧 */ //-----------------------------------------------------------------// void set_curr(float curr, float volt) { auto s = (boost::format("VOLT %5.4f V;CURR %5.4f A\r\n") % volt % (curr + refc_)).str(); serial_.write(s.c_str(), s.size()); // std::cout << "CURR: " << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電圧測定要求 */ //-----------------------------------------------------------------// void req_volt() { std::string s = "MEAS:VOLT:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::volt; } //-----------------------------------------------------------------// /*! @brief 電流測定要求 */ //-----------------------------------------------------------------// void req_curr() { std::string s = "MEAS:CURR:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::curr; } //-----------------------------------------------------------------// /*! @brief 電圧 ID を取得 @return 電圧 ID */ //-----------------------------------------------------------------// uint32_t get_volt_id() const { return volt_id_; } //-----------------------------------------------------------------// /*! @brief 電圧を取得 [V] @return 電圧 */ //-----------------------------------------------------------------// float get_volt() const { return volt_; } //-----------------------------------------------------------------// /*! @brief 電流 ID を取得 @return 電流 ID */ //-----------------------------------------------------------------// uint32_t get_curr_id() const { return curr_id_; } //-----------------------------------------------------------------// /*! @brief 基準電流を取得 [A] @return 基準電流 */ //-----------------------------------------------------------------// float get_ref_curr() const { return refc_; } //-----------------------------------------------------------------// /*! @brief 電流を取得 [A] @return 電流 */ //-----------------------------------------------------------------// float get_curr() const { auto a = curr_ - refc_; // 負電流の場合は、絶対値にしとく・・ if(a < 0.0f) a = std::abs(a); return a; } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { char tmp[256]; auto rl = serial_.read(tmp, sizeof(tmp)); for(uint32_t i = 0; i < rl; ++i) { char ch = tmp[i]; fifo_.put(ch); } switch(task_) { case task::state: if(get_text_()) { idn_ = rt_; task_ = task::refc; } else { if(loop_ > 0) { --loop_; } else { timeout_ = true; task_ = task::idle; } } break; case task::refc: set_output(1); refc_wait_ = 90; task_ = task::refc_wait; break; case task::refc_wait: if(refc_wait_ > 0) { refc_wait_--; } else { std::string s = "MEAS:CURR:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::refc_sync; } break; case task::refc_sync: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % refc_).status()) { } std::cout << "Kikusui ref [A]: " << refc_ << std::endl; set_output(0); task_ = task::idle; } break; case task::volt: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % volt_).status()) { ++volt_id_; } task_ = task::idle; } break; case task::curr: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % curr_).status()) { ++curr_id_; } task_ = task::idle; } break; case task::idle: default: while(fifo_.length() > 0) { fifo_.get(); } break; } } }; } <commit_msg>update: kikusui manage for external sense<commit_after>#pragma once //=====================================================================// /*! @file @brief 菊水電源インターフェース・クラス @n ※0.14 mA 以下の電流を測定出来ない為、停電流源による下駄を @n 履かせている。@n その為、起動時に定電流源の基準を測定している。 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <boost/format.hpp> #include "utils/serial_win32.hpp" #include "utils/fixed_fifo.hpp" #include "utils/input.hpp" #include "utils/string_utils.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 菊水電源インターフェース・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class kikusui { device::serial_win32& serial_; typedef utils::fixed_fifo<char, 1024> FIFO; FIFO fifo_; enum class task { idle, state, ///< 菊水の電源が接続されているか? refc, ///< 下駄を履かせた分の基準電流の測定 refc_wait, refc_sync, volt, curr, }; task task_; float volt_; float curr_; uint32_t volt_id_; uint32_t curr_id_; uint32_t loop_; bool timeout_; uint32_t refc_wait_; float refc_; std::string rt_; std::string idn_; bool get_text_() { while(fifo_.length() > 0) { auto ch = fifo_.get(); if(ch == '\n') { return true; } else if(ch != '\r') { rt_ += ch; } } return false; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// kikusui(device::serial_win32& serial) : serial_(serial), fifo_(), task_(task::idle), volt_(0.0f), curr_(0.0f), volt_id_(0), curr_id_(0), loop_(0), timeout_(false), refc_wait_(0), refc_(0.0f), idn_() { } //-----------------------------------------------------------------// /*! @brief 開始 */ //-----------------------------------------------------------------// void start() { std::string s = "INST:NSEL 6;*IDN?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::state; loop_ = 60; // *IDN? time out 1 sec } //-----------------------------------------------------------------// /*! @brief IDN の取得 @return IDN */ //-----------------------------------------------------------------// const std::string& get_idn() const { return idn_; } //-----------------------------------------------------------------// /*! @brief 停止 */ //-----------------------------------------------------------------// void stop() { std::string s = "CURR 0 A\r\n"; serial_.write(s.c_str(), s.size()); s = "VOLT 0 V\r\n"; serial_.write(s.c_str(), s.size()); s = "OUTP 0\r\n"; serial_.write(s.c_str(), s.size()); } //-----------------------------------------------------------------// /*! @brief 出力設定 @param[in] ena 許可の場合「true」 */ //-----------------------------------------------------------------// void set_output(bool ena) { std::string s; if(ena) { s = "OUTP 1\r\n"; } else { s = "OUTP 0\r\n"; } serial_.write(s.c_str(), s.size()); // std::cout << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電圧設定 @param[in] volt 設定電圧 @param[in] curr 最大電流 */ //-----------------------------------------------------------------// void set_volt(float volt, float curr) { auto s = (boost::format("CURR %5.4f A;VOLT %5.4f V\r\n") % (curr + refc_) % (volt - 0.09f)).str(); serial_.write(s.c_str(), s.size()); // std::cout << "VOLT: " << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電流設定 @param[in] curr 設定電流 @param[in] volt 最大電圧 */ //-----------------------------------------------------------------// void set_curr(float curr, float volt) { auto s = (boost::format("VOLT %5.4f V;CURR %5.4f A\r\n") % volt % (curr + refc_)).str(); serial_.write(s.c_str(), s.size()); // std::cout << "CURR: " << s << std::flush; } //-----------------------------------------------------------------// /*! @brief 電圧測定要求 */ //-----------------------------------------------------------------// void req_volt() { std::string s = "MEAS:VOLT:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::volt; } //-----------------------------------------------------------------// /*! @brief 電流測定要求 */ //-----------------------------------------------------------------// void req_curr() { std::string s = "MEAS:CURR:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::curr; } //-----------------------------------------------------------------// /*! @brief 電圧 ID を取得 @return 電圧 ID */ //-----------------------------------------------------------------// uint32_t get_volt_id() const { return volt_id_; } //-----------------------------------------------------------------// /*! @brief 電圧を取得 [V] @return 電圧 */ //-----------------------------------------------------------------// float get_volt() const { return volt_ + 0.09f; } //-----------------------------------------------------------------// /*! @brief 電流 ID を取得 @return 電流 ID */ //-----------------------------------------------------------------// uint32_t get_curr_id() const { return curr_id_; } //-----------------------------------------------------------------// /*! @brief 基準電流を取得 [A] @return 基準電流 */ //-----------------------------------------------------------------// float get_ref_curr() const { return refc_; } //-----------------------------------------------------------------// /*! @brief 電流を取得 [A] @return 電流 */ //-----------------------------------------------------------------// float get_curr() const { auto a = curr_ - refc_; // 負電流の場合は、絶対値にしとく・・ if(a < 0.0f) a = std::abs(a); return a; } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { char tmp[256]; auto rl = serial_.read(tmp, sizeof(tmp)); for(uint32_t i = 0; i < rl; ++i) { char ch = tmp[i]; fifo_.put(ch); } switch(task_) { case task::state: if(get_text_()) { idn_ = rt_; // 定電流源は正確なので測定は省く(4.0206mA) refc_ = 4.0206e-3; // task_ = task::refc; task_ = task::idle; } else { if(loop_ > 0) { --loop_; } else { timeout_ = true; task_ = task::idle; } } break; case task::refc: set_output(1); refc_wait_ = 90; task_ = task::refc_wait; break; case task::refc_wait: if(refc_wait_ > 0) { refc_wait_--; } else { std::string s = "MEAS:CURR:DC?\r\n"; serial_.write(s.c_str(), s.size()); rt_.clear(); task_ = task::refc_sync; } break; case task::refc_sync: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % refc_).status()) { } std::cout << "Kikusui ref [A]: " << refc_ << std::endl; set_output(0); task_ = task::idle; } break; case task::volt: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % volt_).status()) { ++volt_id_; } task_ = task::idle; } break; case task::curr: if(get_text_()) { if((utils::input("%f", rt_.c_str()) % curr_).status()) { ++curr_id_; } task_ = task::idle; } break; case task::idle: default: while(fifo_.length() > 0) { fifo_.get(); } break; } } }; } <|endoftext|>
<commit_before>#include <boost/program_options.hpp> #include <iostream> #include "parsed_args.h" #include "test_gpucode.h" #define N_ITERS 10 #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> namespace ut = boost::unit_test; namespace po = boost::program_options; parsed_args p_args; //forward declaration void boost_loop_test(void (*func)()); //TODO: when we are running with a boost version > 1.58, start using UTF //datasets with BOOST_PARAM_TEST_CASE BOOST_AUTO_TEST_SUITE(gpucode) BOOST_AUTO_TEST_CASE(interaction_energy) { void (*interaction_energy_ptr)() = &test_interaction_energy; boost_loop_test(interaction_energy_ptr); } BOOST_AUTO_TEST_CASE(eval_intra) { void (*eval_intra_ptr)() = &test_eval_intra; boost_loop_test(eval_intra_ptr); } BOOST_AUTO_TEST_SUITE_END() bool init_unit_test() { std::string logname; unsigned seed; po::positional_options_description positional; po::options_description inputs("Input"); inputs.add_options() ("seed", po::value<unsigned>(&p_args.seed), "seed for random number generator") ("log", po::value<std::string>(&logname), "specify logfile, default is test.log"); po::options_description desc, desc_simple; desc.add(inputs); desc_simple.add(inputs); po::variables_map vm; try { po::store( po::command_line_parser(ut::framework::master_test_suite().argc, ut::framework::master_test_suite().argv).options(desc) .style( po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .positional(positional).run(), vm); notify(vm); } catch (po::error& e) { std::cerr << "Command line parse error: " << e.what() << '\n' << "\nCorrect usage:\n" << desc_simple << '\n'; return false; } if (!vm.count("seed")) { p_args.seed = std::random_device()(); p_args.many_iters = true; } if (!vm.count("log")) logname = "test.log"; p_args.log.init(logname); p_args.params = {p_args.seed}; if (p_args.many_iters) for (size_t i=0; i<N_ITERS; ++i) p_args.params.push_back(std::random_device()()); return true; } int main(int argc, char* argv[]) { //TODO: de-uglify //The following exists so that passing --help prints both the UTF help and our //specific program options unsigned dummy1; std::string dummy2; bool dummy3 = true; po::positional_options_description positional; po::options_description _inputs("Input"); _inputs.add_options() ("seed,s", po::value<unsigned>(&dummy1), "seed for random number generator") ("log", po::value<std::string>(&dummy2), "specify logfile, default is test.log"); po::options_description _info("Information"); _info.add_options() ("help", po::bool_switch(&dummy3), "print usage information"); po::options_description desc, desc_simple; desc.add(_inputs).add(_info); desc_simple.add(_inputs).add(_info); std::vector<std::string> raw_input(argv, argv + argc); for (auto& arg : raw_input) { if (arg.find("help") != std::string::npos) { std::cout << desc_simple << '\n'; break; } } return ut::unit_test_main( &init_unit_test, argc, argv ); } <commit_msg>Trivial changes to test harness.<commit_after>#include <boost/program_options.hpp> #include <iostream> #include "parsed_args.h" #include "test_gpucode.h" #define N_ITERS 10 #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> namespace ut = boost::unit_test; namespace po = boost::program_options; parsed_args p_args; void boost_loop_test(void (*func)()); //TODO: when we are running with a boost version > 1.58, start using UTF //datasets with BOOST_PARAM_TEST_CASE BOOST_AUTO_TEST_SUITE(gpucode) BOOST_AUTO_TEST_CASE(interaction_energy) { boost_loop_test(&test_interaction_energy); } BOOST_AUTO_TEST_CASE(eval_intra) { boost_loop_test(&test_eval_intra); } BOOST_AUTO_TEST_SUITE_END() bool init_unit_test() { std::string logname; unsigned seed; po::positional_options_description positional; po::options_description inputs("Input"); inputs.add_options() ("seed", po::value<unsigned>(&p_args.seed), "seed for random number generator") ("log", po::value<std::string>(&logname), "specify logfile, default is test.log"); po::options_description desc, desc_simple; desc.add(inputs); desc_simple.add(inputs); po::variables_map vm; try { po::store( po::command_line_parser(ut::framework::master_test_suite().argc, ut::framework::master_test_suite().argv).options(desc) .style( po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .positional(positional).run(), vm); notify(vm); } catch (po::error& e) { std::cerr << "Command line parse error: " << e.what() << '\n' << "\nCorrect usage:\n" << desc_simple << '\n'; return false; } if (!vm.count("seed")) { p_args.seed = std::random_device()(); p_args.many_iters = true; } if (!vm.count("log")) logname = "test.log"; p_args.log.init(logname); p_args.params = {p_args.seed}; if (p_args.many_iters) for (size_t i=0; i<N_ITERS; ++i) p_args.params.push_back(std::random_device()()); return true; } int main(int argc, char* argv[]) { //The following exists so that passing --help prints both the UTF help and our //specific program options - I can't see any way of doing this without //parsing the args twice, because UTF chomps args it thinks it owns unsigned _dumvar1; std::string _dumvar2; bool help = false; po::positional_options_description positional; po::options_description inputs("Input"); inputs.add_options() ("seed,s", po::value<unsigned>(&_dumvar1), "seed for random number generator") ("log", po::value<std::string>(&_dumvar2), "specify logfile, default is test.log"); po::options_description info("Information"); info.add_options() ("help", po::bool_switch(&help), "print usage information"); po::options_description desc, desc_simple; desc.add(inputs).add(info); desc_simple.add(inputs).add(info); po::variables_map vm; try { po::store( po::command_line_parser(argc, argv).options(desc) .style( po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .positional(positional).run(), vm); notify(vm); } catch (po::error& e) { } if (help) std::cout << desc_simple << '\n'; return ut::unit_test_main( &init_unit_test, argc, argv ); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \author ([email protected]) \date 07.03.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/expression.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/procedural/calc_const.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- Expression // -------------------------------------------------------------------------------- Expression::Expression(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(RDOParserSrcInfo) src_info) : m_pType(pType) , m_pCalc(pCalc) { ASSERT(m_pType); if (m_pCalc) { rdo::runtime::LPRDOCalcConst pConstCalc = m_pCalc.object_dynamic_cast<rdo::runtime::RDOCalcConst>(); if (pConstCalc) { m_pValue = rdo::Factory<RDOValue>::create(pConstCalc->getValue(), src_info, m_pType); } } setSrcInfo(src_info); } Expression::Expression(CREF(LPRDOValue) pValue) : m_pType (pValue->typeInfo()) , m_pValue(pValue ) { ASSERT(pValue); ASSERT(pValue->constant()); m_pCalc = rdo::Factory<rdo::runtime::RDOCalcConst>::create(pValue->value()); ASSERT(m_pCalc); setSrcInfo(pValue->src_info()); } Expression::Expression(CREF(LPExpression) pExpression) : m_pType (pExpression->m_pType ) , m_pCalc (pExpression->m_pCalc ) , m_pValue(pExpression->m_pValue) {} Expression::~Expression() {} CREF(LPTypeInfo) Expression::typeInfo() const { return m_pType; } CREF(rdo::runtime::LPRDOCalc) Expression::calc() const { return m_pCalc; } void Expression::setSrcInfo(CREF(RDOParserSrcInfo) src_info) { RDOParserSrcInfo::setSrcInfo(src_info); if (m_pCalc) { m_pCalc->setSrcInfo(src_info); } } LPRDOValue Expression::constant() const { if (m_pValue) { return m_pValue; } return LPRDOValue(NULL); } // -------------------------------------------------------------------------------- // -------------------- ExpressionStatement // -------------------------------------------------------------------------------- ExpressionStatement::ExpressionStatement(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(rdo::runtime::RDOSrcInfo) src_info) :Expression (pType, pCalc, src_info), m_returnFlag(true ) {} ExpressionStatement::ExpressionStatement(CREF(LPExpression) pExpression) :Expression (pExpression), m_returnFlag(true ) {} ExpressionStatement::~ExpressionStatement() {} rbool ExpressionStatement::getReturn() { return m_returnFlag; } CLOSE_RDO_PARSER_NAMESPACE <commit_msg>* revert changes from rev.8974<commit_after>/*! \copyright (c) RDO-Team, 2011 \file expression.cpp \author ([email protected]) \date 07.03.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/expression.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/procedural/calc_const.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- Expression // -------------------------------------------------------------------------------- Expression::Expression(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(RDOParserSrcInfo) src_info) : m_pType(pType) , m_pCalc(pCalc) { ASSERT(m_pType); if (m_pCalc) { rdo::runtime::LPRDOCalcConst pConstCalc = m_pCalc.object_dynamic_cast<rdo::runtime::RDOCalcConst>(); if (pConstCalc) { m_pValue = rdo::Factory<RDOValue>::create(pConstCalc->getValue(), src_info, m_pType); } } setSrcInfo(src_info); } Expression::Expression(CREF(LPRDOValue) pValue) : m_pType (pValue->typeInfo()) , m_pValue(pValue ) { ASSERT(pValue); ASSERT(pValue->constant()); m_pCalc = rdo::Factory<rdo::runtime::RDOCalcConst>::create(pValue->value()); ASSERT(m_pCalc); setSrcInfo(pValue->src_info()); } Expression::Expression(CREF(LPExpression) pExpression) : m_pType (pExpression->m_pType ) , m_pCalc (pExpression->m_pCalc ) , m_pValue(pExpression->m_pValue) {} Expression::~Expression() {} CREF(LPTypeInfo) Expression::typeInfo() const { return m_pType; } CREF(rdo::runtime::LPRDOCalc) Expression::calc() const { return m_pCalc; } void Expression::setSrcInfo(CREF(RDOParserSrcInfo) src_info) { RDOParserSrcInfo::setSrcInfo(src_info); if (m_pCalc) { m_pCalc->setSrcInfo(src_info); } } LPRDOValue Expression::constant() const { if (m_pValue) { return m_pValue; } return LPRDOValue(NULL); } // -------------------------------------------------------------------------------- // -------------------- ExpressionStatement // -------------------------------------------------------------------------------- ExpressionStatement::ExpressionStatement(CREF(LPTypeInfo) pType, CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(rdo::runtime::RDOSrcInfo) src_info) :Expression (pType, pCalc, src_info), m_returnFlag(true ) {} ExpressionStatement::ExpressionStatement(CREF(LPExpression) pExpression) :Expression (pExpression), m_returnFlag(true ) {} ExpressionStatement::~ExpressionStatement() {} rbool ExpressionStatement::getReturn() { return m_returnFlag; } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>/* ** Copyright 2009-2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/notification/action.hh" #include "com/centreon/broker/notification/state.hh" #include "com/centreon/broker/notification/process_manager.hh" using namespace com::centreon::broker::notification; using namespace com::centreon::broker::notification::objects; using namespace com::centreon::broker::time; /** * Default constructor. */ action::action() : _act(action::unknown), _forwarded_action(action::unknown), _id(), _notification_rule_id(0), _notification_number(0), _at(0) {} /** * Copy constructor. * * @param[in] obj The object to be copied. */ action::action(action const& obj) { action::operator=(obj); } /** * Assignment operator. * * @param[in] obj The object to be copied. * * @return A reference to this object. */ action& action::operator=(action const& obj) { if (this != &obj) { _act = obj._act; _id = obj._id; _notification_rule_id = obj._notification_rule_id; _notification_number = obj._notification_number; _at = obj._at; _forwarded_action = obj._forwarded_action; } return (*this); } /** * Equality operator. * * @param[in] obj The object from which to test equality. * * @return True if the two objects are equal. */ bool action::operator==(action const& obj) const { return (_act == obj._act && _id == obj._id && _notification_rule_id == obj._notification_rule_id && _notification_number == obj._notification_number && _at == obj._at && _forwarded_action == obj._forwarded_action); } /** * Comparison operator. * * @param[in] obj The compared object. * * @return True if this object is less than the other. */ bool action::operator<(action const& obj) const { if (_act != obj._act) return (_act < obj._act); else if(_id != obj._id) return (_id < obj._id); else if (_notification_rule_id != obj._notification_rule_id) return (_notification_rule_id < obj._notification_rule_id); else if (_notification_number != obj._notification_number) return (_notification_number < obj._notification_number); else if (_at != obj._at) return (_at < obj._at); else return (_forwarded_action < obj._forwarded_action); } /** * Get the type of this action. * * @return[in] The type of this action. */ action::action_type action::get_type() const throw() { return (_act); } /** * Set the type of this action. * * @param[in] type The type of this action. */ void action::set_type(action_type type) throw() { _act = type; } /** * Get the forwarded type. * * @return The forwarded type. */ action::action_type action::get_forwarded_type() const throw() { return (_forwarded_action); } /** * Set the forwarded type. * * @param[in] type The forwarded type. */ void action::set_forwarded_type(action_type type) throw() { _forwarded_action = type; } /** * Get the node id associated with this action. * * @return The node id associated with this action. */ node_id action::get_node_id() const throw() { return (_id); } /** * Set the node id associated with this actions. * * @param[in] id The node id associated with this action. */ void action::set_node_id(objects::node_id id) throw() { _id = id; } /** * Get the notification rule ID. * * @return Notification rule ID. */ unsigned int action::get_notification_rule_id() const throw () { return (_notification_rule_id); } /** * Set the notification rule ID. * * @param[in] id Notification rule ID. */ void action::set_notification_rule_id(unsigned int id) throw () { _notification_rule_id = id; return ; } /** * Get the notification number. * * @return Current notification number. */ unsigned int action::get_notification_number() const throw () { return (_notification_number); } /** * Set the notification number. * * @param[in] num Notification number. */ void action::set_notification_number(unsigned int num) throw () { _notification_number = num; return ; } /** * Get the scheduled time of this action. * * @return The scheduled time of this action. */ time_t action::get_at() const throw() { return (_at); } /** * Set the scheduled time of this action. * * @param[in] at The scheduled time of this action. */ void action::set_at(time_t at) throw() { _at = at; } /** * @brief Process the action. * * What is done changes based on the type of this notification. * * @param[in] state The notification state of the engine. * @param[in] cache The data cache of the module. * @param[out] spawned_actions The actions to add to the queue after the processing. * */ void action::process_action( state& st, node_cache& cache, std::vector<std::pair<time_t, action> >& spawned_actions) const { if (_act == unknown || _id == node_id()) return; if (_act == notification_processing) _spawn_notification_attempts(st, spawned_actions); else _process_notification(st, cache, spawned_actions); } /** * @brief Spawn the notification attempts from a notification processing. * * A notification processing spawn one notification attempt for each rule * associated to a particular node. * * @param[in] st The notification state of the engine. * @param[out] spawned_actions The actions to add to the queue after the processing. */ void action::_spawn_notification_attempts( state& st, std::vector<std::pair<time_t, action> >& spawned_actions) const{ logging::debug(logging::low) << "notification: spawning notification action for node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Spawn an action for each rules. QList<notification_rule::ptr> rules = st.get_notification_rules_by_node(_id); for (QList<notification_rule::ptr>::iterator it(rules.begin()), end(rules.end()); it != end; ++it) { // Build action (viability checks will be made later. action a; a.set_node_id(_id); a.set_type(_forwarded_action); a.set_notification_rule_id((*it)->get_id()); a.set_notification_number(1); // Choose running time. time_t at; timeperiod::ptr tp = st.get_timeperiod_by_id((*it)->get_timeperiod_id()); if (tp) at = tp->get_next_valid(::time(NULL)); else at = ::time(NULL); spawned_actions.push_back(std::make_pair(at, a)); } return ; } /** * Process a notification attempt. * * @param[in] st The notification state of the engine. * @param[in] cache The data cache of the module. * @param[out] spawned_actions The action to add to the queue after the processing. */ void action::_process_notification( state& st, node_cache& cache, std::vector<std::pair<time_t, action> >& spawned_actions) const { logging::debug(logging::low) << "notification: processing action for rule " << _notification_rule_id << " of node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Check action viability. logging::debug(logging::low) << "notification: checking action viability for node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Check the node's existence. node::ptr n(st.get_node_by_id(_id)); if (!n) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id () << ", " << _id.get_service_id() << ") was not declared, notification attempt is not viable"; return ; } // Get all the necessary data. notification_rule::ptr rule = st.get_notification_rule_by_id(_notification_rule_id); if (!rule) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): rule " << _notification_rule_id << " does not exist"; return ; } timeperiod::ptr tp = st.get_timeperiod_by_id(rule->get_timeperiod_id()); if (!tp) logging::error(logging::low) << "notification: could not find timeperiod " << rule->get_timeperiod_id() << " during notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "), so any time will be valid"; notification_method::ptr method = st.get_notification_method_by_id(rule->get_method_id()); if (!method) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): method " << rule->get_method_id() << " does not exist"; return ; } contact::ptr cnt = st.get_contact_by_id(rule->get_contact_id()); if (!cnt) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): contact " << rule->get_contact_id() << " does not exist"; return ; } command::ptr cmd = st.get_command_by_id(method->get_command_id()); if (!cmd) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): command " << method->get_command_id() << " does not exist"; return ; } // Check the existence of correlated parent. if (n->has_parent() && !method->should_be_notified_when_correlated()) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") has parent issue, notification attempt is not viable"; return ; } // Check if the state is valid. if (!method->should_be_notified_for( n->get_hard_state(), n->get_node_id().is_service())) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") should not be notified for state " << static_cast<int>(n->get_hard_state()) << " according to method " << rule->get_method_id(); return ; } // Check if the notification type is valid. if (!method->should_be_notified_for(_act)) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") should not be notified for action type " << static_cast<int>(_act) << " according to method " << rule->get_method_id(); return ; } // See if the timeperiod is valid. time_t now = ::time(NULL); if (tp && !tp->is_valid(now)) { logging::debug(logging::low) << "notification: notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is not in a valid timeperiod, " "rescheduling it at the next valid time"; spawned_actions.push_back(std::make_pair(tp->get_next_valid(now), *this)); return ; } bool should_send_the_notification = true; action next = *this; next.set_notification_number(_notification_number + 1); // See if the node is in downtime. if (_act == notification_attempt && cache.node_in_downtime(_id) == true) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is in downtime, notification won't be sent"; should_send_the_notification = false; return; } // See if the node has been acknowledged. if (_act == notification_attempt && cache.node_acknowledged(_id) == true) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is acknowledged, notification won't be sent"; should_send_the_notification = false; return ; } // See if this notification is between the start and end. if (_notification_number < method->get_start() || (_notification_number >= method->get_end() && method->get_end())) { logging::debug(logging::medium) << "notification: notification number of node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is " << _notification_number << " and not in the method's valid range ([" << method->get_start() << "-" << method->get_end() << "])"; should_send_the_notification = false; } // Send the notification. if (should_send_the_notification) { std::string resolved_command = cmd->resolve(cnt, n, cache, st, *this); logging::debug(logging::low) << "notification: launching notification command on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): " << resolved_command; process_manager& manager = process_manager::instance(); manager.create_process(resolved_command); } // Create the next notification. if (_act == notification_attempt) spawned_actions.push_back(std::make_pair(now + method->get_interval(), next)); } <commit_msg>Notification: Continue trying to send notification even if the node is in downtime/ack.<commit_after>/* ** Copyright 2009-2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/notification/action.hh" #include "com/centreon/broker/notification/state.hh" #include "com/centreon/broker/notification/process_manager.hh" using namespace com::centreon::broker::notification; using namespace com::centreon::broker::notification::objects; using namespace com::centreon::broker::time; /** * Default constructor. */ action::action() : _act(action::unknown), _forwarded_action(action::unknown), _id(), _notification_rule_id(0), _notification_number(0), _at(0) {} /** * Copy constructor. * * @param[in] obj The object to be copied. */ action::action(action const& obj) { action::operator=(obj); } /** * Assignment operator. * * @param[in] obj The object to be copied. * * @return A reference to this object. */ action& action::operator=(action const& obj) { if (this != &obj) { _act = obj._act; _id = obj._id; _notification_rule_id = obj._notification_rule_id; _notification_number = obj._notification_number; _at = obj._at; _forwarded_action = obj._forwarded_action; } return (*this); } /** * Equality operator. * * @param[in] obj The object from which to test equality. * * @return True if the two objects are equal. */ bool action::operator==(action const& obj) const { return (_act == obj._act && _id == obj._id && _notification_rule_id == obj._notification_rule_id && _notification_number == obj._notification_number && _at == obj._at && _forwarded_action == obj._forwarded_action); } /** * Comparison operator. * * @param[in] obj The compared object. * * @return True if this object is less than the other. */ bool action::operator<(action const& obj) const { if (_act != obj._act) return (_act < obj._act); else if(_id != obj._id) return (_id < obj._id); else if (_notification_rule_id != obj._notification_rule_id) return (_notification_rule_id < obj._notification_rule_id); else if (_notification_number != obj._notification_number) return (_notification_number < obj._notification_number); else if (_at != obj._at) return (_at < obj._at); else return (_forwarded_action < obj._forwarded_action); } /** * Get the type of this action. * * @return[in] The type of this action. */ action::action_type action::get_type() const throw() { return (_act); } /** * Set the type of this action. * * @param[in] type The type of this action. */ void action::set_type(action_type type) throw() { _act = type; } /** * Get the forwarded type. * * @return The forwarded type. */ action::action_type action::get_forwarded_type() const throw() { return (_forwarded_action); } /** * Set the forwarded type. * * @param[in] type The forwarded type. */ void action::set_forwarded_type(action_type type) throw() { _forwarded_action = type; } /** * Get the node id associated with this action. * * @return The node id associated with this action. */ node_id action::get_node_id() const throw() { return (_id); } /** * Set the node id associated with this actions. * * @param[in] id The node id associated with this action. */ void action::set_node_id(objects::node_id id) throw() { _id = id; } /** * Get the notification rule ID. * * @return Notification rule ID. */ unsigned int action::get_notification_rule_id() const throw () { return (_notification_rule_id); } /** * Set the notification rule ID. * * @param[in] id Notification rule ID. */ void action::set_notification_rule_id(unsigned int id) throw () { _notification_rule_id = id; return ; } /** * Get the notification number. * * @return Current notification number. */ unsigned int action::get_notification_number() const throw () { return (_notification_number); } /** * Set the notification number. * * @param[in] num Notification number. */ void action::set_notification_number(unsigned int num) throw () { _notification_number = num; return ; } /** * Get the scheduled time of this action. * * @return The scheduled time of this action. */ time_t action::get_at() const throw() { return (_at); } /** * Set the scheduled time of this action. * * @param[in] at The scheduled time of this action. */ void action::set_at(time_t at) throw() { _at = at; } /** * @brief Process the action. * * What is done changes based on the type of this notification. * * @param[in] state The notification state of the engine. * @param[in] cache The data cache of the module. * @param[out] spawned_actions The actions to add to the queue after the processing. * */ void action::process_action( state& st, node_cache& cache, std::vector<std::pair<time_t, action> >& spawned_actions) const { if (_act == unknown || _id == node_id()) return; if (_act == notification_processing) _spawn_notification_attempts(st, spawned_actions); else _process_notification(st, cache, spawned_actions); } /** * @brief Spawn the notification attempts from a notification processing. * * A notification processing spawn one notification attempt for each rule * associated to a particular node. * * @param[in] st The notification state of the engine. * @param[out] spawned_actions The actions to add to the queue after the processing. */ void action::_spawn_notification_attempts( state& st, std::vector<std::pair<time_t, action> >& spawned_actions) const{ logging::debug(logging::low) << "notification: spawning notification action for node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Spawn an action for each rules. QList<notification_rule::ptr> rules = st.get_notification_rules_by_node(_id); for (QList<notification_rule::ptr>::iterator it(rules.begin()), end(rules.end()); it != end; ++it) { // Build action (viability checks will be made later. action a; a.set_node_id(_id); a.set_type(_forwarded_action); a.set_notification_rule_id((*it)->get_id()); a.set_notification_number(1); // Choose running time. time_t at; timeperiod::ptr tp = st.get_timeperiod_by_id((*it)->get_timeperiod_id()); if (tp) at = tp->get_next_valid(::time(NULL)); else at = ::time(NULL); spawned_actions.push_back(std::make_pair(at, a)); } return ; } /** * Process a notification attempt. * * @param[in] st The notification state of the engine. * @param[in] cache The data cache of the module. * @param[out] spawned_actions The action to add to the queue after the processing. */ void action::_process_notification( state& st, node_cache& cache, std::vector<std::pair<time_t, action> >& spawned_actions) const { logging::debug(logging::low) << "notification: processing action for rule " << _notification_rule_id << " of node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Check action viability. logging::debug(logging::low) << "notification: checking action viability for node (" << _id.get_host_id() << ", " << _id.get_service_id() << ")"; // Check the node's existence. node::ptr n(st.get_node_by_id(_id)); if (!n) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id () << ", " << _id.get_service_id() << ") was not declared, notification attempt is not viable"; return ; } // Get all the necessary data. notification_rule::ptr rule = st.get_notification_rule_by_id(_notification_rule_id); if (!rule) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): rule " << _notification_rule_id << " does not exist"; return ; } timeperiod::ptr tp = st.get_timeperiod_by_id(rule->get_timeperiod_id()); if (!tp) logging::error(logging::low) << "notification: could not find timeperiod " << rule->get_timeperiod_id() << " during notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "), so any time will be valid"; notification_method::ptr method = st.get_notification_method_by_id(rule->get_method_id()); if (!method) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): method " << rule->get_method_id() << " does not exist"; return ; } contact::ptr cnt = st.get_contact_by_id(rule->get_contact_id()); if (!cnt) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): contact " << rule->get_contact_id() << " does not exist"; return ; } command::ptr cmd = st.get_command_by_id(method->get_command_id()); if (!cmd) { logging::error(logging::medium) << "notification: aborting notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): command " << method->get_command_id() << " does not exist"; return ; } // Check the existence of correlated parent. if (n->has_parent() && !method->should_be_notified_when_correlated()) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") has parent issue, notification attempt is not viable"; return ; } // Check if the state is valid. if (!method->should_be_notified_for( n->get_hard_state(), n->get_node_id().is_service())) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") should not be notified for state " << static_cast<int>(n->get_hard_state()) << " according to method " << rule->get_method_id(); return ; } // Check if the notification type is valid. if (!method->should_be_notified_for(_act)) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") should not be notified for action type " << static_cast<int>(_act) << " according to method " << rule->get_method_id(); return ; } // See if the timeperiod is valid. time_t now = ::time(NULL); if (tp && !tp->is_valid(now)) { logging::debug(logging::low) << "notification: notification attempt on node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is not in a valid timeperiod, " "rescheduling it at the next valid time"; spawned_actions.push_back(std::make_pair(tp->get_next_valid(now), *this)); return ; } bool should_send_the_notification = true; action next = *this; next.set_notification_number(_notification_number + 1); // See if the node is in downtime. if (_act == notification_attempt && cache.node_in_downtime(_id) == true) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is in downtime, notification won't be sent"; should_send_the_notification = false; } // See if the node has been acknowledged. if (_act == notification_attempt && cache.node_acknowledged(_id) == true) { logging::debug(logging::low) << "notification: node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is acknowledged, notification won't be sent"; should_send_the_notification = false; } // See if this notification is between the start and end. if (_notification_number < method->get_start() || (_notification_number >= method->get_end() && method->get_end())) { logging::debug(logging::medium) << "notification: notification number of node (" << _id.get_host_id() << ", " << _id.get_service_id() << ") is " << _notification_number << " and not in the method's valid range ([" << method->get_start() << "-" << method->get_end() << "])"; should_send_the_notification = false; } // Send the notification. if (should_send_the_notification) { std::string resolved_command = cmd->resolve(cnt, n, cache, st, *this); logging::debug(logging::low) << "notification: launching notification command on node (" << _id.get_host_id() << ", " << _id.get_service_id() << "): " << resolved_command; process_manager& manager = process_manager::instance(); manager.create_process(resolved_command); } // Create the next notification. if (_act == notification_attempt) spawned_actions.push_back(std::make_pair(now + method->get_interval(), next)); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/lib/p9_hcd_common.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_hcd_common.H /// @brief common hcode includes // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : SBE:SGPE:CME // *HWP Level : 2 #ifndef __P9_HCD_COMMON_H__ #define __P9_HCD_COMMON_H__ //------------------------- // Macros //------------------------- // Create a multi-bit mask of \a n bits starting at bit \a b #define BITS64(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b)) #define BITS32(b, n) ((0xffffffff << (32 - (n))) >> (b)) #define BITS16(b, n) ((0xffff << (16 - (n))) >> (b)) #define BITS8(b, n) ((0xff << (8 - (n))) >> (b)) // Create a single bit mask at bit \a b #define BIT64(b) BITS64((b), 1) #define BIT32(b) BITS32((b), 1) #define BIT16(b) BITS16((b), 1) #define BIT8(b) BITS8((b), 1) // Create a amount of shift to bit location \a b #define SHIFT64(b) (63-b) #define SHIFT32(b) (31-b) #define SHIFT16(b) (15-b) #define SHIFT8(b) (7-b) // The BUF_* macros apply operations to a newly constructed buffer #define BUF_SET(bit) fapi2::buffer<uint64_t>().setBit<bit>() #define BUF_UNSET(bit) fapi2::buffer<uint64_t>().flush<1>().clearBit<bit>() #define BUF_INSERT(start,size,val) \ fapi2::buffer<uint64_t>().insertFromRight<start,size>(val) #define BUF_REPLACE(start,size,val) \ fapi2::buffer<uint64_t>().flush<1>().insertFromRight<start,size>(val) // The following DATA_* and MASK_* macros assume you have // "fapi2::buffer<uint64_t> l_data64" declared // The DATA_* macros apply operations to a buffer contains existing data #define DATA_BIT(buf,op,bit) buf.op##Bit<bit>() #define DATA_SET(bit) DATA_BIT(l_data64,set,bit) #define DATA_UNSET(bit) DATA_BIT(l_data64,clear,bit) #define DATA_FIELD(buf,start,size,val) buf.insertFromRight<start,size>(val) #define DATA_INSERT(start,size,val) DATA_FIELD(l_data64,start,size,val) // The MASK_* macros apply operations to a buffer to create a new data mask // data previously stored in the buffer will be overwritten. #define MASK_FLUSH(buf,mask) buf.flush<mask>() #define MASK_ZERO MASK_FLUSH(l_data64,0) #define MASK_ALL MASK_FLUSH(l_data64,1) #define MASK_BIT(buf,mask,op,bit) buf.flush<mask>().op##Bit<bit>() #define MASK_SET(bit) MASK_BIT(l_data64,0,set,bit) #define MASK_UNSET(bit) MASK_BIT(l_data64,1,clear,bit) #define MASK_FIELD(buf,mask,start,size,val) \ buf.flush<mask>().insertFromRight<start,size>(val) #define MASK_OR(start,size,val) MASK_FIELD(l_data64,0,start,size,val) #define MASK_AND(start,size,val) MASK_FIELD(l_data64,1,start,size,val) #define MASK_CLR(start,size,val) MASK_FIELD(l_data64,0,start,size,val) //------------------------- // Constants //------------------------- namespace p9hcd { // Bit masks used by CME hcode enum P9_HCD_CME_CORE_MASKS { LEFT_CORE = 0x2, RIGHT_CORE = 0x1, BOTH_CORES = 0x3, NO_CORE = 0x0 }; // Control parameters for PCB Aribter enum P9_HCD_PCB_ARBITER_CTRL { REQUEST_ARBITER = 1, RELEASE_ARBITER = 0 }; // Constants to calculate hcd poll timeout intervals enum P9_HCD_TIMEOUT_CONSTANTS { CYCLES_PER_MS = 500000, // PPE FREQ 500MHZ INSTS_PER_POLL_LOOP = 8 // }; // Constants to calculate the delay in nanoseconds or simcycles // Source | Domain | Freq | cyc/ns | Period | // DPLL | Core | 4GHz | 4 | 250ps | // | Cache | 2GHz | 2 | 500ps | // | PPE | 500MHz | 0.5 | 2ns | // Refclk | Refclk | 100Mhz | 0.1 | 10ns | enum P9_HCD_DELAY_CONSTANTS { SIM_CYCLE_1U1D = 2, // fastest internal oscillator SIM_CYCLE_4U4D = 8, // 4Ghz ideal dpll SIM_CYCLE_150UD = 300, // 133Mhz refclk SIM_CYCLE_200UD = 400, // 100Mhz refclk external oscillator CLK_PERIOD_250PS = 250, // 4GHZ dpll CLK_PERIOD_10NS = 10, // 100Mhz refclk CLK_PERIOD_CORE2CACHE = 2, CLK_PERIOD_CORE2PPE = 8, CLK_PERIOD_CORE2REF = 40 }; // Chip Position Constants enum P9_HCD_CHIP_POS_CONSTANTS { PERV_TO_EQ_POS_OFFSET = 0x10, PERV_TO_CORE_POS_OFFSET = 0x20 }; // EX Constants enum P9_HCD_EX_CTRL_CONSTANTS { ODD_EX = 1, EVEN_EX = 2, BOTH_EX = 3, QCSR_MASK_EX0 = (BIT64(0) | BIT64(2) | BIT64(4) | BIT64(6) | BIT64(8) | BIT64(10)), QCSR_MASK_EX1 = (BIT64(1) | BIT64(3) | BIT64(5) | BIT64(7) | BIT64(9) | BIT64(11)) }; // Multicast Constants enum P9_HCD_MULTICAST_CONSTANTS { MULTICAST_GROUP_4 = 4, // QUAD MULTICAST_GROUP_5 = 5, // EX0 MULTICAST_GROUP_6 = 6 // EX1 }; // Clock Control Constants enum P9_HCD_CLK_CTRL_CONSTANTS { CLK_STOP_CMD = BIT64(0), CLK_START_CMD = BIT64(1), CLK_REGION_ANEP = BIT64(10), CLK_REGION_DPLL = BIT64(14), CLK_REGION_REFR = BITS64(12, 2), CLK_REGION_L3_REFR = BITS64(6, 2) | BITS64(12, 2), CLK_REGION_EX0_L2_L3_REFR = BIT64(6) | BIT64(8) | BIT64(12), CLK_REGION_EX1_L2_L3_REFR = BIT64(7) | BIT64(9) | BIT64(13), CLK_REGION_ALL_BUT_L3_REFR = BITS64(4, 2) | BITS64(8, 4) | BIT64(14), CLK_REGION_ALL_BUT_L3_REFR_DPLL = BITS64(4, 2) | BITS64(8, 4), CLK_REGION_ALL_BUT_EX = BITS64(4, 2) | BITS64(10, 2) | BIT64(14), CLK_REGION_ALL_BUT_EX_DPLL = BITS64(4, 2) | BITS64(10, 2), CLK_REGION_ALL_BUT_EX_ANEP_DPLL = BITS64(4, 2) | BIT64(11), CLK_REGION_ALL_BUT_PLL = BITS64(4, 10), CLK_REGION_ALL = BITS64(4, 11), CLK_THOLD_ALL = BITS64(48, 3) }; // Scan Flush Constants enum P9_HCD_SCAN0_CONSTANTS { SCAN0_REGION_ALL = 0x7FF, SCAN0_REGION_ALL_BUT_PLL = 0x7FE, SCAN0_REGION_ALL_BUT_EX = 0x619, SCAN0_REGION_ALL_BUT_EX_DPLL = 0x618, SCAN0_REGION_ALL_BUT_EX_ANEP_DPLL = 0x608, SCAN0_REGION_EX0_L2_L3_REFR = 0x144, SCAN0_REGION_EX1_L2_L3_REFR = 0x0A2, SCAN0_TYPE_GPTR_REPR_TIME = 0x230, SCAN0_TYPE_ALL_BUT_GPTR_REPR_TIME = 0xDCF }; //OCC FLag defines enum PM_GPE_OCCFLG_DEFS { SGPE_ACTIVE = 8 }; // XSR defines enum XSR_DEFS { HALTED_STATE = 0 }; // XCR defines enum XCR_DEFS { CLEAR_DEBUG_STATUS = 0, HALT = 1, RESUME = 2, SINGLE_STEP = 3, TOGGLE_XSR_TRH = 4, SOFT_RESET = 5, HARD_RESET = 6, FORCE_HALT = 7 }; } // END OF NAMESPACE p9hcd #define P9_HCD_SCAN_FUNC_REPEAT 1 #define P9_HCD_SCAN_GPTR_REPEAT 1 /// @todo remove these once correct header contains them /// Scom addresses missing from p9_quad_scom_addresses.H #define EQ_QPPM_QCCR_WCLEAR EQ_QPPM_QCCR_SCOM1 #define EQ_QPPM_QCCR_WOR EQ_QPPM_QCCR_SCOM2 #define EX_0_CME_SCOM_SICR_CLEAR EX_0_CME_SCOM_SICR_SCOM1 #define EX_1_CME_SCOM_SICR_CLEAR EX_1_CME_SCOM_SICR_SCOM1 #define EX_0_CME_SCOM_SICR_OR EX_0_CME_SCOM_SICR_SCOM2 #define EX_1_CME_SCOM_SICR_OR EX_1_CME_SCOM_SICR_SCOM2 #define CME_LCL_SICR_OR 0xc0000510 #define CME_LCL_SICR_CLR 0xc0000518 #define CME_LCL_SISR 0xc0000520 #endif // __P9_HCD_COMMON_H__ <commit_msg>CORE/CACHE: core/cache/l2_stopclocks Level 2<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/lib/p9_hcd_common.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_hcd_common.H /// @brief common hcode includes // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : SBE:SGPE:CME // *HWP Level : 2 #ifndef __P9_HCD_COMMON_H__ #define __P9_HCD_COMMON_H__ //------------------------- // Macros //------------------------- // Create a multi-bit mask of \a n bits starting at bit \a b #define BITS64(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b)) #define BITS32(b, n) ((0xffffffff << (32 - (n))) >> (b)) #define BITS16(b, n) ((0xffff << (16 - (n))) >> (b)) #define BITS8(b, n) ((0xff << (8 - (n))) >> (b)) // Create a single bit mask at bit \a b #define BIT64(b) BITS64((b), 1) #define BIT32(b) BITS32((b), 1) #define BIT16(b) BITS16((b), 1) #define BIT8(b) BITS8((b), 1) // Create a amount of shift to bit location \a b #define SHIFT64(b) (63-b) #define SHIFT32(b) (31-b) #define SHIFT16(b) (15-b) #define SHIFT8(b) (7-b) // The BUF_* macros apply operations to a newly constructed buffer #define BUF_SET(bit) fapi2::buffer<uint64_t>().setBit<bit>() #define BUF_UNSET(bit) fapi2::buffer<uint64_t>().flush<1>().clearBit<bit>() #define BUF_INSERT(start,size,val) \ fapi2::buffer<uint64_t>().insertFromRight<start,size>(val) #define BUF_REPLACE(start,size,val) \ fapi2::buffer<uint64_t>().flush<1>().insertFromRight<start,size>(val) // The following DATA_* and MASK_* macros assume you have // "fapi2::buffer<uint64_t> l_data64" declared // The DATA_* macros apply operations to a buffer contains existing data #define DATA_BIT(buf,op,bit) buf.op##Bit<bit>() #define DATA_SET(bit) DATA_BIT(l_data64,set,bit) #define DATA_UNSET(bit) DATA_BIT(l_data64,clear,bit) #define DATA_FIELD(buf,start,size,val) buf.insertFromRight<start,size>(val) #define DATA_INSERT(start,size,val) DATA_FIELD(l_data64,start,size,val) // The MASK_* macros apply operations to a buffer to create a new data mask // data previously stored in the buffer will be overwritten. #define MASK_FLUSH(buf,mask) buf.flush<mask>() #define MASK_ZERO MASK_FLUSH(l_data64,0) #define MASK_ALL MASK_FLUSH(l_data64,1) #define MASK_BIT(buf,mask,op,bit) buf.flush<mask>().op##Bit<bit>() #define MASK_SET(bit) MASK_BIT(l_data64,0,set,bit) #define MASK_UNSET(bit) MASK_BIT(l_data64,1,clear,bit) #define MASK_FIELD(buf,mask,start,size,val) \ buf.flush<mask>().insertFromRight<start,size>(val) #define MASK_OR(start,size,val) MASK_FIELD(l_data64,0,start,size,val) #define MASK_AND(start,size,val) MASK_FIELD(l_data64,1,start,size,val) #define MASK_CLR(start,size,val) MASK_FIELD(l_data64,0,start,size,val) //------------------------- // Constants //------------------------- namespace p9hcd { // Bit masks used by CME hcode enum P9_HCD_CME_CORE_MASKS { LEFT_CORE = 0x2, RIGHT_CORE = 0x1, BOTH_CORES = 0x3, NO_CORE = 0x0 }; // Control parameters for PCB Aribter enum P9_HCD_PCB_ARBITER_CTRL { REQUEST_ARBITER = 1, RELEASE_ARBITER = 0 }; // Constants to calculate hcd poll timeout intervals enum P9_HCD_TIMEOUT_CONSTANTS { CYCLES_PER_MS = 500000, // PPE FREQ 500MHZ INSTS_PER_POLL_LOOP = 8 // }; // Constants to calculate the delay in nanoseconds or simcycles // Source | Domain | Freq | cyc/ns | Period | // DPLL | Core | 4GHz | 4 | 250ps | // | Cache | 2GHz | 2 | 500ps | // | PPE | 500MHz | 0.5 | 2ns | // Refclk | Refclk | 100Mhz | 0.1 | 10ns | enum P9_HCD_DELAY_CONSTANTS { SIM_CYCLE_1U1D = 2, // fastest internal oscillator SIM_CYCLE_4U4D = 8, // 4Ghz ideal dpll SIM_CYCLE_150UD = 300, // 133Mhz refclk SIM_CYCLE_200UD = 400, // 100Mhz refclk external oscillator CLK_PERIOD_250PS = 250, // 4GHZ dpll CLK_PERIOD_10NS = 10, // 100Mhz refclk CLK_PERIOD_CORE2CACHE = 2, CLK_PERIOD_CORE2PPE = 8, CLK_PERIOD_CORE2REF = 40 }; // Chip Position Constants enum P9_HCD_CHIP_POS_CONSTANTS { PERV_TO_EQ_POS_OFFSET = 0x10, PERV_TO_CORE_POS_OFFSET = 0x20 }; // EX Constants enum P9_HCD_EX_CTRL_CONSTANTS { ODD_EX = 1, EVEN_EX = 2, BOTH_EX = 3, QCSR_MASK_EX0 = (BIT64(0) | BIT64(2) | BIT64(4) | BIT64(6) | BIT64(8) | BIT64(10)), QCSR_MASK_EX1 = (BIT64(1) | BIT64(3) | BIT64(5) | BIT64(7) | BIT64(9) | BIT64(11)) }; // Multicast Constants enum P9_HCD_MULTICAST_CONSTANTS { MULTICAST_GROUP_4 = 4, // QUAD MULTICAST_GROUP_5 = 5, // EX0 MULTICAST_GROUP_6 = 6 // EX1 }; // Clock Control Constants enum P9_HCD_CLK_CTRL_CONSTANTS { CLK_STOP_CMD = BIT64(0), CLK_START_CMD = BIT64(1), CLK_REGION_ANEP = BIT64(10), CLK_REGION_DPLL = BIT64(14), CLK_REGION_REFR = BITS64(12, 2), CLK_REGION_L3_REFR = BITS64(6, 2) | BITS64(12, 2), CLK_REGION_EX0_L3 = BIT64(6), CLK_REGION_EX1_L3 = BIT64(7), CLK_REGION_EX0_L2 = BIT64(8), CLK_REGION_EX1_L2 = BIT64(9), CLK_REGION_EX0_REFR = BIT64(12), CLK_REGION_EX1_REFR = BIT64(13), CLK_REGION_EX0_L2_L3_REFR = BIT64(6) | BIT64(8) | BIT64(12), CLK_REGION_EX1_L2_L3_REFR = BIT64(7) | BIT64(9) | BIT64(13), CLK_REGION_ALL_BUT_L3_REFR = BITS64(4, 2) | BITS64(8, 4) | BIT64(14), CLK_REGION_ALL_BUT_L3_REFR_DPLL = BITS64(4, 2) | BITS64(8, 4), CLK_REGION_ALL_BUT_EX = BITS64(4, 2) | BITS64(10, 2) | BIT64(14), CLK_REGION_ALL_BUT_EX_DPLL = BITS64(4, 2) | BITS64(10, 2), CLK_REGION_ALL_BUT_EX_ANEP_DPLL = BITS64(4, 2) | BIT64(11), CLK_REGION_ALL_BUT_PLL = BITS64(4, 10), CLK_REGION_ALL = BITS64(4, 11), CLK_THOLD_ALL = BITS64(48, 3) }; // Scan Flush Constants enum P9_HCD_SCAN0_CONSTANTS { SCAN0_REGION_ALL = 0x7FF, SCAN0_REGION_ALL_BUT_PLL = 0x7FE, SCAN0_REGION_ALL_BUT_EX = 0x619, SCAN0_REGION_ALL_BUT_EX_DPLL = 0x618, SCAN0_REGION_ALL_BUT_EX_ANEP_DPLL = 0x608, SCAN0_REGION_EX0_L2_L3_REFR = 0x144, SCAN0_REGION_EX1_L2_L3_REFR = 0x0A2, SCAN0_TYPE_GPTR_REPR_TIME = 0x230, SCAN0_TYPE_ALL_BUT_GPTR_REPR_TIME = 0xDCF }; //OCC FLag defines enum PM_GPE_OCCFLG_DEFS { SGPE_ACTIVE = 8 }; // XSR defines enum XSR_DEFS { HALTED_STATE = 0 }; // XCR defines enum XCR_DEFS { CLEAR_DEBUG_STATUS = 0, HALT = 1, RESUME = 2, SINGLE_STEP = 3, TOGGLE_XSR_TRH = 4, SOFT_RESET = 5, HARD_RESET = 6, FORCE_HALT = 7 }; } // END OF NAMESPACE p9hcd #define P9_HCD_SCAN_FUNC_REPEAT 1 #define P9_HCD_SCAN_GPTR_REPEAT 1 /// @todo remove these once correct header contains them /// Scom addresses missing from p9_quad_scom_addresses.H #define PU_OCB_OCI_QSSR_CLEAR PU_OCB_OCI_QSSR_SCOM1 #define PU_OCB_OCI_QSSR_OR PU_OCB_OCI_QSSR_SCOM2 #define EQ_QPPM_QCCR_WCLEAR EQ_QPPM_QCCR_SCOM1 #define EQ_QPPM_QCCR_WOR EQ_QPPM_QCCR_SCOM2 #define EX_0_CME_SCOM_SICR_CLEAR EX_0_CME_SCOM_SICR_SCOM1 #define EX_1_CME_SCOM_SICR_CLEAR EX_1_CME_SCOM_SICR_SCOM1 #define EX_0_CME_SCOM_SICR_OR EX_0_CME_SCOM_SICR_SCOM2 #define EX_1_CME_SCOM_SICR_OR EX_1_CME_SCOM_SICR_SCOM2 #define CME_LCL_SICR_OR 0xc0000510 #define CME_LCL_SICR_CLR 0xc0000518 #define CME_LCL_SISR 0xc0000520 #endif // __P9_HCD_COMMON_H__ <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Mathieu Champlon * 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 copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_output_base_hpp #define xeumeuleu_output_base_hpp #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Output base */ // Created: MAT 2009-11-25 // ============================================================================= class output_base { public: //! @name Constructors/Destructor //@{ output_base() {} virtual ~output_base() {} //@} //! @name Operations //@{ virtual void start( const std::string& tag ) = 0; virtual void end() = 0; virtual void write( const std::string& value ) = 0; virtual void write( bool value ) = 0; virtual void write( int value ) = 0; virtual void write( long value ) = 0; virtual void write( long long value ) = 0; virtual void write( float value ) = 0; virtual void write( double value ) = 0; virtual void write( long double value ) = 0; virtual void write( unsigned int value ) = 0; virtual void write( unsigned long value ) = 0; virtual void write( unsigned long long value ) = 0; virtual void cdata( const std::string& value ) = 0; virtual void instruction( const std::string& target, const std::string& data ) = 0; virtual void attribute( const std::string& name, const std::string& value ) = 0; virtual void attribute( const std::string& name, bool value ) = 0; virtual void attribute( const std::string& name, int value ) = 0; virtual void attribute( const std::string& name, long value ) = 0; virtual void attribute( const std::string& name, long long value ) = 0; virtual void attribute( const std::string& name, float value ) = 0; virtual void attribute( const std::string& name, double value ) = 0; virtual void attribute( const std::string& name, long double value ) = 0; virtual void attribute( const std::string& name, unsigned int value ) = 0; virtual void attribute( const std::string& name, unsigned long value ) = 0; virtual void attribute( const std::string& name, unsigned long long value ) = 0; virtual void copy( const input_base& input ) = 0; virtual std::auto_ptr< output_base > branch() const = 0; //@} private: //! @name Copy/Assignment //@{ output_base( const output_base& ); //!< Copy constructor output_base& operator=( const output_base& ); //!< Assignment operator //@} }; } #endif // xeumeuleu_output_base_hpp /* * Copyright (c) 2009, Mathieu Champlon * 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 copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_output_base_hpp #define xeumeuleu_output_base_hpp #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Output base */ // Created: MAT 2009-11-25 // ============================================================================= class output_base { public: //! @name Constructors/Destructor //@{ output_base() {} virtual ~output_base() {} //@} //! @name Operations //@{ virtual void start( const std::string& tag ) = 0; virtual void end() = 0; virtual void write( const std::string& value ) = 0; virtual void write( bool value ) = 0; virtual void write( int value ) = 0; virtual void write( long value ) = 0; virtual void write( long long value ) = 0; virtual void write( float value ) = 0; virtual void write( double value ) = 0; virtual void write( long double value ) = 0; virtual void write( unsigned int value ) = 0; virtual void write( unsigned long value ) = 0; virtual void write( unsigned long long value ) = 0; virtual void cdata( const std::string& value ) = 0; virtual void instruction( const std::string& target, const std::string& data ) = 0; virtual void attribute( const std::string& name, const std::string& value ) = 0; virtual void attribute( const std::string& name, bool value ) = 0; virtual void attribute( const std::string& name, int value ) = 0; virtual void attribute( const std::string& name, long value ) = 0; virtual void attribute( const std::string& name, long long value ) = 0; virtual void attribute( const std::string& name, float value ) = 0; virtual void attribute( const std::string& name, double value ) = 0; virtual void attribute( const std::string& name, long double value ) = 0; virtual void attribute( const std::string& name, unsigned int value ) = 0; virtual void attribute( const std::string& name, unsigned long value ) = 0; virtual void attribute( const std::string& name, unsigned long long value ) = 0; virtual void copy( const input_base& input ) = 0; virtual std::auto_ptr< output_base > branch() const = 0; //@} private: //! @name Copy/Assignment //@{ output_base( const output_base& ); //!< Copy constructor output_base& operator=( const output_base& ); //!< Assignment operator //@} }; } #endif // xeumeuleu_output_base_hpp <commit_msg>Clean-up<commit_after>/* * Copyright (c) 2009, Mathieu Champlon * 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 copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_output_base_hpp #define xeumeuleu_output_base_hpp #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Output base */ // Created: MAT 2009-11-25 // ============================================================================= class output_base { public: //! @name Constructors/Destructor //@{ output_base() {} virtual ~output_base() {} //@} //! @name Operations //@{ virtual void start( const std::string& tag ) = 0; virtual void end() = 0; virtual void write( const std::string& value ) = 0; virtual void write( bool value ) = 0; virtual void write( int value ) = 0; virtual void write( long value ) = 0; virtual void write( long long value ) = 0; virtual void write( float value ) = 0; virtual void write( double value ) = 0; virtual void write( long double value ) = 0; virtual void write( unsigned int value ) = 0; virtual void write( unsigned long value ) = 0; virtual void write( unsigned long long value ) = 0; virtual void cdata( const std::string& value ) = 0; virtual void instruction( const std::string& target, const std::string& data ) = 0; virtual void attribute( const std::string& name, const std::string& value ) = 0; virtual void attribute( const std::string& name, bool value ) = 0; virtual void attribute( const std::string& name, int value ) = 0; virtual void attribute( const std::string& name, long value ) = 0; virtual void attribute( const std::string& name, long long value ) = 0; virtual void attribute( const std::string& name, float value ) = 0; virtual void attribute( const std::string& name, double value ) = 0; virtual void attribute( const std::string& name, long double value ) = 0; virtual void attribute( const std::string& name, unsigned int value ) = 0; virtual void attribute( const std::string& name, unsigned long value ) = 0; virtual void attribute( const std::string& name, unsigned long long value ) = 0; virtual void copy( const input_base& input ) = 0; virtual std::auto_ptr< output_base > branch() const = 0; //@} private: //! @name Copy/Assignment //@{ output_base( const output_base& ); //!< Copy constructor output_base& operator=( const output_base& ); //!< Assignment operator //@} }; } #endif // xeumeuleu_output_base_hpp <|endoftext|>
<commit_before>//===---- llvm/unittest/IR/PatternMatch.cpp - PatternMatch unit tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Operator.h" #include "llvm/Support/NoFolder.h" #include "llvm/Support/PatternMatch.h" #include "gtest/gtest.h" using namespace llvm::PatternMatch; namespace llvm { namespace { /// Ordered floating point minimum/maximum tests. static void m_OrdFMin_expect_match_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match(Select)); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); delete Select; delete Cmp; } static void m_OrdFMin_expect_nomatch_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_FALSE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match(Select)); delete Select; delete Cmp; } static void m_OrdFMax_expect_match_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match(Select)); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); delete Select; delete Cmp; } static void m_OrdFMax_expect_nomatch_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_FALSE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match(Select)); delete Select; delete Cmp; } TEST(PatternMatchTest, FloatingPointOrderedMin) { LLVMContext &C(getGlobalContext()); IRBuilder<true, NoFolder> Builder(C); Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); // Test OLT. Value *Cmp = Builder.CreateFCmpOLT(L, R); Value *Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMin_expect_match_and_delete(Cmp, Select, L, R); // Test OLE. Cmp = Builder.CreateFCmpOLE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMin_expect_match_and_delete(Cmp, Select, L, R); // Test no match on OGE. Cmp = Builder.CreateFCmpOGE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMin_expect_nomatch_and_delete(Cmp, Select, L, R); // Test no match on OGT. Cmp = Builder.CreateFCmpOGT(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMin_expect_nomatch_and_delete(Cmp, Select, L, R); // Test match on OGE with inverted select. Cmp = Builder.CreateFCmpOGE(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_OrdFMin_expect_match_and_delete(Cmp, Select, L, R); // Test match on OGT with inverted select. Cmp = Builder.CreateFCmpOGT(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_OrdFMin_expect_match_and_delete(Cmp, Select, L, R); } TEST(PatternMatchTest, FloatingPointOrderedMax) { LLVMContext &C(getGlobalContext()); IRBuilder<true, NoFolder> Builder(C); Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); // Test OGT. Value *Cmp = Builder.CreateFCmpOGT(L, R); Value *Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMax_expect_match_and_delete(Cmp, Select, L, R); // Test OGE. Cmp = Builder.CreateFCmpOGE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMax_expect_match_and_delete(Cmp, Select, L, R); // Test no match on OLE. Cmp = Builder.CreateFCmpOLE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMax_expect_nomatch_and_delete(Cmp, Select, L, R); // Test no match on OLT. Cmp = Builder.CreateFCmpOLT(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_OrdFMax_expect_nomatch_and_delete(Cmp, Select, L, R); // Test match on OLE with inverted select. Cmp = Builder.CreateFCmpOLE(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_OrdFMax_expect_match_and_delete(Cmp, Select, L, R); // Test match on OLT with inverted select. Cmp = Builder.CreateFCmpOLT(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_OrdFMax_expect_match_and_delete(Cmp, Select, L, R); } /// Unordered floating point minimum/maximum tests. static void m_UnordFMin_expect_match_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match(Select)); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); delete Select; delete Cmp; } static void m_UnordFMin_expect_nomatch_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_FALSE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match(Select)); delete Select; delete Cmp; } static void m_UnordFMax_expect_match_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match(Select)); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); delete Select; delete Cmp; } static void m_UnordFMax_expect_nomatch_and_delete(Value *Cmp, Value *Select, Value *L, Value *R) { Value *MatchL, *MatchR; EXPECT_FALSE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match(Select)); delete Select; delete Cmp; } TEST(PatternMatchTest, FloatingPointUnorderedMin) { LLVMContext &C(getGlobalContext()); IRBuilder<true, NoFolder> Builder(C); Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); // Test ULT. Value *Cmp = Builder.CreateFCmpULT(L, R); Value *Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMin_expect_match_and_delete(Cmp, Select, L, R); // Test ULE. Cmp = Builder.CreateFCmpULE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMin_expect_match_and_delete(Cmp, Select, L, R); // Test no match on UGE. Cmp = Builder.CreateFCmpUGE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMin_expect_nomatch_and_delete(Cmp, Select, L, R); // Test no match on UGT. Cmp = Builder.CreateFCmpUGT(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMin_expect_nomatch_and_delete(Cmp, Select, L, R); // Test match on UGE with inverted select. Cmp = Builder.CreateFCmpUGE(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_UnordFMin_expect_match_and_delete(Cmp, Select, L, R); // Test match on UGT with inverted select. Cmp = Builder.CreateFCmpUGT(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_UnordFMin_expect_match_and_delete(Cmp, Select, L, R); } TEST(PatternMatchTest, FloatingPointUnorderedMax) { LLVMContext &C(getGlobalContext()); IRBuilder<true, NoFolder> Builder(C); Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); // Test UGT. Value *Cmp = Builder.CreateFCmpUGT(L, R); Value *Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMax_expect_match_and_delete(Cmp, Select, L, R); // Test UGE. Cmp = Builder.CreateFCmpUGE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMax_expect_match_and_delete(Cmp, Select, L, R); // Test no match on ULE. Cmp = Builder.CreateFCmpULE(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMax_expect_nomatch_and_delete(Cmp, Select, L, R); // Test no match on ULT. Cmp = Builder.CreateFCmpULT(L, R); Select = Builder.CreateSelect(Cmp, L, R); m_UnordFMax_expect_nomatch_and_delete(Cmp, Select, L, R); // Test match on ULE with inverted select. Cmp = Builder.CreateFCmpULE(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_UnordFMax_expect_match_and_delete(Cmp, Select, L, R); // Test match on ULT with inverted select. Cmp = Builder.CreateFCmpULT(L, R); Select = Builder.CreateSelect(Cmp, R, L); m_UnordFMax_expect_match_and_delete(Cmp, Select, L, R); } } // anonymous namespace. } // llvm namespace. <commit_msg>Simplify the PatternMatch unittest by giving it a module, function, and basic block to hold instructions, and managing all of their lifetimes in a fixture. This makes it easy to sink the expectations into the test cases themselves which also makes things a bit more explicit and clearer IMO.<commit_after>//===---- llvm/unittest/IR/PatternMatch.cpp - PatternMatch unit tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" #include "llvm/IR/Type.h" #include "llvm/Support/NoFolder.h" #include "llvm/Support/PatternMatch.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::PatternMatch; namespace { struct PatternMatchTest : ::testing::Test { LLVMContext Ctx; OwningPtr<Module> M; Function *F; BasicBlock *BB; IRBuilder<true, NoFolder> Builder; PatternMatchTest() : M(new Module("PatternMatchTestModule", Ctx)), F(Function::Create( FunctionType::get(Type::getVoidTy(Ctx), /* IsVarArg */ false), Function::ExternalLinkage, "f", M.get())), BB(BasicBlock::Create(Ctx, "entry", F)), Builder(BB) {} }; TEST_F(PatternMatchTest, FloatingPointOrderedMin) { Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test OLT. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test OLE. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on OGE. EXPECT_FALSE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGE(L, R), L, R))); // Test no match on OGT. EXPECT_FALSE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGT(L, R), L, R))); // Test match on OGE with inverted select. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on OGT with inverted select. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointOrderedMax) { Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test OGT. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test OGE. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOGE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on OLE. EXPECT_FALSE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLE(L, R), L, R))); // Test no match on OLT. EXPECT_FALSE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLT(L, R), L, R))); // Test match on OLE with inverted select. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on OLT with inverted select. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpOLT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointUnorderedMin) { Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test ULT. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test ULE. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on UGE. EXPECT_FALSE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGE(L, R), L, R))); // Test no match on UGT. EXPECT_FALSE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGT(L, R), L, R))); // Test match on UGE with inverted select. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on UGT with inverted select. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointUnorderedMax) { Type *FltTy = Builder.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test UGT. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test UGE. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpUGE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on ULE. EXPECT_FALSE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULE(L, R), L, R))); // Test no match on ULT. EXPECT_FALSE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULT(L, R), L, R))); // Test match on ULE with inverted select. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on ULT with inverted select. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)).match( Builder.CreateSelect(Builder.CreateFCmpULT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } } // anonymous namespace. <|endoftext|>
<commit_before> #include "stxxl/bits/io/wfs_file.h" #ifdef BOOST_MSVC __STXXL_BEGIN_NAMESPACE HANDLE wfs_file_base::get_file_des() const { return file_des; } void wfs_file_base::lock() { if (LockFile(file_des, 0, 0, 0xffffffff, 0xffffffff) == 0) stxxl_win_lasterror_exit("LockFile ", io_error) } wfs_request_base::wfs_request_base ( wfs_file_base * f, void * buf, stxxl::int64 off, size_t b, request_type t, completion_handler on_cmpl) : request (on_cmpl, f, buf, off, b, t), /* file (f), buffer (buf), offset (off), bytes (b), type(t), */ _state (OP) { #ifdef STXXL_CHECK_BLOCK_ALIGNING // Direct I/O requires filsystem block size alighnment for file offsets, // memory buffer adresses, and transfer(buffer) size must be multiple // of the filesystem block size check_aligning (); #endif } bool wfs_request_base::add_waiter (onoff_switch * sw) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); #else waiters_mutex.lock (); #endif if (poll ()) // request already finished { #ifndef STXXL_BOOST_THREADS waiters_mutex.unlock (); #endif return true; } waiters.insert (sw); #ifndef STXXL_BOOST_THREADS waiters_mutex.unlock (); #endif return false; }; void wfs_request_base::delete_waiter (onoff_switch * sw) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); waiters.erase (sw); #else waiters_mutex.lock (); waiters.erase (sw); waiters_mutex.unlock (); #endif } int wfs_request_base::nwaiters () // returns number of waiters { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); return waiters.size(); #else waiters_mutex.lock (); int size = waiters.size (); waiters_mutex.unlock (); return size; #endif } void wfs_request_base::check_aligning () { if (offset % BLOCK_ALIGN) STXXL_ERRMSG ("Offset is not aligned: modulo " << BLOCK_ALIGN << " = " << offset % BLOCK_ALIGN); if (bytes % BLOCK_ALIGN) STXXL_ERRMSG ("Size is multiple of " << BLOCK_ALIGN << ", = " << bytes % BLOCK_ALIGN); if (long (buffer) % BLOCK_ALIGN) STXXL_ERRMSG ("Buffer is not aligned: modulo " << BLOCK_ALIGN << " = " << long (buffer) % BLOCK_ALIGN << " (" << std::hex << buffer << std::dec << ")"); } wfs_request_base::~wfs_request_base () { STXXL_VERBOSE3("wfs_request_base " << unsigned (this) << ": deletion, cnt: " << ref_cnt); assert(_state() == DONE || _state() == READY2DIE); // if(_state() != DONE && _state()!= READY2DIE ) // STXXL_ERRMSG("WARNING: serious stxxl error requiest being deleted while I/O did not finish "<< // "! Please report it to the stxxl author(s) <[email protected]>"); // _state.wait_for (READY2DIE); // does not make sense ? } void wfs_request_base::wait () { STXXL_VERBOSE3("wfs_request_base : " << unsigned (this) << " wait "); START_COUNT_WAIT_TIME #ifdef NO_OVERLAPPING enqueue(); #endif _state.wait_for (READY2DIE); END_COUNT_WAIT_TIME check_errors(); } bool wfs_request_base::poll() { #ifdef NO_OVERLAPPING /*if(_state () < DONE)*/ wait(); #endif bool s = _state() >= DONE; check_errors(); return s; } const char * wfs_request_base::io_type () { return "wfs_base"; } wfs_file_base::wfs_file_base ( const std::string & filename, int mode, int disk) : file (disk), file_des (INVALID_HANDLE_VALUE), mode_(mode) { DWORD dwDesiredAccess = 0; DWORD dwShareMode = 0; DWORD dwCreationDisposition = 0; DWORD dwFlagsAndAttributes = 0; #ifndef STXXL_DIRECT_IO_OFF if (mode & DIRECT) { dwFlagsAndAttributes |= FILE_FLAG_NO_BUFFERING; // TODO: try also FILE_FLAG_WRITE_THROUGH option ? } #endif if (mode & RDONLY) { dwFlagsAndAttributes |= FILE_ATTRIBUTE_READONLY; dwDesiredAccess |= GENERIC_READ; } if (mode & WRONLY) { dwDesiredAccess |= GENERIC_WRITE; } if (mode & RDWR) { dwDesiredAccess |= (GENERIC_READ | GENERIC_WRITE); } if (mode & CREAT) { // ignored } if (mode & TRUNC) { dwCreationDisposition |= TRUNCATE_EXISTING; } else { dwCreationDisposition |= OPEN_ALWAYS; } file_des = ::CreateFile(filename.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); if (file_des == INVALID_HANDLE_VALUE) stxxl_win_lasterror_exit("CreateFile filename=" << filename, io_error) }; wfs_file_base::~wfs_file_base () { if (!CloseHandle(file_des)) stxxl_win_lasterror_exit("closing file (call of ::CloseHandle) ", io_error) file_des = INVALID_HANDLE_VALUE; }; stxxl::int64 wfs_file_base::size () { LARGE_INTEGER result; if (!GetFileSizeEx(file_des, &result)) stxxl_win_lasterror_exit("GetFileSizeEx ", io_error) return result.QuadPart; }; void wfs_file_base::set_size (stxxl::int64 newsize) { stxxl::int64 cur_size = size(); LARGE_INTEGER desired_pos; desired_pos.QuadPart = newsize; if (!SetFilePointerEx(file_des, desired_pos, NULL, FILE_BEGIN)) stxxl_win_lasterror_exit("SetFilePointerEx in wfs_file_base::set_size(..) oldsize=" << cur_size << " newsize=" << newsize << " ", io_error) if (!SetEndOfFile(file_des)) stxxl_win_lasterror_exit("SetEndOfFile oldsize=" << cur_size << " newsize=" << newsize << " ", io_error) }; __STXXL_END_NAMESPACE #endif // BOOST_MSVC <commit_msg>add missing semicolons<commit_after> #include "stxxl/bits/io/wfs_file.h" #ifdef BOOST_MSVC __STXXL_BEGIN_NAMESPACE HANDLE wfs_file_base::get_file_des() const { return file_des; } void wfs_file_base::lock() { if (LockFile(file_des, 0, 0, 0xffffffff, 0xffffffff) == 0) stxxl_win_lasterror_exit("LockFile ", io_error); } wfs_request_base::wfs_request_base ( wfs_file_base * f, void * buf, stxxl::int64 off, size_t b, request_type t, completion_handler on_cmpl) : request (on_cmpl, f, buf, off, b, t), /* file (f), buffer (buf), offset (off), bytes (b), type(t), */ _state (OP) { #ifdef STXXL_CHECK_BLOCK_ALIGNING // Direct I/O requires filsystem block size alighnment for file offsets, // memory buffer adresses, and transfer(buffer) size must be multiple // of the filesystem block size check_aligning (); #endif } bool wfs_request_base::add_waiter (onoff_switch * sw) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); #else waiters_mutex.lock (); #endif if (poll ()) // request already finished { #ifndef STXXL_BOOST_THREADS waiters_mutex.unlock (); #endif return true; } waiters.insert (sw); #ifndef STXXL_BOOST_THREADS waiters_mutex.unlock (); #endif return false; }; void wfs_request_base::delete_waiter (onoff_switch * sw) { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); waiters.erase (sw); #else waiters_mutex.lock (); waiters.erase (sw); waiters_mutex.unlock (); #endif } int wfs_request_base::nwaiters () // returns number of waiters { #ifdef STXXL_BOOST_THREADS boost::mutex::scoped_lock Lock(waiters_mutex); return waiters.size(); #else waiters_mutex.lock (); int size = waiters.size (); waiters_mutex.unlock (); return size; #endif } void wfs_request_base::check_aligning () { if (offset % BLOCK_ALIGN) STXXL_ERRMSG ("Offset is not aligned: modulo " << BLOCK_ALIGN << " = " << offset % BLOCK_ALIGN); if (bytes % BLOCK_ALIGN) STXXL_ERRMSG ("Size is multiple of " << BLOCK_ALIGN << ", = " << bytes % BLOCK_ALIGN); if (long (buffer) % BLOCK_ALIGN) STXXL_ERRMSG ("Buffer is not aligned: modulo " << BLOCK_ALIGN << " = " << long (buffer) % BLOCK_ALIGN << " (" << std::hex << buffer << std::dec << ")"); } wfs_request_base::~wfs_request_base () { STXXL_VERBOSE3("wfs_request_base " << unsigned (this) << ": deletion, cnt: " << ref_cnt); assert(_state() == DONE || _state() == READY2DIE); // if(_state() != DONE && _state()!= READY2DIE ) // STXXL_ERRMSG("WARNING: serious stxxl error requiest being deleted while I/O did not finish "<< // "! Please report it to the stxxl author(s) <[email protected]>"); // _state.wait_for (READY2DIE); // does not make sense ? } void wfs_request_base::wait () { STXXL_VERBOSE3("wfs_request_base : " << unsigned (this) << " wait "); START_COUNT_WAIT_TIME #ifdef NO_OVERLAPPING enqueue(); #endif _state.wait_for (READY2DIE); END_COUNT_WAIT_TIME check_errors(); } bool wfs_request_base::poll() { #ifdef NO_OVERLAPPING /*if(_state () < DONE)*/ wait(); #endif bool s = _state() >= DONE; check_errors(); return s; } const char * wfs_request_base::io_type () { return "wfs_base"; } wfs_file_base::wfs_file_base ( const std::string & filename, int mode, int disk) : file (disk), file_des (INVALID_HANDLE_VALUE), mode_(mode) { DWORD dwDesiredAccess = 0; DWORD dwShareMode = 0; DWORD dwCreationDisposition = 0; DWORD dwFlagsAndAttributes = 0; #ifndef STXXL_DIRECT_IO_OFF if (mode & DIRECT) { dwFlagsAndAttributes |= FILE_FLAG_NO_BUFFERING; // TODO: try also FILE_FLAG_WRITE_THROUGH option ? } #endif if (mode & RDONLY) { dwFlagsAndAttributes |= FILE_ATTRIBUTE_READONLY; dwDesiredAccess |= GENERIC_READ; } if (mode & WRONLY) { dwDesiredAccess |= GENERIC_WRITE; } if (mode & RDWR) { dwDesiredAccess |= (GENERIC_READ | GENERIC_WRITE); } if (mode & CREAT) { // ignored } if (mode & TRUNC) { dwCreationDisposition |= TRUNCATE_EXISTING; } else { dwCreationDisposition |= OPEN_ALWAYS; } file_des = ::CreateFile(filename.c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); if (file_des == INVALID_HANDLE_VALUE) stxxl_win_lasterror_exit("CreateFile filename=" << filename, io_error); }; wfs_file_base::~wfs_file_base () { if (!CloseHandle(file_des)) stxxl_win_lasterror_exit("closing file (call of ::CloseHandle) ", io_error) file_des = INVALID_HANDLE_VALUE; }; stxxl::int64 wfs_file_base::size () { LARGE_INTEGER result; if (!GetFileSizeEx(file_des, &result)) stxxl_win_lasterror_exit("GetFileSizeEx ", io_error) return result.QuadPart; }; void wfs_file_base::set_size (stxxl::int64 newsize) { stxxl::int64 cur_size = size(); LARGE_INTEGER desired_pos; desired_pos.QuadPart = newsize; if (!SetFilePointerEx(file_des, desired_pos, NULL, FILE_BEGIN)) stxxl_win_lasterror_exit("SetFilePointerEx in wfs_file_base::set_size(..) oldsize=" << cur_size << " newsize=" << newsize << " ", io_error) if (!SetEndOfFile(file_des)) stxxl_win_lasterror_exit("SetEndOfFile oldsize=" << cur_size << " newsize=" << newsize << " ", io_error); }; __STXXL_END_NAMESPACE #endif // BOOST_MSVC <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AttributedString.h" #include <react/renderer/debug/DebugStringConvertibleItem.h> namespace facebook::react { using Fragment = AttributedString::Fragment; using Fragments = AttributedString::Fragments; #pragma mark - Fragment std::string Fragment::AttachmentCharacter() { return u8"\uFFFC"; // Unicode `OBJECT REPLACEMENT CHARACTER` } bool Fragment::isAttachment() const { return string == AttachmentCharacter(); } bool Fragment::operator==(const Fragment &rhs) const { return std::tie( string, textAttributes, parentShadowView.tag, parentShadowView.layoutMetrics) == std::tie( rhs.string, rhs.textAttributes, rhs.parentShadowView.tag, rhs.parentShadowView.layoutMetrics); } bool Fragment::isContentEqual(const Fragment &rhs) const { return std::tie(string, textAttributes) == std::tie(rhs.string, rhs.textAttributes); } bool Fragment::operator!=(const Fragment &rhs) const { return !(*this == rhs); } #pragma mark - AttributedString void AttributedString::appendFragment(const Fragment &fragment) { ensureUnsealed(); if (fragment.string.empty()) { return; } fragments_.push_back(fragment); } void AttributedString::prependFragment(const Fragment &fragment) { ensureUnsealed(); if (fragment.string.empty()) { return; } fragments_.insert(fragments_.begin(), fragment); } void AttributedString::appendAttributedString( const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert( fragments_.end(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } void AttributedString::prependAttributedString( const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert( fragments_.begin(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } Fragments const &AttributedString::getFragments() const { return fragments_; } Fragments &AttributedString::getFragments() { return fragments_; } std::string AttributedString::getString() const { auto string = std::string{}; for (const auto &fragment : fragments_) { string += fragment.string; } return string; } bool AttributedString::isEmpty() const { return fragments_.empty(); } bool AttributedString::compareTextAttributesWithoutFrame( const AttributedString &rhs) const { if (fragments_.size() != rhs.fragments_.size()) { return false; } for (unsigned i = 0; i < fragments_.size(); i++) { if (fragments_[i].textAttributes != rhs.fragments_[i].textAttributes || fragments_[i].string != rhs.fragments_[i].string) { return false; } } return true; } bool AttributedString::operator==(const AttributedString &rhs) const { return fragments_ == rhs.fragments_; } bool AttributedString::operator!=(const AttributedString &rhs) const { return !(*this == rhs); } bool AttributedString::isContentEqual(const AttributedString &rhs) const { if (fragments_.size() != rhs.fragments_.size()) { return false; } for (auto i = 0; i < fragments_.size(); i++) { if (!fragments_[i].isContentEqual(rhs.fragments_[i])) { return false; } } return true; } #pragma mark - DebugStringConvertible #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList AttributedString::getDebugChildren() const { auto list = SharedDebugStringConvertibleList{}; for (auto &&fragment : fragments_) { auto propsList = fragment.textAttributes.DebugStringConvertible::getDebugProps(); list.push_back(std::make_shared<DebugStringConvertibleItem>( "Fragment", fragment.string, SharedDebugStringConvertibleList(), propsList)); } return list; } #endif } // namespace facebook::react <commit_msg>Fix windows warning/error over unsigned int (#34947)<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "AttributedString.h" #include <react/renderer/debug/DebugStringConvertibleItem.h> namespace facebook::react { using Fragment = AttributedString::Fragment; using Fragments = AttributedString::Fragments; #pragma mark - Fragment std::string Fragment::AttachmentCharacter() { return u8"\uFFFC"; // Unicode `OBJECT REPLACEMENT CHARACTER` } bool Fragment::isAttachment() const { return string == AttachmentCharacter(); } bool Fragment::operator==(const Fragment &rhs) const { return std::tie( string, textAttributes, parentShadowView.tag, parentShadowView.layoutMetrics) == std::tie( rhs.string, rhs.textAttributes, rhs.parentShadowView.tag, rhs.parentShadowView.layoutMetrics); } bool Fragment::isContentEqual(const Fragment &rhs) const { return std::tie(string, textAttributes) == std::tie(rhs.string, rhs.textAttributes); } bool Fragment::operator!=(const Fragment &rhs) const { return !(*this == rhs); } #pragma mark - AttributedString void AttributedString::appendFragment(const Fragment &fragment) { ensureUnsealed(); if (fragment.string.empty()) { return; } fragments_.push_back(fragment); } void AttributedString::prependFragment(const Fragment &fragment) { ensureUnsealed(); if (fragment.string.empty()) { return; } fragments_.insert(fragments_.begin(), fragment); } void AttributedString::appendAttributedString( const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert( fragments_.end(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } void AttributedString::prependAttributedString( const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert( fragments_.begin(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } Fragments const &AttributedString::getFragments() const { return fragments_; } Fragments &AttributedString::getFragments() { return fragments_; } std::string AttributedString::getString() const { auto string = std::string{}; for (const auto &fragment : fragments_) { string += fragment.string; } return string; } bool AttributedString::isEmpty() const { return fragments_.empty(); } bool AttributedString::compareTextAttributesWithoutFrame( const AttributedString &rhs) const { if (fragments_.size() != rhs.fragments_.size()) { return false; } for (size_t i = 0; i < fragments_.size(); i++) { if (fragments_[i].textAttributes != rhs.fragments_[i].textAttributes || fragments_[i].string != rhs.fragments_[i].string) { return false; } } return true; } bool AttributedString::operator==(const AttributedString &rhs) const { return fragments_ == rhs.fragments_; } bool AttributedString::operator!=(const AttributedString &rhs) const { return !(*this == rhs); } bool AttributedString::isContentEqual(const AttributedString &rhs) const { if (fragments_.size() != rhs.fragments_.size()) { return false; } for (size_t i = 0; i < fragments_.size(); i++) { if (!fragments_[i].isContentEqual(rhs.fragments_[i])) { return false; } } return true; } #pragma mark - DebugStringConvertible #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList AttributedString::getDebugChildren() const { auto list = SharedDebugStringConvertibleList{}; for (auto &&fragment : fragments_) { auto propsList = fragment.textAttributes.DebugStringConvertible::getDebugProps(); list.push_back(std::make_shared<DebugStringConvertibleItem>( "Fragment", fragment.string, SharedDebugStringConvertibleList(), propsList)); } return list; } #endif } // namespace facebook::react <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreGLUniformCacheImp.h" namespace Ogre { GLUniformCacheImp::GLUniformCacheImp(void) { clearCache(); } void GLUniformCacheImp::clearCache() { mUniformValueMap.clear(); } GLUniformCacheImp::~GLUniformCacheImp(void) { mUniformValueMap.clear(); } bool GLUniformCacheImp::updateUniform(GLint location, const void *value, GLsizei length) { uint32 current = mUniformValueMap[location]; uint32 hash = Ogre::FastHash((const char *)value, length); // First check if the uniform name is in the map. If not, this is new so insert it into the map. if (!current || (current != hash)) { // Haven't cached this state yet or the value has changed mUniformValueMap[location] = hash; return true; } return false; } } <commit_msg>Add a missing include for FastHash<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreGLUniformCacheImp.h" #include "OgreCommon.h" namespace Ogre { GLUniformCacheImp::GLUniformCacheImp(void) { clearCache(); } void GLUniformCacheImp::clearCache() { mUniformValueMap.clear(); } GLUniformCacheImp::~GLUniformCacheImp(void) { mUniformValueMap.clear(); } bool GLUniformCacheImp::updateUniform(GLint location, const void *value, GLsizei length) { uint32 current = mUniformValueMap[location]; uint32 hash = Ogre::FastHash((const char *)value, length); // First check if the uniform name is in the map. If not, this is new so insert it into the map. if (!current || (current != hash)) { // Haven't cached this state yet or the value has changed mUniformValueMap[location] = hash; return true; } return false; } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "SamplingTypeGenerator.h" #include <math.h> #include "DataHelper.h" #include <algorithm> #include <numeric> #include "../FFTW-64/include/fftw3.h" #pragma comment(lib, "../FFTW-64/lib/libfftw3-3.lib") #pragma comment(lib, "../FFTW-64/lib/libfftw3f-3.lib") #pragma comment(lib, "../FFTW-64/lib/libfftw3l-3.lib") using namespace Yap; using namespace std; CSamplingTypeGenerator::CSamplingTypeGenerator(void): CProcessorImp(L"SamplingTypeGenerator"), _try_count(10), _tolerance(3) { AddInputPort(L"Input", 0, DataTypeUnknown); AddOutputPort(L"Output", 1, DataTypeFloat); AddProperty(PropertyFloat, L"pow", L""); SetFloat(L"pow", 3.0f); AddProperty(PropertyFloat, L"sample_percent", L""); SetFloat(L"sample_percent", 0.4); AddProperty(PropertyFloat, L"radius", L""); SetFloat(L"radius", 0.2f); AddProperty(PropertyBool, L"equal_unsampling", L""); SetBool(L"equal_unsampling", false); AddProperty(PropertyBool, L"random_unsampling", L""); SetBool(L"random_unsampling", true); } Yap::CSamplingTypeGenerator::CSamplingTypeGenerator(const CSamplingTypeGenerator & rhs) :CProcessorImp(rhs) { } CSamplingTypeGenerator::~CSamplingTypeGenerator() { } IProcessor * Yap::CSamplingTypeGenerator::Clone() { try { auto processor = new CSamplingTypeGenerator(*this); return processor; } catch (std::bad_alloc&) { return nullptr; } } bool Yap::CSamplingTypeGenerator::Input(const wchar_t * name, IData * data) { if (wstring(name) != L"Input") return false; if (data->GetDataType() != DataTypeComplexFloat) return false; CDataHelper input_data(data); if (GetBool(L"random_unsampling")) { auto row_count = input_data.GetHeight(); float pow = static_cast<float> (GetFloat(L"pow")); float sample_percent = static_cast<float> (GetFloat(L"sample_percent")); float radius = static_cast<float> (GetFloat(L"radius")); auto sampling_pattern = GetMinInterferenceSamplingPattern(row_count, pow, sample_percent, radius); char * sampling_type = nullptr; try { sampling_type = new char[row_count]; } catch(bad_alloc&) { return false; } memcpy(sampling_type, sampling_pattern.data(), sizeof(char)); CDimensionsImp dimensions; dimensions(DimensionReadout, 0U, 1) (DimensionPhaseEncoding, 0U, row_count); CSmartPtr<CCharData> outdata(new CCharData(sampling_type, dimensions, nullptr, true)); Feed(L"Output", outdata.get()); } else { } return true; } std::vector<unsigned char> Yap::CSamplingTypeGenerator::GetMinInterferenceSamplingPattern(unsigned int row_count, float pow, float sample_percent, float radius) { float min_peak_interference((float)INT_MAX); vector<float> pdf = GeneratePdf(row_count, pow, sample_percent, radius); vector<unsigned char> min_interference_pattern(pdf.size()); vector<unsigned char> sampling_pattern(pdf.size()); vector<complex<float>> normalized_sampling_pattern(pdf.size()); vector<complex<float>> fft_result(pdf.size()); fftwf_plan p = fftwf_plan_dft_1d(int(normalized_sampling_pattern.size()), (fftwf_complex*)normalized_sampling_pattern.data(), (fftwf_complex*)fft_result.data(), FFTW_BACKWARD, FFTW_ESTIMATE); //kռ䵽ͼǷҶ任 for (unsigned int i = 0; i < _try_count; ++i) { float sum_vector_element = 0; float sum_pdf = accumulate(pdf.begin(), pdf.end(), 0.0f); while (abs(sum_vector_element - sum_pdf) > _tolerance) { sum_vector_element = 0; for (unsigned int j = 0; j < pdf.size(); ++j) { sampling_pattern[j] = ((float)rand() / (RAND_MAX + 1) * 1) < pdf[j]; sum_vector_element += sampling_pattern[j]; } } //תΪʽ for (unsigned int t = 0; t < pdf.size(); t++) { normalized_sampling_pattern[t] = std::complex<float>(sampling_pattern[t] / pdf[t], 0); } // Ҷ任 fftwf_execute(p); for (auto iter = fft_result.begin() + 1; iter != fft_result.end(); ++iter) { (*iter) /= float(sqrt(fft_result.size())); } *(fft_result.data()) = 0; float max_value = abs(fft_result[1]); for (auto it = fft_result.begin() + 1; it != fft_result.end(); ++it) { if (max_value < abs(*it)) { max_value = abs(*it); } } if (max_value < min_peak_interference) { min_peak_interference = max_value; min_interference_pattern = sampling_pattern; } } // fftwf_destroy_plan(p); return min_interference_pattern; } std::vector<float> Yap::CSamplingTypeGenerator::GeneratePdf(unsigned int row_count, float p, float sample_percent, float radius) { float minval = 0.0; float maxval = 1.0; float val = 0.5; unsigned int line_count = (unsigned int)floor(sample_percent * row_count); // PCTG = 0.35 * 512 in Matlab float gap = float(2.0 / (row_count - 1)); std::vector<float> pdf; pdf = LineSpace(-1, 1, row_count); std::vector<unsigned int> pdf_index(row_count); for (unsigned int i = 0; i < pdf.size(); ++i) { pdf_index[i] = 0; if (abs(pdf[i]) < radius) { pdf_index[i] = i; } } for (unsigned int i = 0; i < pdf.size(); ++i) { pdf[i] = pow(1 - abs(pdf[i]), p); if (i == pdf_index[i]) { pdf[i] = 1; } } float sum = accumulate(pdf.begin(), pdf.end(), 0.0f); std::vector<float> pdf_temp; while (1) { val = minval / 2 + maxval / 2; pdf_temp.erase(pdf_temp.begin(), pdf_temp.end()); for (unsigned int i = 0; i < row_count; ++i) { float pdf_elem = pdf[i] + val; if (pdf_elem > 1.0) { pdf_elem = 1.0; } pdf_temp.push_back(pdf_elem); } sum = floor(accumulate(pdf_temp.begin(), pdf_temp.end(), 0.0f)); if (floor(sum) > line_count) { return vector<float>(); //pֵƫС } if (sum > line_count) { maxval = val; } else if (sum < line_count) { minval = val; } else break; } return pdf_temp; } std::vector<float> Yap::CSamplingTypeGenerator::LineSpace(float begin, float end, unsigned int count) { std::vector<float> vec; float current_value = begin; float gap = float(2.0 / (count - 1)); while (current_value <= end) { vec.push_back(current_value); current_value += gap; } while (vec.size() < count) { vec.push_back(end); } return vec; } <commit_msg>Modify SamplingTypeGenerator<commit_after>#include "stdafx.h" #include "SamplingTypeGenerator.h" #include <math.h> #include "DataHelper.h" #include <algorithm> #include <numeric> #include "../FFTW-64/include/fftw3.h" #pragma comment(lib, "../FFTW-64/lib/libfftw3-3.lib") #pragma comment(lib, "../FFTW-64/lib/libfftw3f-3.lib") #pragma comment(lib, "../FFTW-64/lib/libfftw3l-3.lib") using namespace Yap; using namespace std; CSamplingTypeGenerator::CSamplingTypeGenerator(void): CProcessorImp(L"SamplingTypeGenerator"), _try_count(10), _tolerance(3) { AddInputPort(L"Input", YAP_ANY_DIMENSION, DataTypeUnknown); AddOutputPort(L"Output", 1, DataTypeChar); AddProperty(PropertyFloat, L"pow", L""); SetFloat(L"pow", 3.0f); AddProperty(PropertyFloat, L"sample_percent", L""); SetFloat(L"sample_percent", 0.4); AddProperty(PropertyFloat, L"radius", L""); SetFloat(L"radius", 0.2f); AddProperty(PropertyBool, L"equal_subsampling", L""); SetBool(L"equal_subsampling", false); AddProperty(PropertyBool, L"random_subsampling", L""); SetBool(L"random_subsampling", true); AddProperty(PropertyInt, L"Rate", L""); SetInt(L"Rate", 2); AddProperty(PropertyInt, L"AcsCount", L""); SetInt(L"AcsCount", 16); } Yap::CSamplingTypeGenerator::CSamplingTypeGenerator(const CSamplingTypeGenerator & rhs) :CProcessorImp(rhs) { } CSamplingTypeGenerator::~CSamplingTypeGenerator() { } IProcessor * Yap::CSamplingTypeGenerator::Clone() { try { auto processor = new CSamplingTypeGenerator(*this); return processor; } catch (std::bad_alloc&) { return nullptr; } } bool Yap::CSamplingTypeGenerator::Input(const wchar_t * name, IData * data) { if (wstring(name) != L"Input") return false; if (data->GetDataType() != DataTypeComplexFloat) return false; CDataHelper input_data(data); if (GetBool(L"random_subsampling")) { auto row_count = input_data.GetHeight(); float pow = static_cast<float> (GetFloat(L"pow")); float sample_percent = static_cast<float> (GetFloat(L"sample_percent")); float radius = static_cast<float> (GetFloat(L"radius")); auto sampling_pattern = GetMinInterferenceSamplingPattern(row_count, pow, sample_percent, radius); char * sampling_type = nullptr; try { sampling_type = new char[row_count]; } catch(bad_alloc&) { return false; } memcpy(sampling_type, sampling_pattern.data(), sizeof(char)); CDimensionsImp dimensions; dimensions(DimensionReadout, 0U, 1) (DimensionPhaseEncoding, 0U, row_count); CSmartPtr<CCharData> outdata(new CCharData(sampling_type, dimensions, nullptr, true)); Feed(L"Output", outdata.get()); } else { vector<unsigned char> sampling_pattern; unsigned int r = GetInt(L"Rate"); unsigned int acs = GetInt(L"AcsCount"); auto height = input_data.GetHeight(); for (unsigned int i = 0; i <= height - r - 1; ++i) { if (i % r == 0) { sampling_pattern.push_back(1); } else { sampling_pattern.push_back(0); } } unsigned int first = static_cast<unsigned int>((floor((height - acs) / (2 * r))) * r + 1); unsigned int last = first + acs; sampling_pattern[first] = 1; while (first <= last) { first++; sampling_pattern[first] = 1; } char * sampling_type = nullptr; try { sampling_type = new char[height]; } catch (bad_alloc&) { return false; } memcpy(sampling_type, sampling_pattern.data(), sizeof(char)); CDimensionsImp dimensions; dimensions(DimensionReadout, 0U, 1) (DimensionPhaseEncoding, 0U, height); CSmartPtr<CCharData> outdata(new CCharData(sampling_type, dimensions, nullptr, true)); Feed(L"Output", outdata.get()); } return true; } std::vector<unsigned char> Yap::CSamplingTypeGenerator::GetMinInterferenceSamplingPattern(unsigned int row_count, float pow, float sample_percent, float radius) { float min_peak_interference((float)INT_MAX); vector<float> pdf = GeneratePdf(row_count, pow, sample_percent, radius); vector<unsigned char> min_interference_pattern(pdf.size()); vector<unsigned char> sampling_pattern(pdf.size()); vector<complex<float>> normalized_sampling_pattern(pdf.size()); vector<complex<float>> fft_result(pdf.size()); fftwf_plan p = fftwf_plan_dft_1d(int(normalized_sampling_pattern.size()), (fftwf_complex*)normalized_sampling_pattern.data(), (fftwf_complex*)fft_result.data(), FFTW_BACKWARD, FFTW_ESTIMATE); //kռ䵽ͼǷҶ任 for (unsigned int i = 0; i < _try_count; ++i) { float sum_vector_element = 0; float sum_pdf = accumulate(pdf.begin(), pdf.end(), 0.0f); while (abs(sum_vector_element - sum_pdf) > _tolerance) { sum_vector_element = 0; for (unsigned int j = 0; j < pdf.size(); ++j) { sampling_pattern[j] = ((float)rand() / (RAND_MAX + 1) * 1) < pdf[j]; sum_vector_element += sampling_pattern[j]; } } //תΪʽ for (unsigned int t = 0; t < pdf.size(); t++) { normalized_sampling_pattern[t] = std::complex<float>(sampling_pattern[t] / pdf[t], 0); } // Ҷ任 fftwf_execute(p); for (auto iter = fft_result.begin() + 1; iter != fft_result.end(); ++iter) { (*iter) /= float(sqrt(fft_result.size())); } *(fft_result.data()) = 0; float max_value = abs(fft_result[1]); for (auto it = fft_result.begin() + 1; it != fft_result.end(); ++it) { if (max_value < abs(*it)) { max_value = abs(*it); } } if (max_value < min_peak_interference) { min_peak_interference = max_value; min_interference_pattern = sampling_pattern; } } // fftwf_destroy_plan(p); return min_interference_pattern; } std::vector<float> Yap::CSamplingTypeGenerator::GeneratePdf(unsigned int row_count, float p, float sample_percent, float radius) { float minval = 0.0; float maxval = 1.0; float val = 0.5; unsigned int line_count = (unsigned int)floor(sample_percent * row_count); // PCTG = 0.35 * 512 in Matlab float gap = float(2.0 / (row_count - 1)); std::vector<float> pdf; pdf = LineSpace(-1, 1, row_count); std::vector<unsigned int> pdf_index(row_count); for (unsigned int i = 0; i < pdf.size(); ++i) { pdf_index[i] = 0; if (abs(pdf[i]) < radius) { pdf_index[i] = i; } } for (unsigned int i = 0; i < pdf.size(); ++i) { pdf[i] = pow(1 - abs(pdf[i]), p); if (i == pdf_index[i]) { pdf[i] = 1; } } float sum = accumulate(pdf.begin(), pdf.end(), 0.0f); std::vector<float> pdf_temp; while (1) { val = minval / 2 + maxval / 2; pdf_temp.erase(pdf_temp.begin(), pdf_temp.end()); for (unsigned int i = 0; i < row_count; ++i) { float pdf_elem = pdf[i] + val; if (pdf_elem > 1.0) { pdf_elem = 1.0; } pdf_temp.push_back(pdf_elem); } sum = floor(accumulate(pdf_temp.begin(), pdf_temp.end(), 0.0f)); if (floor(sum) > line_count) { return vector<float>(); //pֵƫС } if (sum > line_count) { maxval = val; } else if (sum < line_count) { minval = val; } else break; } return pdf_temp; } std::vector<float> Yap::CSamplingTypeGenerator::LineSpace(float begin, float end, unsigned int count) { std::vector<float> vec; float current_value = begin; float gap = float(2.0 / (count - 1)); while (current_value <= end) { vec.push_back(current_value); current_value += gap; } while (vec.size() < count) { vec.push_back(end); } return vec; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.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 above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" const unsigned int Dimension = 2; typedef unsigned short LabelType; typedef double PixelType; typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::Image<unsigned int,2> LabeledImageType; typedef LabelMapType::LabelObjectContainerType LabelObjectContainerType; typedef LabelObjectContainerType::const_iterator LabelObjectIterator; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::ImageFileWriter<VectorImageType> WriterType; typedef otb::ImageFileWriter<LabeledImageType> LabeledWriterType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType,VectorImageType> BandsStatisticsFilterType; int otbBandsStatisticsAttributesLabelMapFilterNew(int argc, char* argv[]) { BandsStatisticsFilterType::Pointer object = BandsStatisticsFilterType::New(); return EXIT_SUCCESS; } int otbBandsStatisticsAttributesLabelMapFilter(int argc, char* argv[]) { const char * infname = argv[1]; const char * lfname = argv[2]; const char * outfname = argv[3]; // Filters instanciation ReaderType::Pointer reader = ReaderType::New(); LabeledReaderType::Pointer labeledReader = LabeledReaderType::New(); LabelMapFilterType::Pointer filter = LabelMapFilterType::New(); BandsStatisticsFilterType::Pointer stats = BandsStatisticsFilterType::New(); // Read inputs reader->SetFileName(infname); labeledReader->SetFileName(lfname); // Make a LabelMap out of it filter->SetInput(labeledReader->GetOutput()); filter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); //Compute band statistics attributes stats->SetInput(filter->GetOutput()); stats->SetFeatureImage(reader->GetOutput()); stats->Update(); LabelMapType::Pointer labelMap = stats->GetOutput(); // Dump all results in the output file std::ofstream outfile(outfname); LabelObjectIterator it = labelMap->GetLabelObjectContainer().begin(); LabelObjectIterator end = labelMap->GetLabelObjectContainer().end(); for (; it != end; ++it) { LabelType label = it->first; LabelObjectType::Pointer labelObject = it->second; outfile << "Label " << label << " : " << std::endl; std::vector<std::string> attributes = labelObject->GetAvailableAttributes(); std::vector<std::string>::const_iterator attrIt = attributes.begin(); std::vector<std::string>::const_iterator attrEnd = attributes.end(); for (; attrIt != attrEnd; ++attrIt) { LabelObjectType::AttributesValueType value = labelObject->GetAttribute(attrIt->c_str()); outfile << " " << *attrIt << " : "<< std::fixed << std::setprecision(6) << value << std::endl; } outfile << std::endl; } return EXIT_SUCCESS; } <commit_msg>ENH: useless include<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.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 above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include <iostream> #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" const unsigned int Dimension = 2; typedef unsigned short LabelType; typedef double PixelType; typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::Image<unsigned int,2> LabeledImageType; typedef LabelMapType::LabelObjectContainerType LabelObjectContainerType; typedef LabelObjectContainerType::const_iterator LabelObjectIterator; typedef otb::ImageFileReader<VectorImageType> ReaderType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType,VectorImageType> BandsStatisticsFilterType; int otbBandsStatisticsAttributesLabelMapFilterNew(int argc, char* argv[]) { BandsStatisticsFilterType::Pointer object = BandsStatisticsFilterType::New(); return EXIT_SUCCESS; } int otbBandsStatisticsAttributesLabelMapFilter(int argc, char* argv[]) { const char * infname = argv[1]; const char * lfname = argv[2]; const char * outfname = argv[3]; // Filters instanciation ReaderType::Pointer reader = ReaderType::New(); LabeledReaderType::Pointer labeledReader = LabeledReaderType::New(); LabelMapFilterType::Pointer filter = LabelMapFilterType::New(); BandsStatisticsFilterType::Pointer stats = BandsStatisticsFilterType::New(); // Read inputs reader->SetFileName(infname); labeledReader->SetFileName(lfname); // Make a LabelMap out of it filter->SetInput(labeledReader->GetOutput()); filter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); //Compute band statistics attributes stats->SetInput(filter->GetOutput()); stats->SetFeatureImage(reader->GetOutput()); stats->Update(); LabelMapType::Pointer labelMap = stats->GetOutput(); // Dump all results in the output file std::ofstream outfile(outfname); LabelObjectIterator it = labelMap->GetLabelObjectContainer().begin(); LabelObjectIterator end = labelMap->GetLabelObjectContainer().end(); for (; it != end; ++it) { LabelType label = it->first; LabelObjectType::Pointer labelObject = it->second; outfile << "Label " << label << " : " << std::endl; std::vector<std::string> attributes = labelObject->GetAvailableAttributes(); std::vector<std::string>::const_iterator attrIt = attributes.begin(); std::vector<std::string>::const_iterator attrEnd = attributes.end(); for (; attrIt != attrEnd; ++attrIt) { LabelObjectType::AttributesValueType value = labelObject->GetAttribute(attrIt->c_str()); outfile << " " << *attrIt << " : "<< std::fixed << std::setprecision(6) << value << std::endl; } outfile << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// @(#)root/g3d:$Id$ // Author: Rene Brun 14/09/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TRotMatrix.h" #include "TBuffer.h" #include "TClass.h" #include "TGeometry.h" #include "TMath.h" ClassImp(TRotMatrix) /** \class TRotMatrix \ingroup g3d Manages a detector rotation matrix. See class TGeometry. */ //////////////////////////////////////////////////////////////////////////////// /// RotMatrix default constructor. TRotMatrix::TRotMatrix() { for (int i=0;i<9;i++) fMatrix[i] = 0; fNumber = 0; fPhi = 0; fPsi = 0; fTheta = 0; fType = 0; } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor. TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t *matrix) :TNamed(name,title) { if (!matrix) { Error("ctor","No rotation is supplied"); return; } fNumber = 0; fPhi = 0; fPsi = 0; fTheta = 0; fType = 0; SetMatrix(matrix); if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor. TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t theta, Double_t phi, Double_t psi) :TNamed(name,title) { printf("ERROR: This form of TRotMatrix constructor not implemented yet\n"); Int_t i; fTheta = theta; fPhi = phi; fPsi = psi; fType = 2; for (i=0;i<9;i++) fMatrix[i] = 0; fMatrix[0] = 1; fMatrix[4] = 1; fMatrix[8] = 1; if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor defined a la GEANT. /// /// The TRotMatrix constructor with six angles uses the GEANT convention: /// /// theta1 is the polar angle of the x-prim axis in the main reference system /// (MRS), theta2 and theta3 have the same meaning for the y-prim and z-prim /// axis. /// /// Phi1 is the azimuthal angle of the x-prim in the MRS and phi2 and phi3 /// have the same meaning for y-prim and z-prim. /// /// /// for example, the unit matrix is defined in the following way. /// ~~~ {.cpp} /// x-prim || x, y-prim || y, z-prim || z /// /// means: theta1=90, theta2=90, theta3=0, phi1=0, phi2=90, phi3=0 /// ~~~ TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t theta1, Double_t phi1 , Double_t theta2, Double_t phi2 , Double_t theta3, Double_t phi3) :TNamed(name,title) { SetAngles(theta1,phi1,theta2,phi2,theta3,phi3); if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix default destructor. TRotMatrix::~TRotMatrix() { if (gGeometry) gGeometry->GetListOfMatrices()->Remove(this); } //////////////////////////////////////////////////////////////////////////////// /// Returns the value of the determinant of this matrix Double_t TRotMatrix::Determinant() const { return fMatrix[0] * (fMatrix[4]*fMatrix[8] - fMatrix[7]*fMatrix[5]) - fMatrix[3] * (fMatrix[1]*fMatrix[8] - fMatrix[7]*fMatrix[2]) + fMatrix[6] * (fMatrix[1]*fMatrix[5] - fMatrix[4]*fMatrix[2]); } //////////////////////////////////////////////////////////////////////////////// /// Convert this matrix to the OpenGL [4x4] /// /// ~~~ {.cpp} /// [ fMatrix[0] fMatrix[1] fMatrix[2] 0 ] /// [ fMatrix[3] fMatrix[4] fMatrix[5] 0 ] /// [ fMatrix[6] fMatrix[7] fMatrix[8] 0 ] /// [ 0 0 0 1 ] /// ~~~ /// /// Input: /// /// Double_t *rGLMatrix: pointer to Double_t 4x4 buffer array /// /// Return: /// /// Double_t*: pointer to the input buffer Double_t* TRotMatrix::GetGLMatrix(Double_t *rGLMatrix) const { Double_t *glmatrix = rGLMatrix; const Double_t *matrix = fMatrix; if (rGLMatrix) { for (Int_t i=0;i<3;i++) { for (Int_t j=0;j<3;j++) memcpy(glmatrix,matrix,3*sizeof(Double_t)); matrix += 3; glmatrix += 3; *glmatrix = 0.0; glmatrix++; } for (Int_t j=0;j<3;j++) { *glmatrix = 0.0; glmatrix++; } *glmatrix = 1.0; } return rGLMatrix; } //////////////////////////////////////////////////////////////////////////////// /// theta1 is the polar angle of the x-prim axis in the main reference system /// (MRS), theta2 and theta3 have the same meaning for the y-prim and z-prim /// axis. /// /// Phi1 is the azimuthal angle of the x-prim in the MRS and phi2 and phi3 /// have the same meaning for y-prim and z-prim. /// /// /// for example, the unit matrix is defined in the following way. /// /// ~~~ {.cpp} /// x-prim || x, y-prim || y, z-prim || z /// /// means: theta1=90, theta2=90, theta3=0, phi1=0, phi2=90, phi3=0 /// ~~~ const Double_t* TRotMatrix::SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2,Double_t theta3, Double_t phi3) { const Double_t degrad = 0.0174532925199432958; fTheta = theta1; fPhi = phi1; fPsi = theta2; fType = 2; if (!strcmp(GetName(),"Identity")) fType = 0; fMatrix[0] = TMath::Sin(theta1*degrad)*TMath::Cos(phi1*degrad); fMatrix[1] = TMath::Sin(theta1*degrad)*TMath::Sin(phi1*degrad); fMatrix[2] = TMath::Cos(theta1*degrad); fMatrix[3] = TMath::Sin(theta2*degrad)*TMath::Cos(phi2*degrad); fMatrix[4] = TMath::Sin(theta2*degrad)*TMath::Sin(phi2*degrad); fMatrix[5] = TMath::Cos(theta2*degrad); fMatrix[6] = TMath::Sin(theta3*degrad)*TMath::Cos(phi3*degrad); fMatrix[7] = TMath::Sin(theta3*degrad)*TMath::Sin(phi3*degrad); fMatrix[8] = TMath::Cos(theta3*degrad); SetReflection(); return fMatrix; } //////////////////////////////////////////////////////////////////////////////// /// copy predefined 3x3 matrix into TRotMatrix object void TRotMatrix::SetMatrix(const Double_t *matrix) { fTheta = 0; fPhi = 0; fPsi = 0; fType = 0; if (!matrix) return; fType = 2; memcpy(fMatrix,matrix,9*sizeof(Double_t)); SetReflection(); } //////////////////////////////////////////////////////////////////////////////// /// Checks whether the determinant of this /// matrix defines the reflection transformation /// and set the "reflection" flag if any void TRotMatrix::SetReflection() { ResetBit(kReflection); if (Determinant() < 0) { fType=1; SetBit(kReflection);} } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TRotMatrix. void TRotMatrix::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 1) { R__b.ReadClassBuffer(TRotMatrix::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TNamed::Streamer(R__b); R__b >> fNumber; R__b >> fType; R__b >> fTheta; R__b >> fPhi; R__b >> fPsi; R__b.ReadStaticArray(fMatrix); R__b.CheckByteCount(R__s, R__c, TRotMatrix::IsA()); //====end of old versions } else { R__b.WriteClassBuffer(TRotMatrix::Class(),this); } } <commit_msg>Rearrange the code to make sure the data members are initialised as requested by coverity<commit_after>// @(#)root/g3d:$Id$ // Author: Rene Brun 14/09/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TRotMatrix.h" #include "TBuffer.h" #include "TClass.h" #include "TGeometry.h" #include "TMath.h" ClassImp(TRotMatrix) /** \class TRotMatrix \ingroup g3d Manages a detector rotation matrix. See class TGeometry. */ //////////////////////////////////////////////////////////////////////////////// /// RotMatrix default constructor. TRotMatrix::TRotMatrix() { for (int i=0;i<9;i++) fMatrix[i] = 0; fNumber = 0; fPhi = 0; fPsi = 0; fTheta = 0; fType = 0; } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor. TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t *matrix) :TNamed(name,title) { fNumber = 0; fPhi = 0; fPsi = 0; fTheta = 0; fType = 0; if (!matrix) { Error("ctor","No rotation is supplied"); return; } SetMatrix(matrix); if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor. TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t theta, Double_t phi, Double_t psi) :TNamed(name,title) { printf("ERROR: This form of TRotMatrix constructor not implemented yet\n"); Int_t i; fTheta = theta; fPhi = phi; fPsi = psi; fType = 2; for (i=0;i<9;i++) fMatrix[i] = 0; fMatrix[0] = 1; fMatrix[4] = 1; fMatrix[8] = 1; if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix normal constructor defined a la GEANT. /// /// The TRotMatrix constructor with six angles uses the GEANT convention: /// /// theta1 is the polar angle of the x-prim axis in the main reference system /// (MRS), theta2 and theta3 have the same meaning for the y-prim and z-prim /// axis. /// /// Phi1 is the azimuthal angle of the x-prim in the MRS and phi2 and phi3 /// have the same meaning for y-prim and z-prim. /// /// /// for example, the unit matrix is defined in the following way. /// ~~~ {.cpp} /// x-prim || x, y-prim || y, z-prim || z /// /// means: theta1=90, theta2=90, theta3=0, phi1=0, phi2=90, phi3=0 /// ~~~ TRotMatrix::TRotMatrix(const char *name, const char *title, Double_t theta1, Double_t phi1 , Double_t theta2, Double_t phi2 , Double_t theta3, Double_t phi3) :TNamed(name,title) { SetAngles(theta1,phi1,theta2,phi2,theta3,phi3); if (!gGeometry) gGeometry = new TGeometry(); fNumber = gGeometry->GetListOfMatrices()->GetSize(); gGeometry->GetListOfMatrices()->Add(this); } //////////////////////////////////////////////////////////////////////////////// /// RotMatrix default destructor. TRotMatrix::~TRotMatrix() { if (gGeometry) gGeometry->GetListOfMatrices()->Remove(this); } //////////////////////////////////////////////////////////////////////////////// /// Returns the value of the determinant of this matrix Double_t TRotMatrix::Determinant() const { return fMatrix[0] * (fMatrix[4]*fMatrix[8] - fMatrix[7]*fMatrix[5]) - fMatrix[3] * (fMatrix[1]*fMatrix[8] - fMatrix[7]*fMatrix[2]) + fMatrix[6] * (fMatrix[1]*fMatrix[5] - fMatrix[4]*fMatrix[2]); } //////////////////////////////////////////////////////////////////////////////// /// Convert this matrix to the OpenGL [4x4] /// /// ~~~ {.cpp} /// [ fMatrix[0] fMatrix[1] fMatrix[2] 0 ] /// [ fMatrix[3] fMatrix[4] fMatrix[5] 0 ] /// [ fMatrix[6] fMatrix[7] fMatrix[8] 0 ] /// [ 0 0 0 1 ] /// ~~~ /// /// Input: /// /// Double_t *rGLMatrix: pointer to Double_t 4x4 buffer array /// /// Return: /// /// Double_t*: pointer to the input buffer Double_t* TRotMatrix::GetGLMatrix(Double_t *rGLMatrix) const { Double_t *glmatrix = rGLMatrix; const Double_t *matrix = fMatrix; if (rGLMatrix) { for (Int_t i=0;i<3;i++) { for (Int_t j=0;j<3;j++) memcpy(glmatrix,matrix,3*sizeof(Double_t)); matrix += 3; glmatrix += 3; *glmatrix = 0.0; glmatrix++; } for (Int_t j=0;j<3;j++) { *glmatrix = 0.0; glmatrix++; } *glmatrix = 1.0; } return rGLMatrix; } //////////////////////////////////////////////////////////////////////////////// /// theta1 is the polar angle of the x-prim axis in the main reference system /// (MRS), theta2 and theta3 have the same meaning for the y-prim and z-prim /// axis. /// /// Phi1 is the azimuthal angle of the x-prim in the MRS and phi2 and phi3 /// have the same meaning for y-prim and z-prim. /// /// /// for example, the unit matrix is defined in the following way. /// /// ~~~ {.cpp} /// x-prim || x, y-prim || y, z-prim || z /// /// means: theta1=90, theta2=90, theta3=0, phi1=0, phi2=90, phi3=0 /// ~~~ const Double_t* TRotMatrix::SetAngles(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2,Double_t theta3, Double_t phi3) { const Double_t degrad = 0.0174532925199432958; fTheta = theta1; fPhi = phi1; fPsi = theta2; fType = 2; if (!strcmp(GetName(),"Identity")) fType = 0; fMatrix[0] = TMath::Sin(theta1*degrad)*TMath::Cos(phi1*degrad); fMatrix[1] = TMath::Sin(theta1*degrad)*TMath::Sin(phi1*degrad); fMatrix[2] = TMath::Cos(theta1*degrad); fMatrix[3] = TMath::Sin(theta2*degrad)*TMath::Cos(phi2*degrad); fMatrix[4] = TMath::Sin(theta2*degrad)*TMath::Sin(phi2*degrad); fMatrix[5] = TMath::Cos(theta2*degrad); fMatrix[6] = TMath::Sin(theta3*degrad)*TMath::Cos(phi3*degrad); fMatrix[7] = TMath::Sin(theta3*degrad)*TMath::Sin(phi3*degrad); fMatrix[8] = TMath::Cos(theta3*degrad); SetReflection(); return fMatrix; } //////////////////////////////////////////////////////////////////////////////// /// copy predefined 3x3 matrix into TRotMatrix object void TRotMatrix::SetMatrix(const Double_t *matrix) { fTheta = 0; fPhi = 0; fPsi = 0; fType = 0; if (!matrix) return; fType = 2; memcpy(fMatrix,matrix,9*sizeof(Double_t)); SetReflection(); } //////////////////////////////////////////////////////////////////////////////// /// Checks whether the determinant of this /// matrix defines the reflection transformation /// and set the "reflection" flag if any void TRotMatrix::SetReflection() { ResetBit(kReflection); if (Determinant() < 0) { fType=1; SetBit(kReflection);} } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TRotMatrix. void TRotMatrix::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 1) { R__b.ReadClassBuffer(TRotMatrix::Class(), this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TNamed::Streamer(R__b); R__b >> fNumber; R__b >> fType; R__b >> fTheta; R__b >> fPhi; R__b >> fPsi; R__b.ReadStaticArray(fMatrix); R__b.CheckByteCount(R__s, R__c, TRotMatrix::IsA()); //====end of old versions } else { R__b.WriteClassBuffer(TRotMatrix::Class(),this); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeforms.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:17:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_ #define _XMLOFF_FORMS_OFFICEFORMS_HXX_ #ifndef _XMLOFF_FORMATTRIBUTES_HXX_ #include "formattributes.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef XMLOFF_FORMS_LOGGING_HXX #include "logging.hxx" #endif class SvXMLElementExport; class SvXMLExport; //......................................................................... namespace xmloff { //......................................................................... //===================================================================== //= OFormsRootImport //===================================================================== class OFormsRootImport :public SvXMLImportContext ,public OStackedLogging { public: TYPEINFO(); OFormsRootImport( SvXMLImport& _rImport, sal_uInt16 _nPrfx, const rtl::OUString& _rLocalName); virtual ~OFormsRootImport(); // SvXMLImportContext overriabled virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList ); virtual void EndElement(); protected: void implImportBool( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttributes, OfficeFormsAttributes _eAttribute, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault ); }; //===================================================================== //= OFormsRootExport //===================================================================== class OFormsRootExport { private: SvXMLElementExport* m_pImplElement; public: OFormsRootExport( SvXMLExport& _rExp ); ~OFormsRootExport(); private: void addModelAttributes(SvXMLExport& _rExp) SAL_THROW(()); void implExportBool( SvXMLExport& _rExp, OfficeFormsAttributes _eAttribute, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault ); }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_FORMS_OFFICEFORMS_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.6.162); FILE MERGED 2008/04/01 13:04:53 thb 1.6.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:13 rt 1.6.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeforms.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_ #define _XMLOFF_FORMS_OFFICEFORMS_HXX_ #include "formattributes.hxx" #include <xmloff/xmlictxt.hxx> #include "logging.hxx" class SvXMLElementExport; class SvXMLExport; //......................................................................... namespace xmloff { //......................................................................... //===================================================================== //= OFormsRootImport //===================================================================== class OFormsRootImport :public SvXMLImportContext ,public OStackedLogging { public: TYPEINFO(); OFormsRootImport( SvXMLImport& _rImport, sal_uInt16 _nPrfx, const rtl::OUString& _rLocalName); virtual ~OFormsRootImport(); // SvXMLImportContext overriabled virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList ); virtual void EndElement(); protected: void implImportBool( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttributes, OfficeFormsAttributes _eAttribute, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault ); }; //===================================================================== //= OFormsRootExport //===================================================================== class OFormsRootExport { private: SvXMLElementExport* m_pImplElement; public: OFormsRootExport( SvXMLExport& _rExp ); ~OFormsRootExport(); private: void addModelAttributes(SvXMLExport& _rExp) SAL_THROW(()); void implExportBool( SvXMLExport& _rExp, OfficeFormsAttributes _eAttribute, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault ); }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_FORMS_OFFICEFORMS_HXX_ <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "v8.h" #include "node.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <signal.h> #include <cxxabi.h> #include <dlfcn.h> extern "C" { void jsbacktrace(void); int main(int, char**); // Top of the stack. } namespace { #define OFFSET(base, addr) \ (static_cast<long>(static_cast<const char*>(addr) - \ static_cast<const char*>(base))) // Assumes -fno-omit-frame-pointer. struct Frame { const Frame* frame_pointer; const void* return_address; }; // Linked list. Wildly inefficient. struct Code { Code* next; const void* start; const void* end; char name[1]; // Variadic length. }; void sigabrt(int); void find_stack_top(const Frame* frame); void walk_stack_frames(unsigned skip, void (*cb)(const Frame* frame)); v8::Handle<v8::Value> backtrace(const v8::Arguments&); void print_stack_frame(const Frame* frame); bool print_c_frame(const Frame* frame, FILE* stream); bool print_js_frame(const Frame* frame, FILE* stream); Code* find_code(const void* addr); void add_code(const char* name, unsigned int namelen, const void* start, const void* end); void free_code(); void jit_code_event(const v8::JitCodeEvent* ev); struct Code* code_head; int stack_trace_index; v8::Local<v8::StackTrace> stack_trace; const Frame* stack_top = reinterpret_cast<const Frame*>(-1); void init(v8::Handle<v8::Object> module) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_flags = SA_RESETHAND; sa.sa_handler = sigabrt; sigaction(SIGABRT, &sa, NULL); walk_stack_frames(0, find_stack_top); module->Set(v8::String::New("backtrace"), v8::FunctionTemplate::New(backtrace)->GetFunction()); } void find_stack_top(const Frame* frame) { Dl_info info; if (dladdr(frame->return_address, &info) == 0) return; if (strcmp(info.dli_sname, "start") != 0) return; stack_top = frame->frame_pointer; } v8::Handle<v8::Value> backtrace(const v8::Arguments&) { jsbacktrace(); return v8::Undefined(); } void sigabrt(int) { jsbacktrace(); raise(SIGABRT); } // Externally visible. extern "C" void jsbacktrace(void) { walk_stack_frames(1, print_stack_frame); free_code(); } void print_stack_frame(const Frame* frame) { FILE* stream = stderr; if (print_c_frame(frame, stream)) return; if (print_js_frame(frame, stream)) return; // Unresolved. Just print the raw address. fprintf(stream, "%lx\n", reinterpret_cast<long>(frame->return_address)); } bool print_c_frame(const Frame* frame, FILE* stream) { Dl_info info; if (dladdr(frame->return_address, &info) == 0) return false; const char* name = info.dli_sname; const char* demangled_name = abi::__cxa_demangle(name, NULL, NULL, NULL); if (demangled_name != NULL) name = demangled_name; fprintf(stream, "%lx+%lx\t%s %s(%p)\n", reinterpret_cast<long>(info.dli_saddr), OFFSET(info.dli_saddr, frame->return_address), name, info.dli_fname, info.dli_fbase); if (name == demangled_name) free(const_cast<char*>(name)); return true; } bool print_js_frame(const Frame* frame, FILE* stream) { if (code_head == NULL) { // Lazy init. v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventEnumExisting, jit_code_event); v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, NULL); stack_trace = v8::StackTrace::CurrentStackTrace(64); stack_trace_index = 0; } Code* code = find_code(frame->return_address); if (code == NULL) return false; if (stack_trace_index < stack_trace->GetFrameCount()) { v8::Local<v8::StackFrame> js_frame = stack_trace->GetFrame(stack_trace_index++); v8::String::Utf8Value function_name(js_frame->GetFunctionName()); if (function_name.length() > 0) { v8::String::Utf8Value script_name(js_frame->GetScriptName()); fprintf(stream, "%lx+%lx\t%s %s:%d:%d\n", reinterpret_cast<long>(code->start), OFFSET(code->start, frame->return_address), *function_name, *script_name, js_frame->GetLineNumber(), js_frame->GetColumn()); return true; } } fprintf(stream, "%lx+%lx\t%s\n", reinterpret_cast<long>(code->start), OFFSET(code->start, frame->return_address), code->name); return true; } Code* find_code(const void* addr) { for (Code* code = code_head; code != NULL; code = code->next) if (code->start <= addr && code->end >= addr) return code; return NULL; } void add_code(const char* name, unsigned int namelen, const void* start, const void* end) { Code* code = static_cast<Code*>(malloc(sizeof(*code) + namelen)); if (code == NULL) return; memcpy(code->name, name, namelen); code->name[namelen] = '\0'; code->start = start; code->end = end; code->next = code_head; code_head = code; } void free_code() { while (code_head != NULL) { Code* code = code_head; code_head = code->next; free(code); } } void jit_code_event(const v8::JitCodeEvent* ev) { if (ev->type == v8::JitCodeEvent::CODE_ADDED) { add_code(ev->name.str, ev->name.len, ev->code_start, static_cast<const char*>(ev->code_start) + ev->code_len); } } __attribute__((noinline)) void walk_stack_frames(unsigned skip, void (*cb)(const Frame* frame)) { const Frame* frame; __asm__ __volatile__ ("mov %%rbp, %0" : "=g" (frame)); do if (skip == 0) cb(frame); else skip -= 1; while ((frame = frame->frame_pointer) < stack_top); } } // anonymous namespace NODE_MODULE(backtrace, init) <commit_msg>backtrace: fix NULL pointer derefs on linux<commit_after>/* * Copyright (c) 2013, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "v8.h" #include "node.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <signal.h> #include <cxxabi.h> #include <dlfcn.h> extern "C" { void jsbacktrace(void); int main(int, char**); // Top of the stack. } namespace { #define OFFSET(base, addr) \ (static_cast<long>(static_cast<const char*>(addr) - \ static_cast<const char*>(base))) // Assumes -fno-omit-frame-pointer. struct Frame { const Frame* frame_pointer; const void* return_address; }; // Linked list. Wildly inefficient. struct Code { Code* next; const void* start; const void* end; char name[1]; // Variadic length. }; void sigabrt(int); void find_stack_top(const Frame* frame); void walk_stack_frames(unsigned skip, void (*cb)(const Frame* frame)); v8::Handle<v8::Value> backtrace(const v8::Arguments&); void print_stack_frame(const Frame* frame); bool print_c_frame(const Frame* frame, FILE* stream); bool print_js_frame(const Frame* frame, FILE* stream); Code* find_code(const void* addr); void add_code(const char* name, unsigned int namelen, const void* start, const void* end); void free_code(); void jit_code_event(const v8::JitCodeEvent* ev); struct Code* code_head; int stack_trace_index; v8::Local<v8::StackTrace> stack_trace; const Frame* stack_top = reinterpret_cast<const Frame*>(-1); #if defined(__linux__) const char entry_point[] = "main"; #elif defined(__APPLE__) const char entry_point[] = "start"; #else # error "Unsupported platform. Only Linux and OS X work." #endif void init(v8::Handle<v8::Object> module) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_flags = SA_RESETHAND; sa.sa_handler = sigabrt; sigaction(SIGABRT, &sa, NULL); walk_stack_frames(0, find_stack_top); module->Set(v8::String::New("backtrace"), v8::FunctionTemplate::New(backtrace)->GetFunction()); } void find_stack_top(const Frame* frame) { Dl_info info; if (dladdr(frame->return_address, &info) == 0) return; if (info.dli_sname == NULL) return; if (strcmp(info.dli_sname, entry_point) != 0) return; stack_top = frame->frame_pointer; } v8::Handle<v8::Value> backtrace(const v8::Arguments&) { jsbacktrace(); return v8::Undefined(); } void sigabrt(int) { jsbacktrace(); raise(SIGABRT); } // Externally visible. extern "C" void jsbacktrace(void) { walk_stack_frames(1, print_stack_frame); free_code(); } void print_stack_frame(const Frame* frame) { FILE* stream = stderr; if (print_c_frame(frame, stream)) return; if (print_js_frame(frame, stream)) return; // Unresolved. Just print the raw address. fprintf(stream, "%lx\n", reinterpret_cast<long>(frame->return_address)); } bool print_c_frame(const Frame* frame, FILE* stream) { Dl_info info; if (dladdr(frame->return_address, &info) == 0) return false; const char* name = info.dli_sname; const char* demangled_name = abi::__cxa_demangle(name, NULL, NULL, NULL); if (demangled_name != NULL) name = demangled_name; fprintf(stream, "%lx+%lx\t%s %s(%p)\n", reinterpret_cast<long>(info.dli_saddr), OFFSET(info.dli_saddr, frame->return_address), name, info.dli_fname, info.dli_fbase); if (name == demangled_name) free(const_cast<char*>(name)); return true; } bool print_js_frame(const Frame* frame, FILE* stream) { if (code_head == NULL) { // Lazy init. v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventEnumExisting, jit_code_event); v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, NULL); stack_trace = v8::StackTrace::CurrentStackTrace(64); stack_trace_index = 0; } Code* code = find_code(frame->return_address); if (code == NULL) return false; if (stack_trace_index < stack_trace->GetFrameCount()) { v8::Local<v8::StackFrame> js_frame = stack_trace->GetFrame(stack_trace_index++); v8::String::Utf8Value function_name(js_frame->GetFunctionName()); if (function_name.length() > 0) { v8::String::Utf8Value script_name(js_frame->GetScriptName()); fprintf(stream, "%lx+%lx\t%s %s:%d:%d\n", reinterpret_cast<long>(code->start), OFFSET(code->start, frame->return_address), *function_name, *script_name, js_frame->GetLineNumber(), js_frame->GetColumn()); return true; } } fprintf(stream, "%lx+%lx\t%s\n", reinterpret_cast<long>(code->start), OFFSET(code->start, frame->return_address), code->name); return true; } Code* find_code(const void* addr) { for (Code* code = code_head; code != NULL; code = code->next) if (code->start <= addr && code->end >= addr) return code; return NULL; } void add_code(const char* name, unsigned int namelen, const void* start, const void* end) { Code* code = static_cast<Code*>(malloc(sizeof(*code) + namelen)); if (code == NULL) return; memcpy(code->name, name, namelen); code->name[namelen] = '\0'; code->start = start; code->end = end; code->next = code_head; code_head = code; } void free_code() { while (code_head != NULL) { Code* code = code_head; code_head = code->next; free(code); } } void jit_code_event(const v8::JitCodeEvent* ev) { if (ev->type == v8::JitCodeEvent::CODE_ADDED) { add_code(ev->name.str, ev->name.len, ev->code_start, static_cast<const char*>(ev->code_start) + ev->code_len); } } __attribute__((noinline)) void walk_stack_frames(unsigned skip, void (*cb)(const Frame* frame)) { const Frame* frame; __asm__ __volatile__ ("mov %%rbp, %0" : "=g" (frame)); do if (skip == 0) cb(frame); else skip -= 1; while ((frame = frame->frame_pointer) < stack_top); } } // anonymous namespace NODE_MODULE(backtrace, init) <|endoftext|>
<commit_before>/* Copyright (C) 2006 Matthias Kretz <[email protected]> Copyright (C) 2009 Martin Sandsmark <[email protected]> Copyright (C) 2011 Harald Sitter <[email protected]> Copyright (C) 2011 Alessandro Siniscalchi <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "audiodataoutput.h" #include "gsthelper.h" #include "medianode.h" #include <QtCore/QVector> #include <QtCore/QMap> #include <phonon/audiooutput.h> #include <gst/gstghostpad.h> #include <gst/gstutils.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { AudioDataOutput::AudioDataOutput(Backend *backend, QObject *parent) : QObject(parent) , MediaNode(backend, AudioSink) { static int count = 0; m_name = "AudioDataOutput" + QString::number(count++); m_queue = gst_bin_new(NULL); gst_object_ref(GST_OBJECT(m_queue)); gst_object_sink(GST_OBJECT(m_queue)); GstElement* sink = gst_element_factory_make("fakesink", NULL); GstElement* queue = gst_element_factory_make("queue", NULL); GstElement* convert = gst_element_factory_make("audioconvert", NULL); g_signal_connect(sink, "handoff", G_CALLBACK(processBuffer), this); g_object_set(G_OBJECT(sink), "signal-handoffs", true, NULL); //G_BYTE_ORDER is the host machine's endianess GstCaps *caps = gst_caps_new_simple("audio/x-raw-int", "endianess", G_TYPE_INT, G_BYTE_ORDER, "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, NULL); gst_bin_add_many(GST_BIN(m_queue), sink, convert, queue, NULL); gst_element_link(queue, convert); gst_element_link_filtered(convert, sink, caps); gst_caps_unref(caps); GstPad *inputpad = gst_element_get_static_pad(queue, "sink"); gst_element_add_pad(m_queue, gst_ghost_pad_new("sink", inputpad)); gst_object_unref(inputpad); g_object_set(G_OBJECT(sink), "sync", true, NULL); m_isValid = true; } AudioDataOutput::~AudioDataOutput() { gst_element_set_state(m_queue, GST_STATE_NULL); gst_object_unref(m_queue); } void AudioDataOutput::setDataSize(int size) { m_dataSize = size; } int AudioDataOutput::dataSize() const { return m_dataSize; } int AudioDataOutput::sampleRate() const { return 44100; } inline void AudioDataOutput::convertAndEmit() { QMap<Phonon::AudioDataOutput::Channel, QVector<qint16> > map; for (int i = 0 ; i < m_channels ; ++i) { map.insert(static_cast<Phonon::AudioDataOutput::Channel>(i), m_channelBuffers[i]); Q_ASSERT(i == 0 || m_channelBuffers[i - 1].size() == m_channelBuffers[i].size()); } emit dataReady(map); } void AudioDataOutput::processBuffer(GstElement*, GstBuffer* buffer, GstPad*, gpointer gThat) { // TODO emit endOfMedia AudioDataOutput *that = static_cast<AudioDataOutput *>(gThat); // Copiend locally to avoid multithead problems qint32 dataSize = that->m_dataSize; if (dataSize == 0) return; // determine the number of channels GstStructure *structure = gst_caps_get_structure(GST_BUFFER_CAPS(buffer), 0); gst_structure_get_int(structure, "channels", &that->m_channels); // Let's get the buffers gint16 *gstBufferData = reinterpret_cast<gint16 *>(GST_BUFFER_DATA(buffer)); guint gstBufferSize = GST_BUFFER_SIZE(buffer) / sizeof(gint16); if (gstBufferSize == 0) { qWarning() << Q_FUNC_INFO << ": received a buffer of 0 size ... doing nothing"; return; } if ((gstBufferSize % that->m_channels) != 0) { qWarning() << Q_FUNC_INFO << ": corrupted data"; return; } // I set the number of channels if (that->m_channelBuffers.size() != that->m_channels) that->m_channelBuffers.resize(that->m_channels); // check how many emits I will perform int nBlockToSend = (that->m_pendingData.size() + gstBufferSize) / (dataSize * that->m_channels); if (nBlockToSend == 0) { // add data to pending buffer for (quint32 i = 0; i < gstBufferSize ; ++i) { that->m_pendingData.append(gstBufferData[i]); return; } } // SENDING DATA // 1) I empty the stored data if (that->m_pendingData.size() != 0) { for (int i = 0; i < that->m_pendingData.size(); i += that->m_channels) { //TODO: Figure out why it crashes without the second test (bug #279791) for (int j = 0; (j < that->m_channels) && (i+j < that->m_pendingData.size()); ++j) { that->m_channelBuffers[j].append(that->m_pendingData[i+j]); } } if (that->m_pendingData.capacity() != dataSize) that->m_pendingData.reserve(dataSize); that->m_pendingData.resize(0); } // 2) I fill with fresh data and send for (int i = 0 ; i < that->m_channels ; ++i) { if (that->m_channelBuffers[i].capacity() != dataSize) that->m_channelBuffers.reserve(dataSize); } quint32 bufferPosition = 0; for (int i = 0 ; i < nBlockToSend ; ++i) { for ( ; (that->m_channelBuffers[0].size() < dataSize) && (bufferPosition < gstBufferSize) ; bufferPosition += that->m_channels ) { for (int j = 0 ; j < that->m_channels ; ++j) { that->m_channelBuffers[j].append(gstBufferData[bufferPosition+j]); } } that->convertAndEmit(); for (int j = 0 ; j < that->m_channels ; ++j) { // QVector::resize doesn't reallocate the buffer that->m_channelBuffers[j].resize(0); } } // 3) I store the rest of data while (bufferPosition < gstBufferSize) { that->m_pendingData.append(gstBufferData[bufferPosition]); ++bufferPosition; } } }} //namespace Phonon::Gstreamer QT_END_NAMESPACE QT_END_HEADER #include "moc_audiodataoutput.cpp" <commit_msg>fix crash due to wrong placed return<commit_after>/* Copyright (C) 2006 Matthias Kretz <[email protected]> Copyright (C) 2009 Martin Sandsmark <[email protected]> Copyright (C) 2011 Harald Sitter <[email protected]> Copyright (C) 2011 Alessandro Siniscalchi <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "audiodataoutput.h" #include "gsthelper.h" #include "medianode.h" #include <QtCore/QVector> #include <QtCore/QMap> #include <phonon/audiooutput.h> #include <gst/gstghostpad.h> #include <gst/gstutils.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { AudioDataOutput::AudioDataOutput(Backend *backend, QObject *parent) : QObject(parent) , MediaNode(backend, AudioSink) { static int count = 0; m_name = "AudioDataOutput" + QString::number(count++); m_queue = gst_bin_new(NULL); gst_object_ref(GST_OBJECT(m_queue)); gst_object_sink(GST_OBJECT(m_queue)); GstElement* sink = gst_element_factory_make("fakesink", NULL); GstElement* queue = gst_element_factory_make("queue", NULL); GstElement* convert = gst_element_factory_make("audioconvert", NULL); g_signal_connect(sink, "handoff", G_CALLBACK(processBuffer), this); g_object_set(G_OBJECT(sink), "signal-handoffs", true, NULL); //G_BYTE_ORDER is the host machine's endianess GstCaps *caps = gst_caps_new_simple("audio/x-raw-int", "endianess", G_TYPE_INT, G_BYTE_ORDER, "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, NULL); gst_bin_add_many(GST_BIN(m_queue), sink, convert, queue, NULL); gst_element_link(queue, convert); gst_element_link_filtered(convert, sink, caps); gst_caps_unref(caps); GstPad *inputpad = gst_element_get_static_pad(queue, "sink"); gst_element_add_pad(m_queue, gst_ghost_pad_new("sink", inputpad)); gst_object_unref(inputpad); g_object_set(G_OBJECT(sink), "sync", true, NULL); m_isValid = true; } AudioDataOutput::~AudioDataOutput() { gst_element_set_state(m_queue, GST_STATE_NULL); gst_object_unref(m_queue); } void AudioDataOutput::setDataSize(int size) { m_dataSize = size; } int AudioDataOutput::dataSize() const { return m_dataSize; } int AudioDataOutput::sampleRate() const { return 44100; } inline void AudioDataOutput::convertAndEmit() { QMap<Phonon::AudioDataOutput::Channel, QVector<qint16> > map; for (int i = 0 ; i < m_channels ; ++i) { map.insert(static_cast<Phonon::AudioDataOutput::Channel>(i), m_channelBuffers[i]); Q_ASSERT(i == 0 || m_channelBuffers[i - 1].size() == m_channelBuffers[i].size()); } emit dataReady(map); } void AudioDataOutput::processBuffer(GstElement*, GstBuffer* buffer, GstPad*, gpointer gThat) { // TODO emit endOfMedia AudioDataOutput *that = static_cast<AudioDataOutput *>(gThat); // Copiend locally to avoid multithead problems qint32 dataSize = that->m_dataSize; if (dataSize == 0) return; // determine the number of channels GstStructure *structure = gst_caps_get_structure(GST_BUFFER_CAPS(buffer), 0); gst_structure_get_int(structure, "channels", &that->m_channels); // Let's get the buffers gint16 *gstBufferData = reinterpret_cast<gint16 *>(GST_BUFFER_DATA(buffer)); guint gstBufferSize = GST_BUFFER_SIZE(buffer) / sizeof(gint16); if (gstBufferSize == 0) { qWarning() << Q_FUNC_INFO << ": received a buffer of 0 size ... doing nothing"; return; } if ((gstBufferSize % that->m_channels) != 0) { qWarning() << Q_FUNC_INFO << ": corrupted data"; return; } // I set the number of channels if (that->m_channelBuffers.size() != that->m_channels) that->m_channelBuffers.resize(that->m_channels); // check how many emits I will perform int nBlockToSend = (that->m_pendingData.size() + gstBufferSize) / (dataSize * that->m_channels); if (nBlockToSend == 0) { // add data to pending buffer for (quint32 i = 0; i < gstBufferSize ; ++i) { #warning should be QBA, so we can work with append(buffer, size) that->m_pendingData.append(gstBufferData[i]); } return; } // SENDING DATA // 1) I empty the stored data if (that->m_pendingData.size() != 0) { for (int i = 0; i < that->m_pendingData.size(); i += that->m_channels) { for (int j = 0; j < that->m_channels; ++j) { that->m_channelBuffers[j].append(that->m_pendingData[i+j]); } } if (that->m_pendingData.capacity() != dataSize) that->m_pendingData.reserve(dataSize); that->m_pendingData.resize(0); } // 2) I fill with fresh data and send for (int i = 0 ; i < that->m_channels ; ++i) { if (that->m_channelBuffers[i].capacity() != dataSize) that->m_channelBuffers.reserve(dataSize); } quint32 bufferPosition = 0; for (int i = 0 ; i < nBlockToSend ; ++i) { for ( ; (that->m_channelBuffers[0].size() < dataSize) && (bufferPosition < gstBufferSize) ; bufferPosition += that->m_channels ) { for (int j = 0 ; j < that->m_channels ; ++j) { that->m_channelBuffers[j].append(gstBufferData[bufferPosition+j]); } } that->convertAndEmit(); for (int j = 0 ; j < that->m_channels ; ++j) { // QVector::resize doesn't reallocate the buffer that->m_channelBuffers[j].resize(0); } } // 3) I store the rest of data while (bufferPosition < gstBufferSize) { that->m_pendingData.append(gstBufferData[bufferPosition]); ++bufferPosition; } } }} //namespace Phonon::Gstreamer QT_END_NAMESPACE QT_END_HEADER #include "moc_audiodataoutput.cpp" <|endoftext|>
<commit_before><commit_msg>vcl: PVS-Studio V595 'mpImplWin' pointer could be null<commit_after><|endoftext|>
<commit_before>#include <PCU.h> #include <MeshSim.h> #include <SimPartitionedMesh.h> #include <SimUtil.h> #include <apfSIM.h> #include <apfMDS.h> #include <gmi.h> #include <gmi_sim.h> #include <apf.h> #include <apfConvert.h> #include <apfMesh2.h> #include <ma.h> #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> static void fixMatches(apf::Mesh2* m) { if (m->hasMatching()) { if (apf::alignMdsMatches(m)) printf("fixed misaligned matches\n"); else printf("matches were aligned\n"); assert( ! apf::alignMdsMatches(m)); } } static void fixPyramids(apf::Mesh2* m) { if (m->getDimension() != 3) return; /* no pyramids exist in 2D */ if (apf::countEntitiesOfType(m, apf::Mesh::HEX)) return; /* meshadapt can't even look at hexes */ ma::Input* in = ma::configureIdentity(m); in->shouldCleanupLayer = true; ma::adapt(in); } int main(int argc, char** argv) { MPI_Init(&argc, &argv); PCU_Comm_Init(); SimUtil_start(); Sim_readLicenseFile(NULL); SimPartitionedMesh_start(&argc,&argv); const char* gmi_path = NULL; const char* sms_path = NULL; const char* smb_path = NULL; bool should_fix_pyramids = true; bool found_bad_arg = false; for (int i = 1; i < argc; ++i) { if (!gmi_path) { gmi_path = argv[i]; } else if (!sms_path) { sms_path = argv[i]; } else if (!smb_path) { smb_path = argv[i]; } else if (!strcmp(argv[i], "--no-pyramid-fix")) { should_fix_pyramids = false; } else { if(!PCU_Comm_Self()) std::cerr << "bad argument \"" << argv[i] << "\"\n"; found_bad_arg = true; } } if (!gmi_path || !sms_path || !smb_path || found_bad_arg) { if(!PCU_Comm_Self()) { std::cerr << "usage: " << argv[0] << " [options] <model file> <simmetrix mesh> <scorec mesh>\n"; std::cerr << "options:\n"; std::cerr << " --no-pyramid-fix Disable quad-connected pyramid tetrahedronization\n"; } return EXIT_FAILURE; } gmi_sim_start(); gmi_register_sim(); pProgress progress = Progress_new(); Progress_setDefaultCallback(progress); gmi_model* mdl = gmi_load(gmi_path); pGModel simModel = gmi_export_sim(mdl); pParMesh sim_mesh = PM_load(sms_path, sthreadNone, simModel, progress); apf::Mesh* simApfMesh = apf::createMesh(sim_mesh); apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh); apf::printStats(mesh); apf::destroyMesh(simApfMesh); M_release(sim_mesh); fixMatches(mesh); if (should_fix_pyramids) fixPyramids(mesh); mesh->verify(); mesh->writeNative(smb_path); mesh->destroyNative(); apf::destroyMesh(mesh); Progress_delete(progress); gmi_sim_stop(); SimPartitionedMesh_stop(); Sim_unregisterAllKeys(); SimUtil_stop(); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>fix --no-pyramid-fix<commit_after>#include <PCU.h> #include <MeshSim.h> #include <SimPartitionedMesh.h> #include <SimUtil.h> #include <apfSIM.h> #include <apfMDS.h> #include <gmi.h> #include <gmi_sim.h> #include <apf.h> #include <apfConvert.h> #include <apfMesh2.h> #include <ma.h> #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> static void fixMatches(apf::Mesh2* m) { if (m->hasMatching()) { if (apf::alignMdsMatches(m)) printf("fixed misaligned matches\n"); else printf("matches were aligned\n"); assert( ! apf::alignMdsMatches(m)); } } static void fixPyramids(apf::Mesh2* m) { if (m->getDimension() != 3) return; /* no pyramids exist in 2D */ if (apf::countEntitiesOfType(m, apf::Mesh::HEX)) return; /* meshadapt can't even look at hexes */ ma::Input* in = ma::configureIdentity(m); in->shouldCleanupLayer = true; ma::adapt(in); } int main(int argc, char** argv) { MPI_Init(&argc, &argv); PCU_Comm_Init(); SimUtil_start(); Sim_readLicenseFile(NULL); SimPartitionedMesh_start(&argc,&argv); const char* gmi_path = NULL; const char* sms_path = NULL; const char* smb_path = NULL; bool should_fix_pyramids = true; bool found_bad_arg = false; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "--no-pyramid-fix")) { should_fix_pyramids = false; std::cerr << "found " << argv[i] << '\n'; } else if (!gmi_path) { gmi_path = argv[i]; std::cerr << "gmi_path " << gmi_path << '\n'; } else if (!sms_path) { sms_path = argv[i]; std::cerr << "sms_path " << sms_path << '\n'; } else if (!smb_path) { smb_path = argv[i]; std::cerr << "smb_path " << smb_path << '\n'; } else { if(!PCU_Comm_Self()) std::cerr << "bad argument \"" << argv[i] << "\"\n"; found_bad_arg = true; } } if (!gmi_path || !sms_path || !smb_path || found_bad_arg) { if(!PCU_Comm_Self()) { std::cerr << "usage: " << argv[0] << " [options] <model file> <simmetrix mesh> <scorec mesh>\n"; std::cerr << "options:\n"; std::cerr << " --no-pyramid-fix Disable quad-connected pyramid tetrahedronization\n"; } return EXIT_FAILURE; } gmi_sim_start(); gmi_register_sim(); pProgress progress = Progress_new(); Progress_setDefaultCallback(progress); gmi_model* mdl = gmi_load(gmi_path); pGModel simModel = gmi_export_sim(mdl); pParMesh sim_mesh = PM_load(sms_path, sthreadNone, simModel, progress); apf::Mesh* simApfMesh = apf::createMesh(sim_mesh); apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh); apf::printStats(mesh); apf::destroyMesh(simApfMesh); M_release(sim_mesh); fixMatches(mesh); if (should_fix_pyramids) fixPyramids(mesh); mesh->verify(); mesh->writeNative(smb_path); mesh->destroyNative(); apf::destroyMesh(mesh); Progress_delete(progress); gmi_sim_stop(); SimPartitionedMesh_stop(); Sim_unregisterAllKeys(); SimUtil_stop(); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before>#include"CThreadList.h" #include<utility> namespace nThread { template<class T> template<class ... Args> void CThreadList<T>::emplace_back(Args &&...args) { std::lock_guard<std::mutex> lock{insertMut_}; list_.emplace_back(std::forward<Args>(args)...); insert_.notify_all(); } template<class T> template<class UnaryPred> void CThreadList<T>::remove_if(UnaryPred pred) { std::lock_guard<std::mutex> lock{insertMut_}; list_.remove_if(pred); } template<class T> T CThreadList<T>::wait_and_pop() { std::unique_lock<std::mutex> lock{insertMut_}; insert_.wait(lock,[&]{return size();}); const auto temp{list_.front()}; list_.pop_front(); lock.unlock(); return temp; } }<commit_msg>fix wait_and_pop<commit_after>#include"CThreadList.h" #include<utility> namespace nThread { template<class T> template<class ... Args> void CThreadList<T>::emplace_back(Args &&...args) { std::lock_guard<std::mutex> lock{insertMut_}; list_.emplace_back(std::forward<Args>(args)...); insert_.notify_all(); } template<class T> template<class UnaryPred> void CThreadList<T>::remove_if(UnaryPred pred) { std::lock_guard<std::mutex> lock{insertMut_}; list_.remove_if(pred); } template<class T> T CThreadList<T>::wait_and_pop() { std::unique_lock<std::mutex> lock{insertMut_}; insert_.wait(lock,[&]{return size();}); const auto temp{std::move(list_.front())}; list_.pop_front(); lock.unlock(); return temp; } }<|endoftext|>
<commit_before><commit_msg>VclPtr: crash on exit on impress<commit_after><|endoftext|>
<commit_before>// Copyright 2011 Google // 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 <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include "base/file.h" #include "base/logging.h" namespace operations_research { File::File(FILE* const f_des, const std::string& name) : f_(f_des), name_(name) {} bool File::Delete(char* const name) { return remove(name) == 0; } bool File::Exists(char* const name) { return access(name, F_OK) == 0; } size_t File::Size() { struct stat f_stat; stat(name_.c_str(), &f_stat); return f_stat.st_size; } bool File::Flush() { return fflush(f_) == 0; } bool File::Close() { if (fclose(f_) == 0) { f_ = NULL; return true; } else { return false; } } void File::ReadOrDie(void* const buf, size_t size) { CHECK_EQ(fread(buf, 1, size, f_), size); } size_t File::Read(void* const buf, size_t size) { return fread(buf, 1, size, f_); } void File::WriteOrDie(const void* const buf, size_t size) { CHECK_EQ(fwrite(buf, 1, size, f_), size); } size_t File::Write(const void* const buf, size_t size) { return fwrite(buf, 1, size, f_); } File* File::OpenOrDie(const char* const name, const char* const flag) { FILE* const f_des = fopen(name, flag); if (f_des == NULL) { std::cerr << "Cannot open " << name; exit(1); } File* const f = new File(f_des, name); return f; } File* File::Open(const char* const name, const char* const flag) { FILE* const f_des = fopen(name, flag); if (f_des == NULL) return NULL; File* const f = new File(f_des, name); return f; } bool File::ReadLine(std::string* const line) { char buff[1000000]; char* const result = fgets(buff, 1000000, f_); if (result == NULL) { return false; } else { *line = std::string(buff); return true; } } size_t File::WriteString(const std::string& line) { return Write(line.c_str(), line.size()); } bool File::WriteLine(const std::string& line) { if (Write(line.c_str(), line.size()) != line.size()) return false; return Write("\n", 1) == 1; } std::string File::CreateFileName() const { return name_; } bool File::Open() const { return f_ != NULL; } void File::Init() {} } // namespace operations_research <commit_msg>fix windows compilation<commit_after>// Copyright 2011 Google // 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 <string.h> #include <sys/stat.h> #include <sys/types.h> #if defined(_MSC_VER) #include <io.h> #define access _access #define F_OK 0 #else #include <unistd.h> #endif #include <string> #include "base/file.h" #include "base/logging.h" namespace operations_research { File::File(FILE* const f_des, const std::string& name) : f_(f_des), name_(name) {} bool File::Delete(char* const name) { return remove(name) == 0; } bool File::Exists(char* const name) { return access(name, F_OK) == 0; } size_t File::Size() { struct stat f_stat; stat(name_.c_str(), &f_stat); return f_stat.st_size; } bool File::Flush() { return fflush(f_) == 0; } bool File::Close() { if (fclose(f_) == 0) { f_ = NULL; return true; } else { return false; } } void File::ReadOrDie(void* const buf, size_t size) { CHECK_EQ(fread(buf, 1, size, f_), size); } size_t File::Read(void* const buf, size_t size) { return fread(buf, 1, size, f_); } void File::WriteOrDie(const void* const buf, size_t size) { CHECK_EQ(fwrite(buf, 1, size, f_), size); } size_t File::Write(const void* const buf, size_t size) { return fwrite(buf, 1, size, f_); } File* File::OpenOrDie(const char* const name, const char* const flag) { FILE* const f_des = fopen(name, flag); if (f_des == NULL) { std::cerr << "Cannot open " << name; exit(1); } File* const f = new File(f_des, name); return f; } File* File::Open(const char* const name, const char* const flag) { FILE* const f_des = fopen(name, flag); if (f_des == NULL) return NULL; File* const f = new File(f_des, name); return f; } bool File::ReadLine(std::string* const line) { char buff[1000000]; char* const result = fgets(buff, 1000000, f_); if (result == NULL) { return false; } else { *line = std::string(buff); return true; } } size_t File::WriteString(const std::string& line) { return Write(line.c_str(), line.size()); } bool File::WriteLine(const std::string& line) { if (Write(line.c_str(), line.size()) != line.size()) return false; return Write("\n", 1) == 1; } std::string File::CreateFileName() const { return name_; } bool File::Open() const { return f_ != NULL; } void File::Init() {} } // namespace operations_research <|endoftext|>
<commit_before>/*************************************************************************** utilities.cpp - description copyright : (C) 1999 by Christian Thurner email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdio.h> #include <ctype.h> #include <qdir.h> #include <klocale.h> #include <kmessagebox.h> #include "utilities.h" #include "knode.h" #include "knstringsplitter.h" /* bool stripCRLF(char *str) { int pos=strlen(str)-1; while(str[pos]!='\n') pos--; //if(str[pos]=='\n') { str[pos--]='\0'; if(str[pos]=='\r') str[pos]='\0'; return true; //} //else return false; } bool stripCRLF(QCString &str) { int pos=str.length()-1; while(str[pos]==' ') pos--; if(str[pos]=='\n') { if(str[pos-1]=='\r') str.truncate(pos-1); else str.truncate(pos); return true; } else return false; } void removeQuots(QCString &str) { int idx=0, pos1=0, pos2=0; char firstChar, lastChar; do { pos1=idx; firstChar=str[idx++]; } while(firstChar==' '); idx=str.length(); do { lastChar=str[--idx]; pos2=idx-1; } while(lastChar==' '); if(firstChar=='"' && lastChar=='"') { str.remove(pos1,1); str.remove(pos2,1); } } */ void saveWindowSize(const QString &name, const QSize &s) { KConfig *c=KGlobal::config(); c->setGroup("WINDOW_SIZES"); c->writeEntry(name, s); } void restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize) { KConfig *c=KGlobal::config(); c->setGroup("WINDOW_SIZES"); QSize s=c->readSizeEntry(name,&defaultSize); if(s.isValid()) d->resize(s); } QString encryptStr(const QString& aStr) { unsigned int i, val; unsigned int len = aStr.length(); QString result; for (i=0; i<len; i++) { // FIXME probably doesn't work like expected with non-ascii strings unsigned char val = aStr[i].latin1() - ' '; val = (255-' ') - val; result += QChar(val + ' '); } return result; } QString decryptStr(const QString& aStr) { return encryptStr(aStr); } void displayInternalFileError() { KMessageBox::error(0, i18n("Unable to load/save configuration!\nWrong permissions on home directory?\n!\nYou should close this application now,\nto avoid data loss!")); } void displayExternalFileError() { KMessageBox::error(0, i18n("Unable to load/save file!")); } void displayRemoteFileError() { KMessageBox::error(0, i18n("Unable to save remote file!")); } void displayTempFileError() { KMessageBox::error(0, i18n("Unable to create temporary file!")); }<commit_msg>- fixed "utilities.cpp:156: warning: file does not end in newline " ;-)<commit_after>/*************************************************************************** utilities.cpp - description copyright : (C) 1999 by Christian Thurner email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdio.h> #include <ctype.h> #include <qdir.h> #include <klocale.h> #include <kmessagebox.h> #include "utilities.h" #include "knode.h" #include "knstringsplitter.h" /* bool stripCRLF(char *str) { int pos=strlen(str)-1; while(str[pos]!='\n') pos--; //if(str[pos]=='\n') { str[pos--]='\0'; if(str[pos]=='\r') str[pos]='\0'; return true; //} //else return false; } bool stripCRLF(QCString &str) { int pos=str.length()-1; while(str[pos]==' ') pos--; if(str[pos]=='\n') { if(str[pos-1]=='\r') str.truncate(pos-1); else str.truncate(pos); return true; } else return false; } void removeQuots(QCString &str) { int idx=0, pos1=0, pos2=0; char firstChar, lastChar; do { pos1=idx; firstChar=str[idx++]; } while(firstChar==' '); idx=str.length(); do { lastChar=str[--idx]; pos2=idx-1; } while(lastChar==' '); if(firstChar=='"' && lastChar=='"') { str.remove(pos1,1); str.remove(pos2,1); } } */ void saveWindowSize(const QString &name, const QSize &s) { KConfig *c=KGlobal::config(); c->setGroup("WINDOW_SIZES"); c->writeEntry(name, s); } void restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize) { KConfig *c=KGlobal::config(); c->setGroup("WINDOW_SIZES"); QSize s=c->readSizeEntry(name,&defaultSize); if(s.isValid()) d->resize(s); } QString encryptStr(const QString& aStr) { unsigned int i, val; unsigned int len = aStr.length(); QString result; for (i=0; i<len; i++) { // FIXME probably doesn't work like expected with non-ascii strings unsigned char val = aStr[i].latin1() - ' '; val = (255-' ') - val; result += QChar(val + ' '); } return result; } QString decryptStr(const QString& aStr) { return encryptStr(aStr); } void displayInternalFileError() { KMessageBox::error(0, i18n("Unable to load/save configuration!\nWrong permissions on home directory?\n!\nYou should close this application now,\nto avoid data loss!")); } void displayExternalFileError() { KMessageBox::error(0, i18n("Unable to load/save file!")); } void displayRemoteFileError() { KMessageBox::error(0, i18n("Unable to save remote file!")); } void displayTempFileError() { KMessageBox::error(0, i18n("Unable to create temporary file!")); } <|endoftext|>
<commit_before><commit_msg>use SAL_N_ELEMENTS<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "swirlcons_user.h" #include <fclaw2d_include_all.h> /* Two versions of Clawpack */ #include <fc2d_clawpack46.h> #include <fc2d_clawpack46_options.h> #include <clawpack46_user_fort.h> /* Headers for user defined fortran files */ #include <fclaw2d_clawpatch.h> #include <fclaw2d_clawpatch_fort.h> /* headers for tag2refinement, tag4coarsening */ #include "../all/advection_user_fort.h" void swirlcons_link_solvers(fclaw2d_global_t *glob) { fclaw2d_vtable_t *vt = fclaw2d_vt(); fclaw2d_patch_vtable_t *patch_vt = fclaw2d_patch_vt(); fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fc2d_clawpack46_vtable_t *clawpack46_vt = fc2d_clawpack46_vt(); fc2d_clawpack46_options_t *clawopt = fc2d_clawpack46_get_options(glob); const user_options_t* user = swirlcons_get_options(glob); /* ForestClaw functions */ vt->problem_setup = &swirlcons_problem_setup; /* Version-independent */ /* ClawPatch specific functions */ clawpatch_vt->fort_tag4coarsening = &TAG4COARSENING; clawpatch_vt->fort_tag4refinement = &TAG4REFINEMENT; /* Patch specific functions */ patch_vt->setup = &swirlcons_patch_setup_manifold; switch(user->mapping) { case 0: clawpack46_vt->fort_rpt2 = &RPT2CONS; clawpack46_vt->fort_rpn2_cons = &RPN2_CONS_UPDATE; break; case 1: case 2: clawpack46_vt->fort_rpt2 = &RPT2CONS_MANIFOLD; clawpack46_vt->fort_rpn2_cons = &RPN2_CONS_UPDATE_MANIFOLD; break; } clawpack46_vt->fort_qinit = CLAWPACK46_QINIT; clawpack46_vt->fort_setaux = CLAWPACK46_SETAUX; clawpack46_vt->fort_rpt2 = RPT2CONS; clawopt->use_fwaves = 0; switch(user->rp_solver) { case 1: if (user->mapping == 0) { clawpack46_vt->fort_rpn2 = &RPN2CONS_QS; } else { clawpack46_vt->fort_rpn2 = &RPN2CONS_QS_MANIFOLD; } break; case 2: clawpack46_vt->fort_rpn2 = &RPN2CONS_WD; break; case 3: if (user->mapping == 0) { clawpack46_vt->fort_rpn2 = &RPN2CONS_EC; } else { clawpack46_vt->fort_rpn2 = &RPN2CONS_EC_MANIFOLD; } break; case 4: clawopt->use_fwaves = 1; clawpack46_vt->fort_rpn2 = RPN2CONS_FW; break; } } void swirlcons_problem_setup(fclaw2d_global_t* glob) { const user_options_t* user = swirlcons_get_options(glob); int ex = user->example; SWIRL_SETPROB(&ex); } void swirlcons_patch_setup_manifold(fclaw2d_global_t *glob, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { const user_options_t* user = swirlcons_get_options(glob); int mx,my,mbc,maux; double xlower,ylower,dx,dy; double *aux,*edgelengths,*area, *curvature; double *xp, *yp, *zp, *xd, *yd, *zd; double *xnormals,*ynormals,*xtangents,*ytangents,*surfnormals; fclaw2d_clawpatch_grid_data(glob,this_patch,&mx,&my,&mbc, &xlower,&ylower,&dx,&dy); fclaw2d_clawpatch_metric_data(glob,this_patch,&xp,&yp,&zp, &xd,&yd,&zd,&area); fclaw2d_clawpatch_metric_scalar(glob, this_patch,&area,&edgelengths, &curvature); fclaw2d_clawpatch_metric_vector(glob,this_patch, &xnormals, &ynormals, &xtangents, &ytangents, &surfnormals); fclaw2d_clawpatch_aux_data(glob,this_patch,&aux,&maux); if (user->mapping == 0) { int maxmx, maxmy; maxmx = mx; maxmy = my; CLAWPACK46_SETAUX(&maxmx, &maxmy, &mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux); } else { CLAWPACK46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux,&this_block_idx, xp,yp,zp,area, edgelengths,xnormals,ynormals,surfnormals); } } <commit_msg>(swirlcons) Comments<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "swirlcons_user.h" #include <fclaw2d_include_all.h> #include <fc2d_clawpack46.h> #include <fc2d_clawpack46_options.h> #include <clawpack46_user_fort.h> /* Headers for user defined fortran files */ #include <fclaw2d_clawpatch.h> #include <fclaw2d_clawpatch_fort.h> /* headers for tag2refinement, tag4coarsening */ #include "../all/advection_user_fort.h" void swirlcons_link_solvers(fclaw2d_global_t *glob) { fclaw2d_vtable_t *vt = fclaw2d_vt(); fclaw2d_patch_vtable_t *patch_vt = fclaw2d_patch_vt(); fclaw2d_clawpatch_vtable_t *clawpatch_vt = fclaw2d_clawpatch_vt(); fc2d_clawpack46_vtable_t *clawpack46_vt = fc2d_clawpack46_vt(); fc2d_clawpack46_options_t *clawopt = fc2d_clawpack46_get_options(glob); const user_options_t* user = swirlcons_get_options(glob); /* ForestClaw functions */ vt->problem_setup = &swirlcons_problem_setup; /* Version-independent */ /* ClawPatch specific functions */ clawpatch_vt->fort_tag4coarsening = &TAG4COARSENING; clawpatch_vt->fort_tag4refinement = &TAG4REFINEMENT; /* Patch specific functions */ patch_vt->setup = &swirlcons_patch_setup_manifold; switch(user->mapping) { case 0: clawpack46_vt->fort_rpt2 = &RPT2CONS; clawpack46_vt->fort_rpn2_cons = &RPN2_CONS_UPDATE; break; case 1: case 2: clawpack46_vt->fort_rpt2 = &RPT2CONS_MANIFOLD; clawpack46_vt->fort_rpn2_cons = &RPN2_CONS_UPDATE_MANIFOLD; break; } clawpack46_vt->fort_qinit = CLAWPACK46_QINIT; clawpack46_vt->fort_setaux = CLAWPACK46_SETAUX; clawpack46_vt->fort_rpt2 = RPT2CONS; clawopt->use_fwaves = 0; switch(user->rp_solver) { case 1: if (user->mapping == 0) { clawpack46_vt->fort_rpn2 = &RPN2CONS_QS; } else { clawpack46_vt->fort_rpn2 = &RPN2CONS_QS_MANIFOLD; } break; case 2: clawpack46_vt->fort_rpn2 = &RPN2CONS_WD; break; case 3: if (user->mapping == 0) { clawpack46_vt->fort_rpn2 = &RPN2CONS_EC; } else { clawpack46_vt->fort_rpn2 = &RPN2CONS_EC_MANIFOLD; } break; case 4: clawopt->use_fwaves = 1; clawpack46_vt->fort_rpn2 = RPN2CONS_FW; break; } } void swirlcons_problem_setup(fclaw2d_global_t* glob) { const user_options_t* user = swirlcons_get_options(glob); int ex = user->example; SWIRL_SETPROB(&ex); } void swirlcons_patch_setup_manifold(fclaw2d_global_t *glob, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { const user_options_t* user = swirlcons_get_options(glob); int mx,my,mbc,maux; double xlower,ylower,dx,dy; double *aux,*edgelengths,*area, *curvature; double *xp, *yp, *zp, *xd, *yd, *zd; double *xnormals,*ynormals,*xtangents,*ytangents,*surfnormals; fclaw2d_clawpatch_grid_data(glob,this_patch,&mx,&my,&mbc, &xlower,&ylower,&dx,&dy); fclaw2d_clawpatch_metric_data(glob,this_patch,&xp,&yp,&zp, &xd,&yd,&zd,&area); fclaw2d_clawpatch_metric_scalar(glob, this_patch,&area,&edgelengths, &curvature); fclaw2d_clawpatch_metric_vector(glob,this_patch, &xnormals, &ynormals, &xtangents, &ytangents, &surfnormals); fclaw2d_clawpatch_aux_data(glob,this_patch,&aux,&maux); if (user->mapping == 0) { int maxmx, maxmy; maxmx = mx; maxmy = my; CLAWPACK46_SETAUX(&maxmx, &maxmy, &mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux); } else { CLAWPACK46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower, &dx,&dy,&maux,aux,&this_block_idx, xp,yp,zp,area, edgelengths,xnormals,ynormals,surfnormals); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadImplementationsRegister.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkVisitorDispatcher.h" #include "itkFEMLoadPoint.h" #include "itkFEMLoadGrav.h" #include "itkFEMLoadEdge.h" #include "itkFEMLoadImagePairBase.h" #include "itkFEMElementBar2D.h" #include "itkFEMElementBeam2D.h" #include "itkFEMElementTriC02D.h" #include "itkFEMElementQuadC02D.h" #include "itkFEMElementMembraneC02D.h" #include "itkFEMElementC1IsoCurve2D.h" #include "itkFEMElementHexahedronC03D.h" #include "itkFEMElementTetrahedronC03D.h" #include "itkFEMElement2DC0LinearQuadrilateralStress.h" namespace itk { namespace fem { /* This macro makes registering Load implementations easier. */ #define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \ extern Element::LoadVectorType FunctionName(ElementClass::ConstPointer, Element::LoadElementPointer); \ VisitorDispatcher<ElementClass, Element::LoadElementType, Element::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName); /** * Registers all Load classes in the FEM library with VisitorDispatcher. * This function must be calles before the FEM library is functional!. */ void LoadImplementationsRegister(void) { // Loads acting on Bar2D element REGISTER_LOAD( Bar2D, LoadGrav, LoadGravImplementationBar2D ); REGISTER_LOAD( Bar2D, LoadGravConst, LoadGravImplementationBar2D ); REGISTER_LOAD( Bar2D, LoadPoint, LoadPointImplementationBar2D ); // Loads acting on Beam2D element REGISTER_LOAD( Beam2D, LoadGrav, LoadGravImplementationBeam2D ); REGISTER_LOAD( Beam2D, LoadGravConst, LoadGravImplementationBeam2D ); REGISTER_LOAD( Beam2D, LoadPoint, LoadPointImplementationBeam2D ); // Loads acting on TriC02D element REGISTER_LOAD( TriC02D, LoadGrav, LoadGravImplementationTriC02D ); REGISTER_LOAD( TriC02D, LoadGravConst, LoadGravImplementationTriC02D ); REGISTER_LOAD( TriC02D, LoadEdge, LoadEdgeImplementationTriC02D ); // Loads acting on QuadC02D element REGISTER_LOAD( QuadC02D, LoadGrav, LoadGravImplementationQuadC02D ); REGISTER_LOAD( QuadC02D, LoadGravConst, LoadGravImplementationQuadC02D ); REGISTER_LOAD( QuadC02D, LoadEdge, LoadEdgeImplementationQuadC02D ); // Loads acting on MembraneC02D element REGISTER_LOAD( MembraneC02D, LoadGrav, LoadGravImplementationMembraneC02D ); /* typedef Image< unsigned char, 2 > ImageType; VisitorDispatcher<MembraneC02D, LoadElement, Element::LoadVectorType> ::RegisterVisitor( (LoadImagePairBase<ImageType,ImageType>*)0, &LoadGravImplementationMembraneC02D ); */ // Loads acting on C1IsoCurve2D element REGISTER_LOAD( C1IsoCurve2D, LoadElement, LoadImplementationC1IsoCurve2D ); // Loads acting on HexahedronC03D element REGISTER_LOAD( HexahedronC03D, LoadGrav, LoadGravImplementationHexahedronC03D ); REGISTER_LOAD( HexahedronC03D, LoadGravConst, LoadGravImplementationHexahedronC03D ); // Loads acting on TetrahedronC03D element REGISTER_LOAD( TetrahedronC03D, LoadGrav, LoadGravImplementationTetrahedronC03D ); REGISTER_LOAD( TetrahedronC03D, LoadGravConst, LoadGravImplementationTetrahedronC03D ); // Add any additional loads here in a similar fashion... // Make sure that the pointer to the visit function is the correct one!!! } }} // end namespace itk::fem <commit_msg>ENH: Changed LOAD_FUNCTION macro.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadImplementationsRegister.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkVisitorDispatcher.h" #include "itkFEMLoadPoint.h" #include "itkFEMLoadGrav.h" #include "itkFEMLoadEdge.h" #include "itkFEMLoadImagePairBase.h" #include "itkFEMElementBar2D.h" #include "itkFEMElementBeam2D.h" #include "itkFEMElementTriC02D.h" #include "itkFEMElementQuadC02D.h" #include "itkFEMElementMembraneC02D.h" #include "itkFEMElementC1IsoCurve2D.h" #include "itkFEMElementHexahedronC03D.h" #include "itkFEMElementTetrahedronC03D.h" #include "itkFEMElement2DC0LinearQuadrilateralStress.h" namespace itk { namespace fem { /* This macro makes registering Load implementations easier. */ #define REGISTER_LOAD(ElementClass,LoadClass,FunctionName) \ extern ElementClass::LoadVectorType FunctionName(ElementClass::ConstPointer, ElementClass::LoadElementPointer); \ VisitorDispatcher<ElementClass, ElementClass::LoadElementType, ElementClass::LoadVectorType>::RegisterVisitor((LoadClass*)0, &FunctionName); /** * Registers all Load classes in the FEM library with VisitorDispatcher. * This function must be called before the FEM library is functional!. */ void LoadImplementationsRegister(void) { // Loads acting on Bar2D element REGISTER_LOAD( Bar2D, LoadGrav, LoadGravImplementationBar2D ); REGISTER_LOAD( Bar2D, LoadGravConst, LoadGravImplementationBar2D ); REGISTER_LOAD( Bar2D, LoadPoint, LoadPointImplementationBar2D ); // Loads acting on Beam2D element REGISTER_LOAD( Beam2D, LoadGrav, LoadGravImplementationBeam2D ); REGISTER_LOAD( Beam2D, LoadGravConst, LoadGravImplementationBeam2D ); REGISTER_LOAD( Beam2D, LoadPoint, LoadPointImplementationBeam2D ); // Loads acting on TriC02D element REGISTER_LOAD( TriC02D, LoadGrav, LoadGravImplementationTriC02D ); REGISTER_LOAD( TriC02D, LoadGravConst, LoadGravImplementationTriC02D ); REGISTER_LOAD( TriC02D, LoadEdge, LoadEdgeImplementationTriC02D ); // Loads acting on QuadC02D element REGISTER_LOAD( QuadC02D, LoadGrav, LoadGravImplementationQuadC02D ); REGISTER_LOAD( QuadC02D, LoadGravConst, LoadGravImplementationQuadC02D ); REGISTER_LOAD( QuadC02D, LoadEdge, LoadEdgeImplementationQuadC02D ); // Loads acting on MembraneC02D element REGISTER_LOAD( MembraneC02D, LoadGrav, LoadGravImplementationMembraneC02D ); /* typedef Image< unsigned char, 2 > ImageType; VisitorDispatcher<MembraneC02D, LoadElement, Element::LoadVectorType> ::RegisterVisitor( (LoadImagePairBase<ImageType,ImageType>*)0, &LoadGravImplementationMembraneC02D ); */ // Loads acting on C1IsoCurve2D element REGISTER_LOAD( C1IsoCurve2D, LoadElement, LoadImplementationC1IsoCurve2D ); // Loads acting on HexahedronC03D element REGISTER_LOAD( HexahedronC03D, LoadGrav, LoadGravImplementationHexahedronC03D ); REGISTER_LOAD( HexahedronC03D, LoadGravConst, LoadGravImplementationHexahedronC03D ); // Loads acting on TetrahedronC03D element REGISTER_LOAD( TetrahedronC03D, LoadGrav, LoadGravImplementationTetrahedronC03D ); REGISTER_LOAD( TetrahedronC03D, LoadGravConst, LoadGravImplementationTetrahedronC03D ); // Add any additional loads here in a similar fashion... // Make sure that the pointer to the visit function is the correct one!!! } }} // end namespace itk::fem <|endoftext|>
<commit_before>//===-- AMDGPUDisassembler.cpp - Disassembler for AMDGPU ISA --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// // /// \file /// /// This file contains definition for AMDGPU ISA disassembler // //===----------------------------------------------------------------------===// // ToDo: What to do with instruction suffixes (v_mov_b32 vs v_mov_b32_e32)? #include "AMDGPUDisassembler.h" #include "AMDGPU.h" #include "AMDGPURegisterInfo.h" #include "Utils/AMDGPUBaseInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCFixedLenDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-disassembler" typedef llvm::MCDisassembler::DecodeStatus DecodeStatus; inline static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand& Opnd) { Inst.addOperand(Opnd); return Opnd.isValid() ? MCDisassembler::Success : MCDisassembler::SoftFail; } #define DECODE_OPERAND2(RegClass, DecName) \ static DecodeStatus Decode##RegClass##RegisterClass(MCInst &Inst, \ unsigned Imm, \ uint64_t /*Addr*/, \ const void *Decoder) { \ auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder); \ return addOperand(Inst, DAsm->decodeOperand_##DecName(Imm)); \ } #define DECODE_OPERAND(RegClass) DECODE_OPERAND2(RegClass, RegClass) DECODE_OPERAND(VGPR_32) DECODE_OPERAND(VS_32) DECODE_OPERAND(VS_64) DECODE_OPERAND(VReg_64) DECODE_OPERAND(VReg_96) DECODE_OPERAND(VReg_128) //DECODE_OPERAND(SGPR_32) DECODE_OPERAND(SReg_32) DECODE_OPERAND(SReg_64) DECODE_OPERAND(SReg_128) DECODE_OPERAND(SReg_256) //DECODE_OPERAND(SReg_512) #define GET_SUBTARGETINFO_ENUM #include "AMDGPUGenSubtargetInfo.inc" #undef GET_SUBTARGETINFO_ENUM #include "AMDGPUGenDisassemblerTables.inc" //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// static inline uint32_t eatB32(ArrayRef<uint8_t>& Bytes) { assert(Bytes.size() >= sizeof eatB32(Bytes)); const auto Res = support::endian::read32le(Bytes.data()); Bytes = Bytes.slice(sizeof Res); return Res; } DecodeStatus AMDGPUDisassembler::tryDecodeInst(const uint8_t* Table, MCInst &MI, uint64_t Inst, uint64_t Address) const { assert(MI.getOpcode() == 0); assert(MI.getNumOperands() == 0); MCInst TmpInst; const auto SavedBytes = Bytes; if (decodeInstruction(Table, TmpInst, Inst, Address, this, STI)) { MI = TmpInst; return MCDisassembler::Success; } Bytes = SavedBytes; return MCDisassembler::Fail; } DecodeStatus AMDGPUDisassembler::getInstruction(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes_, uint64_t Address, raw_ostream &WS, raw_ostream &CS) const { CommentStream = &CS; // ToDo: AMDGPUDisassembler supports only VI ISA. assert(AMDGPU::isVI(STI) && "Can disassemble only VI ISA."); const unsigned MaxInstBytesNum = (std::min)((size_t)8, Bytes_.size()); Bytes = Bytes_.slice(0, MaxInstBytesNum); DecodeStatus Res = MCDisassembler::Fail; do { // ToDo: better to switch enc len using some bit predicate // but it is unknown yet, so try all we can if (Bytes.size() < 4) break; const uint32_t DW = eatB32(Bytes); Res = tryDecodeInst(DecoderTableVI32, MI, DW, Address); if (Res) break; Res = tryDecodeInst(DecoderTableAMDGPU32, MI, DW, Address); if (Res) break; if (Bytes.size() < 4) break; const uint64_t QW = ((uint64_t)eatB32(Bytes) << 32) | DW; Res = tryDecodeInst(DecoderTableVI64, MI, QW, Address); if (Res) break; Res = tryDecodeInst(DecoderTableAMDGPU64, MI, QW, Address); } while (false); Size = Res ? (MaxInstBytesNum - Bytes.size()) : 0; return Res; } const char* AMDGPUDisassembler::getRegClassName(unsigned RegClassID) const { return getContext().getRegisterInfo()-> getRegClassName(&AMDGPUMCRegisterClasses[RegClassID]); } inline MCOperand AMDGPUDisassembler::errOperand(unsigned V, const Twine& ErrMsg) const { *CommentStream << "Error: " + ErrMsg; // ToDo: add support for error operands to MCInst.h // return MCOperand::createError(V); return MCOperand(); } inline MCOperand AMDGPUDisassembler::createRegOperand(unsigned int RegId) const { return MCOperand::createReg(RegId); } inline MCOperand AMDGPUDisassembler::createRegOperand(unsigned RegClassID, unsigned Val) const { const auto& RegCl = AMDGPUMCRegisterClasses[RegClassID]; if (Val >= RegCl.getNumRegs()) return errOperand(Val, Twine(getRegClassName(RegClassID)) + ": unknown register " + Twine(Val)); return createRegOperand(RegCl.getRegister(Val)); } inline MCOperand AMDGPUDisassembler::createSRegOperand(unsigned SRegClassID, unsigned Val) const { // ToDo: SI/CI have 104 SGPRs, VI - 102 // Valery: here we accepting as much as we can, let assembler sort it out int shift = 0; switch (SRegClassID) { case AMDGPU::SGPR_32RegClassID: case AMDGPU::SReg_32RegClassID: break; case AMDGPU::SGPR_64RegClassID: case AMDGPU::SReg_64RegClassID: shift = 1; break; case AMDGPU::SReg_128RegClassID: // ToDo: unclear if s[100:104] is available on VI. Can we use VCC as SGPR in // this bundle? case AMDGPU::SReg_256RegClassID: // ToDo: unclear if s[96:104] is available on VI. Can we use VCC as SGPR in // this bundle? case AMDGPU::SReg_512RegClassID: shift = 2; break; // ToDo: unclear if s[88:104] is available on VI. Can we use VCC as SGPR in // this bundle? default: assert(false); break; } if (Val % (1 << shift)) *CommentStream << "Warning: " << getRegClassName(SRegClassID) << ": scalar reg isn't aligned " << Val; return createRegOperand(SRegClassID, Val >> shift); } MCOperand AMDGPUDisassembler::decodeOperand_VS_32(unsigned Val) const { return decodeSrcOp(OP32, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VS_64(unsigned Val) const { return decodeSrcOp(OP64, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VGPR_32(unsigned Val) const { return createRegOperand(AMDGPU::VGPR_32RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_64(unsigned Val) const { return createRegOperand(AMDGPU::VReg_64RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_96(unsigned Val) const { return createRegOperand(AMDGPU::VReg_96RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_128(unsigned Val) const { return createRegOperand(AMDGPU::VReg_128RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SGPR_32(unsigned Val) const { return createSRegOperand(AMDGPU::SGPR_32RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_32(unsigned Val) const { // table-gen generated disassembler doesn't care about operand types // leaving only registry class so SSrc_32 operand turns into SReg_32 // and therefore we accept immediates and literals here as well return decodeSrcOp(OP32, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_64(unsigned Val) const { // see decodeOperand_SReg_32 comment return decodeSrcOp(OP64, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_128(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_128RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_256(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_256RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_512(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_512RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeLiteralConstant() const { // For now all literal constants are supposed to be unsigned integer // ToDo: deal with signed/unsigned 64-bit integer constants // ToDo: deal with float/double constants if (Bytes.size() < 4) return errOperand(0, "cannot read literal, inst bytes left " + Twine(Bytes.size())); return MCOperand::createImm(eatB32(Bytes)); } MCOperand AMDGPUDisassembler::decodeIntImmed(unsigned Imm) { assert(Imm >= 128 && Imm <= 208); return MCOperand::createImm((Imm <= 192) ? (Imm - 128) : (192 - Imm)); } MCOperand AMDGPUDisassembler::decodeFPImmed(bool Is32, unsigned Imm) { assert(Imm >= 240 && Imm <= 248); // ToDo: case 248: 1/(2*PI) - is allowed only on VI // ToDo: AMDGPUInstPrinter does not support 1/(2*PI). It consider 1/(2*PI) as // literal constant. float V = 0.0f; switch (Imm) { case 240: V = 0.5f; break; case 241: V = -0.5f; break; case 242: V = 1.0f; break; case 243: V = -1.0f; break; case 244: V = 2.0f; break; case 245: V = -2.0f; break; case 246: V = 4.0f; break; case 247: V = -4.0f; break; case 248: return MCOperand::createImm(Is32 ? // 1/(2*PI) 0x3e22f983 : 0x3fc45f306dc9c882); default: break; } return MCOperand::createImm(Is32? FloatToBits(V) : DoubleToBits(V)); } MCOperand AMDGPUDisassembler::decodeSrcOp(bool Is32, unsigned Val) const { using namespace AMDGPU; assert(Val < 512); // enum9 if (Val >= 256) return createRegOperand(Is32 ? VGPR_32RegClassID : VReg_64RegClassID, Val - 256); if (Val <= 101) return createSRegOperand(Is32 ? SGPR_32RegClassID : SGPR_64RegClassID, Val); if (Val >= 128 && Val <= 208) return decodeIntImmed(Val); if (Val >= 240 && Val <= 248) return decodeFPImmed(Is32, Val); if (Val == 255) return decodeLiteralConstant(); return Is32 ? decodeSpecialReg32(Val) : decodeSpecialReg64(Val); } MCOperand AMDGPUDisassembler::decodeSpecialReg32(unsigned Val) const { using namespace AMDGPU; switch (Val) { case 102: return createRegOperand(getMCReg(FLAT_SCR_LO, STI)); case 103: return createRegOperand(getMCReg(FLAT_SCR_HI, STI)); // ToDo: no support for xnack_mask_lo/_hi register case 104: case 105: break; case 106: return createRegOperand(VCC_LO); case 107: return createRegOperand(VCC_HI); // ToDo: no support for tba_lo/_hi register case 108: case 109: break; // ToDo: no support for tma_lo/_hi register case 110: case 111: break; // ToDo: no support for ttmp[0:11] register case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: break; case 124: return createRegOperand(M0); case 126: return createRegOperand(EXEC_LO); case 127: return createRegOperand(EXEC_HI); // ToDo: no support for vccz register case 251: break; // ToDo: no support for execz register case 252: break; case 253: return createRegOperand(SCC); default: break; } return errOperand(Val, "unknown operand encoding " + Twine(Val)); } MCOperand AMDGPUDisassembler::decodeSpecialReg64(unsigned Val) const { using namespace AMDGPU; switch (Val) { case 102: return createRegOperand(getMCReg(FLAT_SCR, STI)); case 106: return createRegOperand(VCC); case 126: return createRegOperand(EXEC); default: break; } return errOperand(Val, "unknown operand encoding " + Twine(Val)); } static MCDisassembler *createAMDGPUDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx) { return new AMDGPUDisassembler(STI, Ctx); } extern "C" void LLVMInitializeAMDGPUDisassembler() { TargetRegistry::RegisterMCDisassembler(TheGCNTarget, createAMDGPUDisassembler); } <commit_msg>[AMDGPU] Remove unused disassembler code.<commit_after>//===-- AMDGPUDisassembler.cpp - Disassembler for AMDGPU ISA --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// // /// \file /// /// This file contains definition for AMDGPU ISA disassembler // //===----------------------------------------------------------------------===// // ToDo: What to do with instruction suffixes (v_mov_b32 vs v_mov_b32_e32)? #include "AMDGPUDisassembler.h" #include "AMDGPU.h" #include "AMDGPURegisterInfo.h" #include "Utils/AMDGPUBaseInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCFixedLenDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-disassembler" typedef llvm::MCDisassembler::DecodeStatus DecodeStatus; inline static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand& Opnd) { Inst.addOperand(Opnd); return Opnd.isValid() ? MCDisassembler::Success : MCDisassembler::SoftFail; } #define DECODE_OPERAND2(RegClass, DecName) \ static DecodeStatus Decode##RegClass##RegisterClass(MCInst &Inst, \ unsigned Imm, \ uint64_t /*Addr*/, \ const void *Decoder) { \ auto DAsm = static_cast<const AMDGPUDisassembler*>(Decoder); \ return addOperand(Inst, DAsm->decodeOperand_##DecName(Imm)); \ } #define DECODE_OPERAND(RegClass) DECODE_OPERAND2(RegClass, RegClass) DECODE_OPERAND(VGPR_32) DECODE_OPERAND(VS_32) DECODE_OPERAND(VS_64) DECODE_OPERAND(VReg_64) DECODE_OPERAND(VReg_96) DECODE_OPERAND(VReg_128) DECODE_OPERAND(SReg_32) DECODE_OPERAND(SReg_64) DECODE_OPERAND(SReg_128) DECODE_OPERAND(SReg_256) #define GET_SUBTARGETINFO_ENUM #include "AMDGPUGenSubtargetInfo.inc" #undef GET_SUBTARGETINFO_ENUM #include "AMDGPUGenDisassemblerTables.inc" //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// static inline uint32_t eatB32(ArrayRef<uint8_t>& Bytes) { assert(Bytes.size() >= sizeof eatB32(Bytes)); const auto Res = support::endian::read32le(Bytes.data()); Bytes = Bytes.slice(sizeof Res); return Res; } DecodeStatus AMDGPUDisassembler::tryDecodeInst(const uint8_t* Table, MCInst &MI, uint64_t Inst, uint64_t Address) const { assert(MI.getOpcode() == 0); assert(MI.getNumOperands() == 0); MCInst TmpInst; const auto SavedBytes = Bytes; if (decodeInstruction(Table, TmpInst, Inst, Address, this, STI)) { MI = TmpInst; return MCDisassembler::Success; } Bytes = SavedBytes; return MCDisassembler::Fail; } DecodeStatus AMDGPUDisassembler::getInstruction(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes_, uint64_t Address, raw_ostream &WS, raw_ostream &CS) const { CommentStream = &CS; // ToDo: AMDGPUDisassembler supports only VI ISA. assert(AMDGPU::isVI(STI) && "Can disassemble only VI ISA."); const unsigned MaxInstBytesNum = (std::min)((size_t)8, Bytes_.size()); Bytes = Bytes_.slice(0, MaxInstBytesNum); DecodeStatus Res = MCDisassembler::Fail; do { // ToDo: better to switch enc len using some bit predicate // but it is unknown yet, so try all we can if (Bytes.size() < 4) break; const uint32_t DW = eatB32(Bytes); Res = tryDecodeInst(DecoderTableVI32, MI, DW, Address); if (Res) break; Res = tryDecodeInst(DecoderTableAMDGPU32, MI, DW, Address); if (Res) break; if (Bytes.size() < 4) break; const uint64_t QW = ((uint64_t)eatB32(Bytes) << 32) | DW; Res = tryDecodeInst(DecoderTableVI64, MI, QW, Address); if (Res) break; Res = tryDecodeInst(DecoderTableAMDGPU64, MI, QW, Address); } while (false); Size = Res ? (MaxInstBytesNum - Bytes.size()) : 0; return Res; } const char* AMDGPUDisassembler::getRegClassName(unsigned RegClassID) const { return getContext().getRegisterInfo()-> getRegClassName(&AMDGPUMCRegisterClasses[RegClassID]); } inline MCOperand AMDGPUDisassembler::errOperand(unsigned V, const Twine& ErrMsg) const { *CommentStream << "Error: " + ErrMsg; // ToDo: add support for error operands to MCInst.h // return MCOperand::createError(V); return MCOperand(); } inline MCOperand AMDGPUDisassembler::createRegOperand(unsigned int RegId) const { return MCOperand::createReg(RegId); } inline MCOperand AMDGPUDisassembler::createRegOperand(unsigned RegClassID, unsigned Val) const { const auto& RegCl = AMDGPUMCRegisterClasses[RegClassID]; if (Val >= RegCl.getNumRegs()) return errOperand(Val, Twine(getRegClassName(RegClassID)) + ": unknown register " + Twine(Val)); return createRegOperand(RegCl.getRegister(Val)); } inline MCOperand AMDGPUDisassembler::createSRegOperand(unsigned SRegClassID, unsigned Val) const { // ToDo: SI/CI have 104 SGPRs, VI - 102 // Valery: here we accepting as much as we can, let assembler sort it out int shift = 0; switch (SRegClassID) { case AMDGPU::SGPR_32RegClassID: case AMDGPU::SReg_32RegClassID: break; case AMDGPU::SGPR_64RegClassID: case AMDGPU::SReg_64RegClassID: shift = 1; break; case AMDGPU::SReg_128RegClassID: // ToDo: unclear if s[100:104] is available on VI. Can we use VCC as SGPR in // this bundle? case AMDGPU::SReg_256RegClassID: // ToDo: unclear if s[96:104] is available on VI. Can we use VCC as SGPR in // this bundle? case AMDGPU::SReg_512RegClassID: shift = 2; break; // ToDo: unclear if s[88:104] is available on VI. Can we use VCC as SGPR in // this bundle? default: assert(false); break; } if (Val % (1 << shift)) *CommentStream << "Warning: " << getRegClassName(SRegClassID) << ": scalar reg isn't aligned " << Val; return createRegOperand(SRegClassID, Val >> shift); } MCOperand AMDGPUDisassembler::decodeOperand_VS_32(unsigned Val) const { return decodeSrcOp(OP32, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VS_64(unsigned Val) const { return decodeSrcOp(OP64, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VGPR_32(unsigned Val) const { return createRegOperand(AMDGPU::VGPR_32RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_64(unsigned Val) const { return createRegOperand(AMDGPU::VReg_64RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_96(unsigned Val) const { return createRegOperand(AMDGPU::VReg_96RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_VReg_128(unsigned Val) const { return createRegOperand(AMDGPU::VReg_128RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SGPR_32(unsigned Val) const { return createSRegOperand(AMDGPU::SGPR_32RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_32(unsigned Val) const { // table-gen generated disassembler doesn't care about operand types // leaving only registry class so SSrc_32 operand turns into SReg_32 // and therefore we accept immediates and literals here as well return decodeSrcOp(OP32, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_64(unsigned Val) const { // see decodeOperand_SReg_32 comment return decodeSrcOp(OP64, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_128(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_128RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_256(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_256RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeOperand_SReg_512(unsigned Val) const { return createSRegOperand(AMDGPU::SReg_512RegClassID, Val); } MCOperand AMDGPUDisassembler::decodeLiteralConstant() const { // For now all literal constants are supposed to be unsigned integer // ToDo: deal with signed/unsigned 64-bit integer constants // ToDo: deal with float/double constants if (Bytes.size() < 4) return errOperand(0, "cannot read literal, inst bytes left " + Twine(Bytes.size())); return MCOperand::createImm(eatB32(Bytes)); } MCOperand AMDGPUDisassembler::decodeIntImmed(unsigned Imm) { assert(Imm >= 128 && Imm <= 208); return MCOperand::createImm((Imm <= 192) ? (Imm - 128) : (192 - Imm)); } MCOperand AMDGPUDisassembler::decodeFPImmed(bool Is32, unsigned Imm) { assert(Imm >= 240 && Imm <= 248); // ToDo: case 248: 1/(2*PI) - is allowed only on VI // ToDo: AMDGPUInstPrinter does not support 1/(2*PI). It consider 1/(2*PI) as // literal constant. float V = 0.0f; switch (Imm) { case 240: V = 0.5f; break; case 241: V = -0.5f; break; case 242: V = 1.0f; break; case 243: V = -1.0f; break; case 244: V = 2.0f; break; case 245: V = -2.0f; break; case 246: V = 4.0f; break; case 247: V = -4.0f; break; case 248: return MCOperand::createImm(Is32 ? // 1/(2*PI) 0x3e22f983 : 0x3fc45f306dc9c882); default: break; } return MCOperand::createImm(Is32? FloatToBits(V) : DoubleToBits(V)); } MCOperand AMDGPUDisassembler::decodeSrcOp(bool Is32, unsigned Val) const { using namespace AMDGPU; assert(Val < 512); // enum9 if (Val >= 256) return createRegOperand(Is32 ? VGPR_32RegClassID : VReg_64RegClassID, Val - 256); if (Val <= 101) return createSRegOperand(Is32 ? SGPR_32RegClassID : SGPR_64RegClassID, Val); if (Val >= 128 && Val <= 208) return decodeIntImmed(Val); if (Val >= 240 && Val <= 248) return decodeFPImmed(Is32, Val); if (Val == 255) return decodeLiteralConstant(); return Is32 ? decodeSpecialReg32(Val) : decodeSpecialReg64(Val); } MCOperand AMDGPUDisassembler::decodeSpecialReg32(unsigned Val) const { using namespace AMDGPU; switch (Val) { case 102: return createRegOperand(getMCReg(FLAT_SCR_LO, STI)); case 103: return createRegOperand(getMCReg(FLAT_SCR_HI, STI)); // ToDo: no support for xnack_mask_lo/_hi register case 104: case 105: break; case 106: return createRegOperand(VCC_LO); case 107: return createRegOperand(VCC_HI); // ToDo: no support for tba_lo/_hi register case 108: case 109: break; // ToDo: no support for tma_lo/_hi register case 110: case 111: break; // ToDo: no support for ttmp[0:11] register case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: break; case 124: return createRegOperand(M0); case 126: return createRegOperand(EXEC_LO); case 127: return createRegOperand(EXEC_HI); // ToDo: no support for vccz register case 251: break; // ToDo: no support for execz register case 252: break; case 253: return createRegOperand(SCC); default: break; } return errOperand(Val, "unknown operand encoding " + Twine(Val)); } MCOperand AMDGPUDisassembler::decodeSpecialReg64(unsigned Val) const { using namespace AMDGPU; switch (Val) { case 102: return createRegOperand(getMCReg(FLAT_SCR, STI)); case 106: return createRegOperand(VCC); case 126: return createRegOperand(EXEC); default: break; } return errOperand(Val, "unknown operand encoding " + Twine(Val)); } static MCDisassembler *createAMDGPUDisassembler(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx) { return new AMDGPUDisassembler(STI, Ctx); } extern "C" void LLVMInitializeAMDGPUDisassembler() { TargetRegistry::RegisterMCDisassembler(TheGCNTarget, createAMDGPUDisassembler); } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 Stephen Williams ([email protected]) * Copyright CERN 2015 * @author Maciej Suminski ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ # include "expression.h" # include "architec.h" # include <ivl_assert.h> bool Expression::evaluate(ScopeBase*, int64_t&) const { return false; } bool Expression::evaluate(Entity*, ScopeBase*scope, int64_t&val) const { return evaluate(scope, val); } bool ExpArithmetic::evaluate(ScopeBase*scope, int64_t&val) const { int64_t val1, val2; bool rc; rc = eval_operand1(scope, val1); if (rc == false) return false; rc = eval_operand2(scope, val2); if (rc == false) return false; switch (fun_) { case PLUS: val = val1 + val2; break; case MINUS: val = val1 - val2; break; case MULT: val = val1 * val2; break; case DIV: if (val2 == 0) return false; val = val1 / val2; break; case MOD: if (val2 == 0) return false; val = val1 % val2; break; case REM: return false; case POW: return false; case xCONCAT: // not possible return false; } return true; } bool ExpAttribute::evaluate(ScopeBase*scope, int64_t&val) const { /* Special Case: The array attributes can sometimes be calculated all the down to a literal integer at compile time, and all it needs is the type of the base expression. (The base expression doesn't even need to be evaluated.) */ if (name_ == "length" || name_ == "right" || name_ == "left") { const VType*base_type = base_->peek_type(); if(!base_type) { const ExpName*name = NULL; if(scope && (name = dynamic_cast<const ExpName*>(base_))) { const perm_string& n = name->peek_name(); if(const Variable*var = scope->find_variable(n)) base_type = var->peek_type(); else if(const Signal*sig = scope->find_signal(n)) base_type = sig->peek_type(); else if(const InterfacePort*port = scope->find_param(n)) base_type = port->type; } } if(!base_type) return false; // I tried really hard, sorry const VTypeArray*arr = dynamic_cast<const VTypeArray*>(base_type); if (arr == 0) { cerr << get_fileline() << ": error: " << "Cannot apply the 'length attribute to non-array objects" << endl; return false; } if(name_ == "length") { int64_t size = arr->get_width(scope); if(size > 0) val = size; else return false; } else if(name_ == "left") { arr->dimension(0).msb()->evaluate(scope, val); } else if(name_ == "right") { arr->dimension(0).lsb()->evaluate(scope, val); } else ivl_assert(*this, false); return true; } return false; } bool ExpAttribute::evaluate(Entity*ent, ScopeBase*scope, int64_t&val) const { if (!ent || !scope) { // it's impossible to evaluate, probably it is inside a subprogram return false; } if (name_ == "left" || name_ == "right") { const VType*base_type = base_->peek_type(); if (base_type == 0) base_type = base_->probe_type(ent, scope); ivl_assert(*this, base_type); const VTypeArray*arr = dynamic_cast<const VTypeArray*>(base_type); if (arr == 0) { cerr << get_fileline() << ": error: " << "Cannot apply the '" << name_ << " attribute to non-array objects" << endl; return false; } ivl_assert(*this, arr->dimensions() == 1); if(name_ == "left") arr->dimension(0).msb()->evaluate(ent, scope, val); else // "right" arr->dimension(0).lsb()->evaluate(ent, scope, val); return true; } return evaluate(scope, val); } /* * I don't yet know how to evaluate concatenations. It is not likely * to come up anyhow. */ bool ExpConcat::evaluate(ScopeBase*, int64_t&) const { return false; } bool ExpName::evaluate(ScopeBase*scope, int64_t&val) const { const VType*type; Expression*exp; if (prefix_.get()) { cerr << get_fileline() << ": sorry: I don't know how to evaluate ExpName prefix parts." << endl; return false; } if (!scope) return false; if (!scope->find_constant(name_, type, exp)) return false; return exp->evaluate(scope, val); } bool ExpName::evaluate(Entity*ent, ScopeBase*scope, int64_t&val) const { if (prefix_.get()) { cerr << get_fileline() << ": sorry: I don't know how to evaluate ExpName prefix parts." << endl; return false; } const InterfacePort*gen = ent->find_generic(name_); if (gen) { cerr << get_fileline() << ": sorry: I don't necessarily handle generic overrides." << endl; // Evaluate the default expression and use that. if (gen->expr) return gen->expr->evaluate(ent, scope, val); } return evaluate(scope, val); } bool ExpShift::evaluate(ScopeBase*scope, int64_t&val) const { int64_t val1, val2; bool rc; rc = eval_operand1(scope, val1); if (rc == false) return false; rc = eval_operand2(scope, val2); if (rc == false) return false; switch (shift_) { case SRL: val = (uint64_t)val1 >> (uint64_t)val2; break; case SLL: val = (uint64_t)val1 << (uint64_t)val2; break; case SRA: val = (int64_t)val1 >> (int64_t)val2; break; case SLA: val = (int64_t)val1 << (int64_t)val2; break; case ROR: case ROL: return false; } return true; } <commit_msg>vhdlpp: Stop compilation on invalid attributes.<commit_after>/* * Copyright (c) 2011-2013 Stephen Williams ([email protected]) * Copyright CERN 2015 * @author Maciej Suminski ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ # include "expression.h" # include "architec.h" # include <ivl_assert.h> bool Expression::evaluate(ScopeBase*, int64_t&) const { return false; } bool Expression::evaluate(Entity*, ScopeBase*scope, int64_t&val) const { return evaluate(scope, val); } bool ExpArithmetic::evaluate(ScopeBase*scope, int64_t&val) const { int64_t val1, val2; bool rc; rc = eval_operand1(scope, val1); if (rc == false) return false; rc = eval_operand2(scope, val2); if (rc == false) return false; switch (fun_) { case PLUS: val = val1 + val2; break; case MINUS: val = val1 - val2; break; case MULT: val = val1 * val2; break; case DIV: if (val2 == 0) return false; val = val1 / val2; break; case MOD: if (val2 == 0) return false; val = val1 % val2; break; case REM: return false; case POW: return false; case xCONCAT: // not possible return false; } return true; } bool ExpAttribute::evaluate(ScopeBase*scope, int64_t&val) const { /* Special Case: The array attributes can sometimes be calculated all the down to a literal integer at compile time, and all it needs is the type of the base expression. (The base expression doesn't even need to be evaluated.) */ if (name_ == "length" || name_ == "right" || name_ == "left") { const VType*base_type = base_->peek_type(); if(!base_type) { const ExpName*name = NULL; if(scope && (name = dynamic_cast<const ExpName*>(base_))) { const perm_string& n = name->peek_name(); if(const Variable*var = scope->find_variable(n)) base_type = var->peek_type(); else if(const Signal*sig = scope->find_signal(n)) base_type = sig->peek_type(); else if(const InterfacePort*port = scope->find_param(n)) base_type = port->type; } } if(!base_type) return false; // I tried really hard, sorry const VTypeArray*arr = dynamic_cast<const VTypeArray*>(base_type); if (arr == 0) { cerr << endl << get_fileline() << ": error: " << "Cannot apply the 'length attribute to non-array objects" << endl; ivl_assert(*this, false); return false; } if(name_ == "length") { int64_t size = arr->get_width(scope); if(size > 0) val = size; else return false; } else if(name_ == "left") { arr->dimension(0).msb()->evaluate(scope, val); } else if(name_ == "right") { arr->dimension(0).lsb()->evaluate(scope, val); } else ivl_assert(*this, false); return true; } return false; } bool ExpAttribute::evaluate(Entity*ent, ScopeBase*scope, int64_t&val) const { if (!ent || !scope) { // it's impossible to evaluate, probably it is inside a subprogram return false; } if (name_ == "left" || name_ == "right") { const VType*base_type = base_->peek_type(); if (base_type == 0) base_type = base_->probe_type(ent, scope); ivl_assert(*this, base_type); const VTypeArray*arr = dynamic_cast<const VTypeArray*>(base_type); if (arr == 0) { cerr << endl << get_fileline() << ": error: " << "Cannot apply the '" << name_ << " attribute to non-array objects" << endl; ivl_assert(*this, false); return false; } ivl_assert(*this, arr->dimensions() == 1); if(name_ == "left") arr->dimension(0).msb()->evaluate(ent, scope, val); else // "right" arr->dimension(0).lsb()->evaluate(ent, scope, val); return true; } return evaluate(scope, val); } /* * I don't yet know how to evaluate concatenations. It is not likely * to come up anyhow. */ bool ExpConcat::evaluate(ScopeBase*, int64_t&) const { return false; } bool ExpName::evaluate(ScopeBase*scope, int64_t&val) const { const VType*type; Expression*exp; if (prefix_.get()) { cerr << get_fileline() << ": sorry: I don't know how to evaluate ExpName prefix parts." << endl; return false; } if (!scope) return false; if (!scope->find_constant(name_, type, exp)) return false; return exp->evaluate(scope, val); } bool ExpName::evaluate(Entity*ent, ScopeBase*scope, int64_t&val) const { if (prefix_.get()) { cerr << get_fileline() << ": sorry: I don't know how to evaluate ExpName prefix parts." << endl; return false; } const InterfacePort*gen = ent->find_generic(name_); if (gen) { cerr << get_fileline() << ": sorry: I don't necessarily handle generic overrides." << endl; // Evaluate the default expression and use that. if (gen->expr) return gen->expr->evaluate(ent, scope, val); } return evaluate(scope, val); } bool ExpShift::evaluate(ScopeBase*scope, int64_t&val) const { int64_t val1, val2; bool rc; rc = eval_operand1(scope, val1); if (rc == false) return false; rc = eval_operand2(scope, val2); if (rc == false) return false; switch (shift_) { case SRL: val = (uint64_t)val1 >> (uint64_t)val2; break; case SLL: val = (uint64_t)val1 << (uint64_t)val2; break; case SRA: val = (int64_t)val1 >> (int64_t)val2; break; case SLA: val = (int64_t)val1 << (int64_t)val2; break; case ROR: case ROL: return false; } return true; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartSeriesModelCollection.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartSeriesModelCollection.cxx /// \date February 8, 2008 #ifdef _MSC_VER // Disable warnings that Qt headers give. #pragma warning(disable:4127) #endif #include "vtkQtChartSeriesModelCollection.h" vtkQtChartSeriesModelCollection::vtkQtChartSeriesModelCollection( QObject *parentObject) : vtkQtChartSeriesModel(parentObject), Models() { } int vtkQtChartSeriesModelCollection::getNumberOfSeries() const { int series = 0; QList<vtkQtChartSeriesModel *>::ConstIterator model = this->Models.begin(); for( ; model != this->Models.end(); ++model) { series += (*model)->getNumberOfSeries(); } return series; } int vtkQtChartSeriesModelCollection::getNumberOfSeriesValues(int series) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getNumberOfSeriesValues(series); } return 0; } QVariant vtkQtChartSeriesModelCollection::getSeriesName(int series) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesName(series); } return QVariant(); } QVariant vtkQtChartSeriesModelCollection::getSeriesValue(int series, int index, int component) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesValue(series, index, component); } return QVariant(); } QList<QVariant> vtkQtChartSeriesModelCollection::getSeriesRange(int series, int component) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesRange(series, component); } return QList<QVariant>(); } void vtkQtChartSeriesModelCollection::addSeriesModel( vtkQtChartSeriesModel *model) { if(model) { this->connect(model, SIGNAL(modelAboutToBeReset()), this, SIGNAL(modelAboutToBeReset())); this->connect(model, SIGNAL(modelReset()), this, SIGNAL(modelReset())); this->connect(model, SIGNAL(seriesAboutToBeInserted(int, int)), this, SLOT(onSeriesAboutToBeInserted(int, int))); this->connect(model, SIGNAL(seriesInserted(int, int)), this, SLOT(onSeriesInserted(int, int))); this->connect(model, SIGNAL(seriesAboutToBeRemoved(int, int)), this, SLOT(onSeriesAboutToBeRemoved(int, int))); this->connect(model, SIGNAL(seriesRemoved(int, int)), this, SLOT(onSeriesRemoved(int, int))); this->Models.append(model); } } void vtkQtChartSeriesModelCollection::removeSeriesModel( vtkQtChartSeriesModel *model) { int index = this->Models.indexOf(model); if(index != -1) { this->disconnect(model, 0, this, 0); this->Models.removeAt(index); } } int vtkQtChartSeriesModelCollection::getNumberOfSeriesModels() const { return this->Models.size(); } vtkQtChartSeriesModel* vtkQtChartSeriesModelCollection::getSeriesModel( int index) const { return this->Models[index]; } void vtkQtChartSeriesModelCollection::onSeriesAboutToBeInserted( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesAboutToBeInserted(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesInserted( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesInserted(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesAboutToBeRemoved( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesAboutToBeRemoved(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesRemoved( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesRemoved(first + x, last + x); } } vtkQtChartSeriesModel *vtkQtChartSeriesModelCollection::modelForSeries( int &series) const { QList<vtkQtChartSeriesModel *>::ConstIterator model = this->Models.begin(); for( ; model != this->Models.end(); ++model) { if(series < (*model)->getNumberOfSeries()) { return (*model); } series -= (*model)->getNumberOfSeries(); } return 0; } int vtkQtChartSeriesModelCollection::seriesForModel( vtkQtChartSeriesModel *model) const { int series = 0; QList<vtkQtChartSeriesModel *>::ConstIterator iter = this->Models.begin(); for( ; iter != this->Models.end(); ++iter) { if(model == *iter) { return series; } series += (*iter)->getNumberOfSeries(); } return -1; } <commit_msg>BUG: Fixing the signals when a model is added or removed. This also fixes the paraview representation visibility toggle for the new chart views.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartSeriesModelCollection.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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartSeriesModelCollection.cxx /// \date February 8, 2008 #ifdef _MSC_VER // Disable warnings that Qt headers give. #pragma warning(disable:4127) #endif #include "vtkQtChartSeriesModelCollection.h" vtkQtChartSeriesModelCollection::vtkQtChartSeriesModelCollection( QObject *parentObject) : vtkQtChartSeriesModel(parentObject), Models() { } int vtkQtChartSeriesModelCollection::getNumberOfSeries() const { int series = 0; QList<vtkQtChartSeriesModel *>::ConstIterator model = this->Models.begin(); for( ; model != this->Models.end(); ++model) { series += (*model)->getNumberOfSeries(); } return series; } int vtkQtChartSeriesModelCollection::getNumberOfSeriesValues(int series) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getNumberOfSeriesValues(series); } return 0; } QVariant vtkQtChartSeriesModelCollection::getSeriesName(int series) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesName(series); } return QVariant(); } QVariant vtkQtChartSeriesModelCollection::getSeriesValue(int series, int index, int component) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesValue(series, index, component); } return QVariant(); } QList<QVariant> vtkQtChartSeriesModelCollection::getSeriesRange(int series, int component) const { vtkQtChartSeriesModel *model = this->modelForSeries(series); if(model) { return model->getSeriesRange(series, component); } return QList<QVariant>(); } void vtkQtChartSeriesModelCollection::addSeriesModel( vtkQtChartSeriesModel *model) { if(model) { // Listen for model changes. this->connect(model, SIGNAL(modelAboutToBeReset()), this, SIGNAL(modelAboutToBeReset())); this->connect(model, SIGNAL(modelReset()), this, SIGNAL(modelReset())); this->connect(model, SIGNAL(seriesAboutToBeInserted(int, int)), this, SLOT(onSeriesAboutToBeInserted(int, int))); this->connect(model, SIGNAL(seriesInserted(int, int)), this, SLOT(onSeriesInserted(int, int))); this->connect(model, SIGNAL(seriesAboutToBeRemoved(int, int)), this, SLOT(onSeriesAboutToBeRemoved(int, int))); this->connect(model, SIGNAL(seriesRemoved(int, int)), this, SLOT(onSeriesRemoved(int, int))); // Add the model to the list of models. If the model has series, // the view needs to be notified. int x = this->getNumberOfSeries(); int total = model->getNumberOfSeries(); if(total > 0) { emit this->seriesAboutToBeInserted(x, x + total - 1); } this->Models.append(model); if(total > 0) { emit this->seriesInserted(x, x + total - 1); } } } void vtkQtChartSeriesModelCollection::removeSeriesModel( vtkQtChartSeriesModel *model) { int index = this->Models.indexOf(model); if(index != -1) { // Disconnect from the model change signals. this->disconnect(model, 0, this, 0); // Remove the model from the list. If the model has series, the // view needs to be notified. int x = this->seriesForModel(model); int total = model->getNumberOfSeries(); if(total > 0) { emit this->seriesAboutToBeRemoved(x, x + total - 1); } this->Models.removeAt(index); if(total > 0) { emit this->seriesRemoved(x, x + total - 1); } } } int vtkQtChartSeriesModelCollection::getNumberOfSeriesModels() const { return this->Models.size(); } vtkQtChartSeriesModel* vtkQtChartSeriesModelCollection::getSeriesModel( int index) const { return this->Models[index]; } void vtkQtChartSeriesModelCollection::onSeriesAboutToBeInserted( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesAboutToBeInserted(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesInserted( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesInserted(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesAboutToBeRemoved( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesAboutToBeRemoved(first + x, last + x); } } void vtkQtChartSeriesModelCollection::onSeriesRemoved( int first, int last) { vtkQtChartSeriesModel *model = qobject_cast<vtkQtChartSeriesModel *>( this->sender()); if(model) { int x = this->seriesForModel(model); this->seriesRemoved(first + x, last + x); } } vtkQtChartSeriesModel *vtkQtChartSeriesModelCollection::modelForSeries( int &series) const { QList<vtkQtChartSeriesModel *>::ConstIterator model = this->Models.begin(); for( ; model != this->Models.end(); ++model) { if(series < (*model)->getNumberOfSeries()) { return (*model); } series -= (*model)->getNumberOfSeries(); } return 0; } int vtkQtChartSeriesModelCollection::seriesForModel( vtkQtChartSeriesModel *model) const { int series = 0; QList<vtkQtChartSeriesModel *>::ConstIterator iter = this->Models.begin(); for( ; iter != this->Models.end(); ++iter) { if(model == *iter) { return series; } series += (*iter)->getNumberOfSeries(); } return -1; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/protector/base_setting_change.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" #endif namespace protector { namespace { const char kStartupUrl[] = "http://example.com/"; } // namespace class PrefsBackupInvalidChangeTest : public testing::Test { protected: TestingProfile profile_; }; // Test that correct default values are applied by Init. TEST_F(PrefsBackupInvalidChangeTest, Defaults) { #if defined(OS_MACOSX) if (base::mac::IsOSLionOrLater()) FAIL() << "Broken after r142958; http://crbug.com/134186"; #endif SessionStartupPref startup_pref(SessionStartupPref::URLS); startup_pref.urls.push_back(GURL(kStartupUrl)); SessionStartupPref::SetStartupPref(&profile_, startup_pref); scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange()); change->Init(&profile_); SessionStartupPref new_startup_pref = SessionStartupPref::GetStartupPref(&profile_); // Startup type should be reset to default. EXPECT_EQ(SessionStartupPref::GetDefaultStartupType(), new_startup_pref.type); // Startup URLs should be left unchanged. EXPECT_EQ(1UL, new_startup_pref.urls.size()); EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec()); // Homepage prefs are reset to defaults. PrefService* prefs = profile_.GetPrefs(); EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePageIsNewTabPage)); EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePage)); EXPECT_FALSE(prefs->HasPrefPath(prefs::kShowHomeButton)); } // Test that "restore last session" setting is not changed by Init. TEST_F(PrefsBackupInvalidChangeTest, DefaultsWithSessionRestore) { SessionStartupPref startup_pref(SessionStartupPref::LAST); startup_pref.urls.push_back(GURL(kStartupUrl)); SessionStartupPref::SetStartupPref(&profile_, startup_pref); scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange()); change->Init(&profile_); SessionStartupPref new_startup_pref = SessionStartupPref::GetStartupPref(&profile_); // Both startup type and startup URLs should be left unchanged. EXPECT_EQ(SessionStartupPref::LAST, new_startup_pref.type); EXPECT_EQ(1UL, new_startup_pref.urls.size()); EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec()); } } // namespace protector <commit_msg>Fix: PrefsBackupInvalidChangeTest.Defaults on Mac Lion.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/protector/base_setting_change.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" #endif namespace protector { namespace { const char kStartupUrl[] = "http://example.com/"; } // namespace class PrefsBackupInvalidChangeTest : public testing::Test { protected: virtual void SetUp() OVERRIDE { // Make the tests independent of the Mac startup pref migration (see // SessionStartupPref::MigrateMacDefaultPrefIfNecessary). PrefService* prefs = profile_.GetPrefs(); prefs->SetString(prefs::kProfileCreatedByVersion, "22.0.0.0.0"); } TestingProfile profile_; }; // Test that correct default values are applied by Init. TEST_F(PrefsBackupInvalidChangeTest, Defaults) { SessionStartupPref startup_pref(SessionStartupPref::URLS); startup_pref.urls.push_back(GURL(kStartupUrl)); SessionStartupPref::SetStartupPref(&profile_, startup_pref); scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange()); change->Init(&profile_); SessionStartupPref new_startup_pref = SessionStartupPref::GetStartupPref(&profile_); // Startup type should be reset to default. EXPECT_EQ(SessionStartupPref::GetDefaultStartupType(), new_startup_pref.type); // Startup URLs should be left unchanged. EXPECT_EQ(1UL, new_startup_pref.urls.size()); EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec()); // Homepage prefs are reset to defaults. PrefService* prefs = profile_.GetPrefs(); EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePageIsNewTabPage)); EXPECT_FALSE(prefs->HasPrefPath(prefs::kHomePage)); EXPECT_FALSE(prefs->HasPrefPath(prefs::kShowHomeButton)); } // Test that "restore last session" setting is not changed by Init. TEST_F(PrefsBackupInvalidChangeTest, DefaultsWithSessionRestore) { SessionStartupPref startup_pref(SessionStartupPref::LAST); startup_pref.urls.push_back(GURL(kStartupUrl)); SessionStartupPref::SetStartupPref(&profile_, startup_pref); scoped_ptr<BaseSettingChange> change(CreatePrefsBackupInvalidChange()); change->Init(&profile_); SessionStartupPref new_startup_pref = SessionStartupPref::GetStartupPref(&profile_); // Both startup type and startup URLs should be left unchanged. EXPECT_EQ(SessionStartupPref::LAST, new_startup_pref.type); EXPECT_EQ(1UL, new_startup_pref.urls.size()); EXPECT_EQ(std::string(kStartupUrl), new_startup_pref.urls[0].spec()); } } // namespace protector <|endoftext|>
<commit_before> #include "InverseKinematicsStudy.h" #include "OpenSenseUtilities.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/TimeSeriesTable.h> #include <OpenSim/Common/TableSource.h> #include <OpenSim/Common/STOFileAdapter.h> #include <OpenSim/Common/TRCFileAdapter.h> #include <OpenSim/Common/Reporter.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h> #include <OpenSim/Simulation/InverseKinematicsSolver.h> #include <OpenSim/Simulation/OrientationsReference.h> #include "ExperimentalMarker.h" #include "ExperimentalFrame.h" using namespace OpenSim; using namespace SimTK; using namespace std; InverseKinematicsStudy::InverseKinematicsStudy() { constructProperties(); } InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile) : Object(setupFile, true) { constructProperties(); updateFromXMLDocument(); } InverseKinematicsStudy::~InverseKinematicsStudy() { } void InverseKinematicsStudy::constructProperties() { constructProperty_accuracy(1e-6); constructProperty_constraint_weight(Infinity); Array<double> range{ Infinity, 2}; constructProperty_time_range(range); constructProperty_base_imu_label(""); constructProperty_base_heading_axis("z"); constructProperty_model_file_name(""); constructProperty_marker_file_name(""); constructProperty_orientations_file_name(""); constructProperty_results_directory(""); } void InverseKinematicsStudy:: previewExperimentalData(const TimeSeriesTableVec3& markers, const TimeSeriesTable_<SimTK::Rotation>& orientations) const { Model previewWorld; // Load the marker data into a TableSource that has markers // as its output which each markers occupying its own channel TableSourceVec3* markersSource = new TableSourceVec3(markers); // Add the markersSource Component to the model previewWorld.addComponent(markersSource); // Get the underlying Table backing the the marker Source so we // know how many markers we have and their names const auto& markerData = markersSource->getTable(); auto& times = markerData.getIndependentColumn(); auto startEnd = getTimeRangeInUse(times); // Create an ExperimentalMarker Component for every column in the markerData for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) { auto marker = new ExperimentalMarker(); marker->setName(markerData.getColumnLabel(i)); // markers are owned by the model previewWorld.addComponent(marker); // the time varying location of the marker comes from the markersSource // Component marker->updInput("location_in_ground").connect( markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i))); } previewWorld.setUseVisualizer(true); SimTK::State& state = previewWorld.initSystem(); state.updTime() = times[0]; previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); char c; std::cout << "press any key to visualize experimental marker data ..." << std::endl; std::cin >> c; for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) { std::cout << "time: " << times[j] << "s" << std::endl; state.setTime(times[j]); previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); } } void InverseKinematicsStudy:: runInverseKinematicsWithOrientationsFromFile(Model& model, const std::string& orientationsFileName, bool visualizeResults) { // Add a reporter to get IK computed coordinate values out TableReporter* ikReporter = new TableReporter(); ikReporter->setName("ik_reporter"); auto coordinates = model.updComponentList<Coordinate>(); std::vector<std::string> transCoordNames; // Hookup reporter inputs to the individual coordinate outputs // and keep track of coordinates that are translations for (auto& coord : coordinates) { ikReporter->updInput("inputs").connect( coord.getOutput("value"), coord.getName()); if (coord.getMotionType() == Coordinate::Translational) { transCoordNames.push_back(coord.getName()); coord.set_locked(true); } } model.addComponent(ikReporter); TimeSeriesTable_<SimTK::Quaternion> quatTable = STOFileAdapter_<SimTK::Quaternion>::readFile(orientationsFileName); std::cout << "Loading orientations as quaternions from " << orientationsFileName << std::endl; auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn()); const auto axis_string = IO::Lowercase(get_base_heading_axis()); int axis = (axis_string == "x" ? 0 : ((axis_string == "y") ? 1 : 2) ); SimTK::CoordinateAxis heading{ axis }; cout << "Heading correction for base '" << get_base_imu_label() << "' along its '" << axis_string << "' axis." << endl; TimeSeriesTable_<SimTK::Rotation> orientationsData = OpenSenseUtilities::convertQuaternionsToRotations(quatTable, startEnd, get_base_imu_label(), heading); OrientationsReference oRefs(orientationsData); MarkersReference mRefs{}; SimTK::Array_<CoordinateReference> coordinateReferences; // visualize for debugging if (visualizeResults) model.setUseVisualizer(true); SimTK::State& s0 = model.initSystem(); double t0 = s0.getTime(); // create the solver given the input data const double accuracy = 1e-4; InverseKinematicsSolver ikSolver(model, mRefs, oRefs, coordinateReferences); ikSolver.setAccuracy(accuracy); auto& times = oRefs.getTimes(); s0.updTime() = times[0]; ikSolver.assemble(s0); if (visualizeResults) { model.getVisualizer().show(s0); model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true); } for (auto time : times) { s0.updTime() = time; ikSolver.track(s0); if (visualizeResults) model.getVisualizer().show(s0); else cout << "Solved frame at time: " << time << endl; // realize to report to get reporter to pull values from model model.realizeReport(s0); } auto report = ikReporter->getTable(); auto eix = orientationsFileName.rfind("_"); if (eix == std::string::npos) { eix = orientationsFileName.rfind("."); } auto stix = orientationsFileName.rfind("/") + 1; IO::makeDir(get_results_directory()); std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix); std::string outputFile = get_results_directory() + "/" + outName; // Convert to degrees to compare with marker-based IK // but ignore translational coordinates for (size_t i = 0; i < report.getNumColumns(); ++i) { auto it = find( transCoordNames.begin(), transCoordNames.end(), report.getColumnLabel(i) ); if (it == transCoordNames.end()) { // not found = not translational auto repVec = report.updDependentColumnAtIndex(i); repVec *= SimTK::Real(SimTK_RTD); } } report.updTableMetaData().setValueForKey<string>("name", outName); report.updTableMetaData().setValueForKey<size_t>("nRows", report.getNumRows()); // getNumColumns returns the number of dependent columns, but Storage expects time report.updTableMetaData().setValueForKey<size_t>("nColumns", report.getNumColumns()+1); report.updTableMetaData().setValueForKey<string>("inDegrees","yes"); STOFileAdapter_<double>::write(report, outputFile + ".mot"); std::cout << "Wrote IK with IMU tracking results to: '" << outputFile << "'." << std::endl; } // main driver bool InverseKinematicsStudy::run(bool visualizeResults) { if (_model.empty()) { _model.reset(new Model(get_model_file_name())); } runInverseKinematicsWithOrientationsFromFile(*_model, get_orientations_file_name(), visualizeResults); return true; } SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse( const std::vector<double>& times ) const { int nt = static_cast<int>(times.size()); int startIx = 0; int endIx = nt-1; for (int i = 0; i < nt; ++i) { if (times[i] <= get_time_range(0)) { startIx = i; } else { break; } } for (int i = nt - 1; i > 0; --i) { if (times[i] >= get_time_range(1)) { endIx= i; } else { break; } } SimTK::Array_<int> retArray; retArray.push_back(startIx); retArray.push_back(endIx); return retArray; } TimeSeriesTable_<SimTK::Vec3> InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile) { auto markers = TRCFileAdapter::readFile(markerFile); std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers " << " and " << markers.getNumRows() << " rows of data." << std::endl; if (markers.hasTableMetaDataKey("Units")) { std::cout << markerFile << " has Units meta data." << std::endl; auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; if (value.getValue<std::string>() == "mm") { std::cout << "Marker data in mm, converting to m." << std::endl; for (size_t i = 0; i < markers.getNumRows(); ++i) { markers.updRowAtIndex(i) *= 0.001; } markers.updTableMetaData().removeValueForKey("Units"); markers.updTableMetaData().setValueForKey<std::string>("Units", "m"); } } auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; return markers; }<commit_msg>Remove logic that shortens the output filename and use the entire input filename pre-pended with "ik_" as the resultant output file name.<commit_after> #include "InverseKinematicsStudy.h" #include "OpenSenseUtilities.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/TimeSeriesTable.h> #include <OpenSim/Common/TableSource.h> #include <OpenSim/Common/STOFileAdapter.h> #include <OpenSim/Common/TRCFileAdapter.h> #include <OpenSim/Common/Reporter.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h> #include <OpenSim/Simulation/InverseKinematicsSolver.h> #include <OpenSim/Simulation/OrientationsReference.h> #include "ExperimentalMarker.h" #include "ExperimentalFrame.h" using namespace OpenSim; using namespace SimTK; using namespace std; InverseKinematicsStudy::InverseKinematicsStudy() { constructProperties(); } InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile) : Object(setupFile, true) { constructProperties(); updateFromXMLDocument(); } InverseKinematicsStudy::~InverseKinematicsStudy() { } void InverseKinematicsStudy::constructProperties() { constructProperty_accuracy(1e-6); constructProperty_constraint_weight(Infinity); Array<double> range{ Infinity, 2}; constructProperty_time_range(range); constructProperty_base_imu_label(""); constructProperty_base_heading_axis("z"); constructProperty_model_file_name(""); constructProperty_marker_file_name(""); constructProperty_orientations_file_name(""); constructProperty_results_directory(""); } void InverseKinematicsStudy:: previewExperimentalData(const TimeSeriesTableVec3& markers, const TimeSeriesTable_<SimTK::Rotation>& orientations) const { Model previewWorld; // Load the marker data into a TableSource that has markers // as its output which each markers occupying its own channel TableSourceVec3* markersSource = new TableSourceVec3(markers); // Add the markersSource Component to the model previewWorld.addComponent(markersSource); // Get the underlying Table backing the the marker Source so we // know how many markers we have and their names const auto& markerData = markersSource->getTable(); auto& times = markerData.getIndependentColumn(); auto startEnd = getTimeRangeInUse(times); // Create an ExperimentalMarker Component for every column in the markerData for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) { auto marker = new ExperimentalMarker(); marker->setName(markerData.getColumnLabel(i)); // markers are owned by the model previewWorld.addComponent(marker); // the time varying location of the marker comes from the markersSource // Component marker->updInput("location_in_ground").connect( markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i))); } previewWorld.setUseVisualizer(true); SimTK::State& state = previewWorld.initSystem(); state.updTime() = times[0]; previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); char c; std::cout << "press any key to visualize experimental marker data ..." << std::endl; std::cin >> c; for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) { std::cout << "time: " << times[j] << "s" << std::endl; state.setTime(times[j]); previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); } } void InverseKinematicsStudy:: runInverseKinematicsWithOrientationsFromFile(Model& model, const std::string& orientationsFileName, bool visualizeResults) { // Add a reporter to get IK computed coordinate values out TableReporter* ikReporter = new TableReporter(); ikReporter->setName("ik_reporter"); auto coordinates = model.updComponentList<Coordinate>(); std::vector<std::string> transCoordNames; // Hookup reporter inputs to the individual coordinate outputs // and keep track of coordinates that are translations for (auto& coord : coordinates) { ikReporter->updInput("inputs").connect( coord.getOutput("value"), coord.getName()); if (coord.getMotionType() == Coordinate::Translational) { transCoordNames.push_back(coord.getName()); coord.set_locked(true); } } model.addComponent(ikReporter); TimeSeriesTable_<SimTK::Quaternion> quatTable = STOFileAdapter_<SimTK::Quaternion>::readFile(orientationsFileName); std::cout << "Loading orientations as quaternions from " << orientationsFileName << std::endl; auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn()); const auto axis_string = IO::Lowercase(get_base_heading_axis()); int axis = (axis_string == "x" ? 0 : ((axis_string == "y") ? 1 : 2) ); SimTK::CoordinateAxis heading{ axis }; cout << "Heading correction for base '" << get_base_imu_label() << "' along its '" << axis_string << "' axis." << endl; TimeSeriesTable_<SimTK::Rotation> orientationsData = OpenSenseUtilities::convertQuaternionsToRotations(quatTable, startEnd, get_base_imu_label(), heading); OrientationsReference oRefs(orientationsData); MarkersReference mRefs{}; SimTK::Array_<CoordinateReference> coordinateReferences; // visualize for debugging if (visualizeResults) model.setUseVisualizer(true); SimTK::State& s0 = model.initSystem(); double t0 = s0.getTime(); // create the solver given the input data const double accuracy = 1e-4; InverseKinematicsSolver ikSolver(model, mRefs, oRefs, coordinateReferences); ikSolver.setAccuracy(accuracy); auto& times = oRefs.getTimes(); s0.updTime() = times[0]; ikSolver.assemble(s0); if (visualizeResults) { model.getVisualizer().show(s0); model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true); } for (auto time : times) { s0.updTime() = time; ikSolver.track(s0); if (visualizeResults) model.getVisualizer().show(s0); else cout << "Solved frame at time: " << time << endl; // realize to report to get reporter to pull values from model model.realizeReport(s0); } auto report = ikReporter->getTable(); auto eix = orientationsFileName.rfind("."); auto stix = orientationsFileName.rfind("/") + 1; IO::makeDir(get_results_directory()); std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix); std::string outputFile = get_results_directory() + "/" + outName; // Convert to degrees to compare with marker-based IK // but ignore translational coordinates for (size_t i = 0; i < report.getNumColumns(); ++i) { auto it = find( transCoordNames.begin(), transCoordNames.end(), report.getColumnLabel(i) ); if (it == transCoordNames.end()) { // not found = not translational auto repVec = report.updDependentColumnAtIndex(i); repVec *= SimTK::Real(SimTK_RTD); } } report.updTableMetaData().setValueForKey<string>("name", outName); report.updTableMetaData().setValueForKey<size_t>("nRows", report.getNumRows()); // getNumColumns returns the number of dependent columns, but Storage expects time report.updTableMetaData().setValueForKey<size_t>("nColumns", report.getNumColumns()+1); report.updTableMetaData().setValueForKey<string>("inDegrees","yes"); STOFileAdapter_<double>::write(report, outputFile + ".mot"); std::cout << "Wrote IK with IMU tracking results to: '" << outputFile << "'." << std::endl; } // main driver bool InverseKinematicsStudy::run(bool visualizeResults) { if (_model.empty()) { _model.reset(new Model(get_model_file_name())); } runInverseKinematicsWithOrientationsFromFile(*_model, get_orientations_file_name(), visualizeResults); return true; } SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse( const std::vector<double>& times ) const { int nt = static_cast<int>(times.size()); int startIx = 0; int endIx = nt-1; for (int i = 0; i < nt; ++i) { if (times[i] <= get_time_range(0)) { startIx = i; } else { break; } } for (int i = nt - 1; i > 0; --i) { if (times[i] >= get_time_range(1)) { endIx= i; } else { break; } } SimTK::Array_<int> retArray; retArray.push_back(startIx); retArray.push_back(endIx); return retArray; } TimeSeriesTable_<SimTK::Vec3> InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile) { auto markers = TRCFileAdapter::readFile(markerFile); std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers " << " and " << markers.getNumRows() << " rows of data." << std::endl; if (markers.hasTableMetaDataKey("Units")) { std::cout << markerFile << " has Units meta data." << std::endl; auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; if (value.getValue<std::string>() == "mm") { std::cout << "Marker data in mm, converting to m." << std::endl; for (size_t i = 0; i < markers.getNumRows(); ++i) { markers.updRowAtIndex(i) *= 0.001; } markers.updTableMetaData().removeValueForKey("Units"); markers.updTableMetaData().setValueForKey<std::string>("Units", "m"); } } auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; return markers; }<|endoftext|>
<commit_before> /* App.cpp * * Copyright (C) 2013 Michael Imamura * * 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 "StdAfx.h" #include "Exception.h" #include "FinalScene.h" #include "IntroScene.h" #include "MainLoopScene.h" #include "PreloadScene.h" #include "ResStr.h" #include "Scene.h" #include "App.h" namespace AISDL { /** * Constructor. * @param startingScene Index of the scene to start. */ App::App(int startingScene) : SUPER(), display(), startingScene(startingScene), sceneIdx(-1), clockDecor(display) { AddScene(std::make_shared<IntroScene>(*this, display)); AddScene(std::make_shared<MainLoopScene>(*this, display)); AddScene(std::make_shared<FinalScene>(*this, display)); } App::~App() { } /** * Add a scene to the end of the scene list. * @param scene The scene (may not be @c nullptr). */ void App::AddScene(std::shared_ptr<Scene> scene) { scenes.emplace_back(std::move(scene)); } /** * Attempt to attach a game controller. * @param idx The joystick index. * @return @c true if attached successfully, @c false otherwise. */ bool App::AttachController(int idx) { if (!SDL_IsGameController(idx)) return false; SDL_GameController *controller = SDL_GameControllerOpen(idx); if (!controller) { SDL_Log("Could not open controller %d: %s", idx, SDL_GetError()); return false; } // Keep track of the instance ID of each controller so we can detach it // later -- the detach event returns the instance ID, not the index! int instanceId = SDL_JoystickInstanceID( SDL_GameControllerGetJoystick(controller)); gameControllers[instanceId] = controller; SDL_Log("Attached controller index=%d instance=%d (%s).", idx, instanceId, SDL_GameControllerName(controller)); return true; } /** * Attempt to detach a game controller. * @param instanceId The joystick instance ID (not the index!). * @return @c true if detached successfully, @c false otherwise. */ bool App::DetachController(int instanceId) { auto iter = gameControllers.find(instanceId); if (iter == gameControllers.end()) { SDL_Log("Unable to find controller for instance ID: %d", instanceId); return false; } else { SDL_GameControllerClose(iter->second); gameControllers.erase(iter); SDL_Log("Detached controller instance=%d.", instanceId); return true; } } /** * Handle when a controller button is pressed. * @param evt The button press event. */ void App::OnControllerButtonDown(SDL_ControllerButtonEvent &evt) { const SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(evt.button); SDL_Log("Controller button pressed [%d]: %s", btn, SDL_GameControllerGetStringForButton(btn)); switch (btn) { case SDL_CONTROLLER_BUTTON_A: scene->OnAction(); break; case SDL_CONTROLLER_BUTTON_B: scene->OnCancel(); break; case SDL_CONTROLLER_BUTTON_X: scene->OnInteract(); break; case SDL_CONTROLLER_BUTTON_LEFTSTICK: ResStr::ReloadAll(); break; case SDL_CONTROLLER_BUTTON_BACK: clockDecor.Flash(); break; case SDL_CONTROLLER_BUTTON_START: //TODO: Switch to TOC (last scene in list). break; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: RequestPrevScene(); break; case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: RequestNextScene(); break; default: // Ignore. break; } } /** * Handle when a key is pressed. * @param evt The key pressed event. */ void App::OnKeyDown(SDL_KeyboardEvent &evt) { switch (evt.keysym.sym) { case SDLK_RETURN: if (evt.keysym.mod & KMOD_ALT) { // Alt+Enter - Toggle fullscreen. display.ToggleFullscreen(); } else { scene->OnAction(); } break; case SDLK_ESCAPE: scene->OnCancel(); break; case SDLK_e: scene->OnInteract(); break; case SDLK_F5: ResStr::ReloadAll(); break; case SDLK_TAB: clockDecor.Flash(); break; case SDLK_HOME: //TODO: Switch to TOC (last scene in list). break; case SDLK_PAGEUP: RequestPrevScene(); break; case SDLK_PAGEDOWN: RequestNextScene(); break; default: // Ignore. break; } } /** * Main loop. */ void App::Run() { bool quit = false; SDL_Event evt; // Always start with the preload scene. // When the preloader finishes, it'll request to switch to the next scene. scene = std::make_shared<PreloadScene>(*this, display); // Attach all already-plugged-in controllers. for (int i = 0; i < SDL_NumJoysticks(); i++) { AttachController(i); } while (!quit) { // Process all events that have been triggered since the last // frame was rendered. while (SDL_PollEvent(&evt) && !quit) { switch (evt.type) { case SDL_KEYDOWN: OnKeyDown(evt.key); break; // SDL_ControllerButtonEvent case SDL_CONTROLLERBUTTONDOWN: OnControllerButtonDown(evt.cbutton); break; // SDL_ControllerDeviceEvent case SDL_CONTROLLERDEVICEADDED: AttachController(evt.cdevice.which); break; case SDL_CONTROLLERDEVICEREMOVED: DetachController(evt.cdevice.which); break; case SDL_CONTROLLERDEVICEREMAPPED: //TODO SDL_Log("Remapped controller: %d", evt.cdevice.which); break; case SDL_QUIT: quit = true; break; } // Let the current scene have a chance at handling the event. scene->HandleEvent(evt); } if (quit) break; RenderFrame(*scene); // If a new scene was requested, switch to it. if (nextScene) { scene = nextScene; nextScene.reset(); } } // Detach all controllers. while (!gameControllers.empty()) { DetachController(gameControllers.begin()->first); } SDL_Log("Shutting down."); } void App::RenderFrame(Scene &scene) { auto tick = SDL_GetTicks(); scene.Advance(tick); clockDecor.Advance(tick); // We let the scene decide how to clear the frame. scene.Render(); clockDecor.Render(); SDL_RenderPresent(display.renderer); } void App::RequestPrevScene() { if (sceneIdx > 0) { sceneIdx--; SDL_Log("Switching to scene: %d", sceneIdx); nextScene = scenes[sceneIdx]; } } void App::RequestNextScene() { if (sceneIdx == -1) { // The scene at -1 is the preload scene; it's followed by the // requested starting scene. sceneIdx = startingScene; if (startingScene < 0 || startingScene >= (int)scenes.size()) { std::ostringstream oss; oss << "Invalid starting scene index [" << startingScene << "] -- " "Starting scene must be in range 0.." << (scenes.size() - 1) << " (inclusive)"; throw Exception(oss.str()); } } else if (sceneIdx == scenes.size() - 1) { // At the final scene. return; } else { sceneIdx++; } SDL_Log("Switching to scene: %d", sceneIdx); nextScene = scenes[sceneIdx]; } void App::RequestShutdown() { // Handle the shutdown in a calm and orderly fashion, when the // main loop gets around to it. SDL_Event evt; evt.type = SDL_QUIT; SDL_PushEvent(&evt); } } // namespace AISDL <commit_msg>Remove log cruft.<commit_after> /* App.cpp * * Copyright (C) 2013 Michael Imamura * * 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 "StdAfx.h" #include "Exception.h" #include "FinalScene.h" #include "IntroScene.h" #include "MainLoopScene.h" #include "PreloadScene.h" #include "ResStr.h" #include "Scene.h" #include "App.h" namespace AISDL { /** * Constructor. * @param startingScene Index of the scene to start. */ App::App(int startingScene) : SUPER(), display(), startingScene(startingScene), sceneIdx(-1), clockDecor(display) { AddScene(std::make_shared<IntroScene>(*this, display)); AddScene(std::make_shared<MainLoopScene>(*this, display)); AddScene(std::make_shared<FinalScene>(*this, display)); } App::~App() { } /** * Add a scene to the end of the scene list. * @param scene The scene (may not be @c nullptr). */ void App::AddScene(std::shared_ptr<Scene> scene) { scenes.emplace_back(std::move(scene)); } /** * Attempt to attach a game controller. * @param idx The joystick index. * @return @c true if attached successfully, @c false otherwise. */ bool App::AttachController(int idx) { if (!SDL_IsGameController(idx)) return false; SDL_GameController *controller = SDL_GameControllerOpen(idx); if (!controller) { SDL_Log("Could not open controller %d: %s", idx, SDL_GetError()); return false; } // Keep track of the instance ID of each controller so we can detach it // later -- the detach event returns the instance ID, not the index! int instanceId = SDL_JoystickInstanceID( SDL_GameControllerGetJoystick(controller)); gameControllers[instanceId] = controller; SDL_Log("Attached controller index=%d instance=%d (%s).", idx, instanceId, SDL_GameControllerName(controller)); return true; } /** * Attempt to detach a game controller. * @param instanceId The joystick instance ID (not the index!). * @return @c true if detached successfully, @c false otherwise. */ bool App::DetachController(int instanceId) { auto iter = gameControllers.find(instanceId); if (iter == gameControllers.end()) { SDL_Log("Unable to find controller for instance ID: %d", instanceId); return false; } else { SDL_GameControllerClose(iter->second); gameControllers.erase(iter); SDL_Log("Detached controller instance=%d.", instanceId); return true; } } /** * Handle when a controller button is pressed. * @param evt The button press event. */ void App::OnControllerButtonDown(SDL_ControllerButtonEvent &evt) { const SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(evt.button); switch (btn) { case SDL_CONTROLLER_BUTTON_A: scene->OnAction(); break; case SDL_CONTROLLER_BUTTON_B: scene->OnCancel(); break; case SDL_CONTROLLER_BUTTON_X: scene->OnInteract(); break; case SDL_CONTROLLER_BUTTON_LEFTSTICK: ResStr::ReloadAll(); break; case SDL_CONTROLLER_BUTTON_BACK: clockDecor.Flash(); break; case SDL_CONTROLLER_BUTTON_START: //TODO: Switch to TOC (last scene in list). break; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: RequestPrevScene(); break; case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: RequestNextScene(); break; default: // Ignore. break; } } /** * Handle when a key is pressed. * @param evt The key pressed event. */ void App::OnKeyDown(SDL_KeyboardEvent &evt) { switch (evt.keysym.sym) { case SDLK_RETURN: if (evt.keysym.mod & KMOD_ALT) { // Alt+Enter - Toggle fullscreen. display.ToggleFullscreen(); } else { scene->OnAction(); } break; case SDLK_ESCAPE: scene->OnCancel(); break; case SDLK_e: scene->OnInteract(); break; case SDLK_F5: ResStr::ReloadAll(); break; case SDLK_TAB: clockDecor.Flash(); break; case SDLK_HOME: //TODO: Switch to TOC (last scene in list). break; case SDLK_PAGEUP: RequestPrevScene(); break; case SDLK_PAGEDOWN: RequestNextScene(); break; default: // Ignore. break; } } /** * Main loop. */ void App::Run() { bool quit = false; SDL_Event evt; // Always start with the preload scene. // When the preloader finishes, it'll request to switch to the next scene. scene = std::make_shared<PreloadScene>(*this, display); // Attach all already-plugged-in controllers. for (int i = 0; i < SDL_NumJoysticks(); i++) { AttachController(i); } while (!quit) { // Process all events that have been triggered since the last // frame was rendered. while (SDL_PollEvent(&evt) && !quit) { switch (evt.type) { case SDL_KEYDOWN: OnKeyDown(evt.key); break; // SDL_ControllerButtonEvent case SDL_CONTROLLERBUTTONDOWN: OnControllerButtonDown(evt.cbutton); break; // SDL_ControllerDeviceEvent case SDL_CONTROLLERDEVICEADDED: AttachController(evt.cdevice.which); break; case SDL_CONTROLLERDEVICEREMOVED: DetachController(evt.cdevice.which); break; case SDL_CONTROLLERDEVICEREMAPPED: //TODO SDL_Log("Remapped controller: %d", evt.cdevice.which); break; case SDL_QUIT: quit = true; break; } // Let the current scene have a chance at handling the event. scene->HandleEvent(evt); } if (quit) break; RenderFrame(*scene); // If a new scene was requested, switch to it. if (nextScene) { scene = nextScene; nextScene.reset(); } } // Detach all controllers. while (!gameControllers.empty()) { DetachController(gameControllers.begin()->first); } SDL_Log("Shutting down."); } void App::RenderFrame(Scene &scene) { auto tick = SDL_GetTicks(); scene.Advance(tick); clockDecor.Advance(tick); // We let the scene decide how to clear the frame. scene.Render(); clockDecor.Render(); SDL_RenderPresent(display.renderer); } void App::RequestPrevScene() { if (sceneIdx > 0) { sceneIdx--; SDL_Log("Switching to scene: %d", sceneIdx); nextScene = scenes[sceneIdx]; } } void App::RequestNextScene() { if (sceneIdx == -1) { // The scene at -1 is the preload scene; it's followed by the // requested starting scene. sceneIdx = startingScene; if (startingScene < 0 || startingScene >= (int)scenes.size()) { std::ostringstream oss; oss << "Invalid starting scene index [" << startingScene << "] -- " "Starting scene must be in range 0.." << (scenes.size() - 1) << " (inclusive)"; throw Exception(oss.str()); } } else if (sceneIdx == scenes.size() - 1) { // At the final scene. return; } else { sceneIdx++; } SDL_Log("Switching to scene: %d", sceneIdx); nextScene = scenes[sceneIdx]; } void App::RequestShutdown() { // Handle the shutdown in a calm and orderly fashion, when the // main loop gets around to it. SDL_Event evt; evt.type = SDL_QUIT; SDL_PushEvent(&evt); } } // namespace AISDL <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; //------------------------------------------------------------------------------------------------- // Helper functions // // nested for loop over matrices -------------------------- template <typename Func> void for_each_mat4_e(Func f) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { f(i, j); } } } // get rows and columns ----------------------------------- vec4 get_row(mat4 const& m, int i) { assert( i >= 0 && i < 4 ); return vec4( m(i, 0), m(i, 1), m(i, 2), m(i, 3) ); } vec4 get_col(mat4 const& m, int j) { assert( j >= 0 && j < 4 ); return m(j); } TEST(Matrix, Inverse) { //------------------------------------------------------------------------- // mat4 // mat4 I = mat4::identity(); // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = inverse(A); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(C(i, j), I(i, j)); } ); } TEST(Matrix, Mult) { //------------------------------------------------------------------------- // mat4 // // make some non-singular matrices mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = make_translation(vec3(3, 4, 5)); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { float d = dot(get_row(A, i), get_col(B, j)); EXPECT_FLOAT_EQ(C(i, j), d); } ); } TEST(Matrix, Transpose) { //------------------------------------------------------------------------- // mat4 // // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = transpose(A); for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(A(i, j), B(j, i)); } ); } <commit_msg>Expand matrix unit tests to mat3<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; //------------------------------------------------------------------------------------------------- // Helper functions // // nested for loop over matrices -------------------------- template <typename Func> void for_each_mat3_e(Func f) { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { f(i, j); } } } template <typename Func> void for_each_mat4_e(Func f) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { f(i, j); } } } // get rows and columns ----------------------------------- template <size_t Dim> vector<Dim, float> get_row(matrix<Dim, Dim, float> const& m, int i) { assert( i >= 0 && i < 4 ); vector<Dim, float> result; for (size_t d = 0; d < Dim; ++d) { result[d] = m(i, d); } return result; } template <size_t Dim> vector<Dim, float> get_col(matrix<Dim, Dim, float> const& m, int j) { assert( j >= 0 && j < 4 ); return m(j); } TEST(Matrix, Inverse) { //------------------------------------------------------------------------- // mat4 // mat4 I = mat4::identity(); // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = inverse(A); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(C(i, j), I(i, j)); } ); } TEST(Matrix, Mult) { //------------------------------------------------------------------------- // mat3 // { // make some matrices mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f; mat3 B = mat3::identity(); B(0, 1) = 11.0f; B(2, 1) = 6.28f; B(2, 2) = 3.0f; mat3 C = A * B; for_each_mat3_e( [&](int i, int j) { float d = dot(get_row(A, i), get_col(B, j)); EXPECT_FLOAT_EQ(C(i, j), d); } ); } //------------------------------------------------------------------------- // mat4 // { // make some matrices mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = make_translation(vec3(3, 4, 5)); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { float d = dot(get_row(A, i), get_col(B, j)); EXPECT_FLOAT_EQ(C(i, j), d); } ); } } TEST(Matrix, Transpose) { //------------------------------------------------------------------------- // mat3 // { // make some non-singular matrix mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f; mat3 B = transpose(A); for_each_mat3_e( [&](int i, int j) { EXPECT_FLOAT_EQ(A(i, j), B(j, i)); } ); } //------------------------------------------------------------------------- // mat4 // { // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = transpose(A); for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(A(i, j), B(j, i)); } ); } } <|endoftext|>
<commit_before>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <vector> #include <message.hpp> #include <parser.hpp> namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK_EQUAL( msg.base_, copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } for(const Message& msg : state.messages_) { BOOST_CHECK_EQUAL( msg.base_, copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.length_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.length_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.length_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.length_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.length_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } } } <commit_msg>Parser: fix Valgrind errors in tests<commit_after>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <vector> #include <message.hpp> #include <parser.hpp> namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } for(const Message& msg : state.messages_) { BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.length_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.length_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.length_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.length_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.length_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } } } <|endoftext|>
<commit_before>#include <algorithm> #include "CPU.hpp" #include "WordDecoder.hpp" namespace Core8 { CPU::CPU(MMU& mmu, IoDevice& ioDevice, RandomNumberGenerator& rndGenerator) : m_mmu{mmu}, m_ioDevice{ioDevice}, m_rndGenerator{rndGenerator}, m_dispatchTable{ {Chip8::OpCode::CLEAR_SCREEN, [this] () { clearDisplay(); }}, {Chip8::OpCode::JUMP, [this] () { jumpToNnn(); }}, {Chip8::OpCode::RETURN, [this] () { returnFromSubroutine(); }}, {Chip8::OpCode::CALL, [this] () { callNNN(); }}, {Chip8::OpCode::SKIP_IF_VX_EQUALS_NN, [this] () { skipIfVxEqualsNn(); }}, {Chip8::OpCode::SKIP_IF_VX_NOT_EQUALS_NN, [this] () { skipIfVxNotEqualsNn(); }}, {Chip8::OpCode::SKIP_IF_VX_EQUALS_VY, [this] () { skipIfVxEqualsVy(); }}, {Chip8::OpCode::SKIP_IF_VX_NOT_EQUALS_VY, [this] () { skipIfVxNotEqualsVy(); }}, {Chip8::OpCode::LOAD_NN_TO_VX, [this] () { loadNnToVx(); }}, {Chip8::OpCode::ADD_NN_TO_VX, [this] () { addNnToVx(); }}, {Chip8::OpCode::LOAD_VY_TO_VX, [this] () { loadVyToVx(); }}, {Chip8::OpCode::VX_OR_VY, [this] () { bitwiseVxOrVy(); }}, {Chip8::OpCode::VX_AND_VY, [this] () { bitwiseVxAndVy(); }}, {Chip8::OpCode::VX_XOR_VY, [this] () { bitwiseVxXorVy(); }}, {Chip8::OpCode::SHIFT_VX_RIGHT, [this] () { shiftVxRight(); }}, {Chip8::OpCode::SHIFT_VX_LEFT, [this] () { shiftVxLeft(); }}, {Chip8::OpCode::VX_PLUS_VY, [this] () { addVyToVx(); }}, {Chip8::OpCode::VX_MINUS_VY, [this] () { subVyFromVx(); }}, {Chip8::OpCode::SET_VX_TO_VY_MINUS_VX, [this] () { subVxFromVy(); }}, {Chip8::OpCode::JUMP_NNN_PLUS_V0, [this] () { jumpToNnnPlusV0(); }}, {Chip8::OpCode::LOAD_DELAY_TIMER_TO_VX, [this] () { loadDelayToVx(); }}, {Chip8::OpCode::LOAD_VX_TO_DELAY_TIMER, [this] () { loadVxToDelay(); }}, {Chip8::OpCode::LOAD_VX_TO_SOUND_TIMER, [this] () { loadVxToSound(); }}, {Chip8::OpCode::LOAD_NNN_TO_I, [this] () { loadNnnToI(); }}, {Chip8::OpCode::LOAD_V0_TO_VX_IN_ADDRESS_I, [this] () { loadRegistersToI(); }}, {Chip8::OpCode::LOAD_ADDRESS_I_TO_V0_TO_VX, [this] () { loadItoRegisters(); }}, {Chip8::OpCode::ADD_VX_TO_I, [this] () { addVxToI(); }}, {Chip8::OpCode::LOAD_FONT_SPRITE_ADDRESS_TO_I, [this] () { loadFontSpriteAddressToI(); }}, {Chip8::OpCode::DRAW, [this]() { draw(); }}, {Chip8::OpCode::SKIP_IF_VX_IS_PRESSED, [this] () { executeSkipIfVxIsPressed(); }}, {Chip8::OpCode::SKIP_IF_VX_IS_NOT_PRESSED, [this] () { executeSkipIfVxIsNotPressed(); }}, {Chip8::OpCode::LOAD_PRESSED_KEY_TO_VX, [this] () { executeWaitPressedKeyToVx(); }}, {Chip8::OpCode::LOAD_VX_BCD_TO_I, [this] () { executeLoadVxBcdToI(); }}, {Chip8::OpCode::LOAD_RANDOM_TO_VX, [this] () { executeLoadRandomToVx(); }} } { m_registers.fill(0x0); m_mmu.load(Chip8::FONT_SET, 0x0); } Chip8::BYTE CPU::readRegister(const Chip8::Register id) const { return m_registers[static_cast<std::size_t>(id)]; } void CPU::writeRegister(const Chip8::Register id, const Chip8::BYTE value) { m_registers[static_cast<std::size_t>(id)] = value; } void CPU::loadToRegisters(const std::vector<Chip8::BYTE> values) { const auto size = std::min(values.size(), m_registers.size()); std::copy_n(std::begin(values), size, std::begin(m_registers)); } void CPU::cycle() { fetch(); decode(); execute(); updateDelayTimer(); updateSoundTimer(); } void CPU::execute(const Chip8::WORD instr) { m_instruction = instr; decode(); execute(); } void CPU::fetch() { m_instruction = m_mmu.readWord(m_pc); m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } void CPU::decode() { m_opcode = OpDecoder::decode(m_instruction); } void CPU::execute() { m_dispatchTable.at(m_opcode)(); } void CPU::updateDelayTimer() { if (m_delayTimer > 0) { --m_delayTimer; } } void CPU::updateSoundTimer() { if (m_soundTimer > 0) { --m_soundTimer; } } void CPU::clearDisplay() { m_frameBuffer.fill(0x0); m_ioDevice.drawScreen(m_frameBuffer); } void CPU::jumpToNnn() { m_pc = WordDecoder::readNNN(m_instruction); } void CPU::returnFromSubroutine() { m_pc = m_stack.at(--m_sp); } void CPU::callNNN() { m_stack.at(m_sp++) = m_pc; m_pc = WordDecoder::readNNN(m_instruction); } void CPU::skipIfVxEqualsNn() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); if (m_registers.at(x) == nn) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxNotEqualsNn() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); if (m_registers.at(x) != nn) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxEqualsVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); if (m_registers.at(x) == m_registers.at(y)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxNotEqualsVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); if (m_registers.at(x) != m_registers.at(y)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::loadNnToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); m_registers.at(x) = nn; } void CPU::addNnToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); m_registers.at(x) += nn; } void CPU::loadVyToVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) = m_registers.at(y); } void CPU::bitwiseVxOrVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) |= m_registers.at(y); } void CPU::bitwiseVxAndVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) &= m_registers.at(y); } void CPU::bitwiseVxXorVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) ^= m_registers.at(y); } void CPU::shiftVxRight() { const auto x = WordDecoder::readX(m_instruction); const auto mask = static_cast<Chip8::BYTE>(0x1); auto& vx = m_registers.at(x); writeRegister(Chip8::Register::VF, vx & mask); vx >>= 1; } void CPU::shiftVxLeft() { const auto x = WordDecoder::readX(m_instruction); auto& vx = m_registers.at(x); writeRegister(Chip8::Register::VF, vx >> 7); vx <<= 1; } void CPU::addVyToVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasCarry = vy > (0xFF - vx); writeRegister(Chip8::Register::VF, hasCarry ? 0x1 : 0x0); vx += vy; } void CPU::subVyFromVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasBorrow = vy > vx; writeRegister(Chip8::Register::VF, hasBorrow ? 0x0 : 0x1); vx -= vy; } void CPU::subVxFromVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasBorrow = vx > vy; writeRegister(Chip8::Register::VF, hasBorrow ? 0x0 : 0x1); vx = vy - vx; } void CPU::jumpToNnnPlusV0() { m_pc = WordDecoder::readNNN(m_instruction) + m_registers.at(0x0); } void CPU::loadDelayToVx() { const auto x = WordDecoder::readX(m_instruction); m_registers.at(x) = m_delayTimer; } void CPU::loadVxToDelay() { const auto x = WordDecoder::readX(m_instruction); m_delayTimer = m_registers.at(x); } void CPU::loadVxToSound() { const auto x = WordDecoder::readX(m_instruction); m_soundTimer = m_registers.at(x); } void CPU::loadNnnToI() { m_I = WordDecoder::readNNN(m_instruction); } void CPU::loadRegistersToI() { const auto x = WordDecoder::readX(m_instruction); for (std::size_t i = 0; i <= x; ++i) { m_mmu.writeByte(m_registers.at(i), m_I + i); } m_I += x + 1; } void CPU::loadItoRegisters() { const auto x = WordDecoder::readX(m_instruction); for (std::size_t i = 0; i <= x; ++i) { m_registers.at(i) = m_mmu.readByte(m_I + i); } m_I += x + 1; } void CPU::addVxToI() { const auto x = WordDecoder::readX(m_instruction); m_I += m_registers.at(x); } void CPU::loadFontSpriteAddressToI() { const auto x = WordDecoder::readX(m_instruction); m_I = m_registers.at(x) * Chip8::CHAR_SPRITE_SIZE; } void CPU::draw() { const auto vx = WordDecoder::readX(m_instruction); const auto vy = WordDecoder::readY(m_instruction); const auto x = m_registers.at(vx); const auto y = m_registers.at(vy); const auto height = WordDecoder::readN(m_instruction); Chip8::BYTE flipped{0x0u}; for (auto line = 0u; line < height; ++line) { const auto rowPixels = m_mmu.readByte(m_I + line); for (auto row = 0u; row < Chip8::SPRITE_WIDTH; ++row) { if ((rowPixels & (0x80 >> row)) != 0) { const auto offset = (x + row + ((y + line) * 64)) % 2048; Chip8::BYTE& pixel = m_frameBuffer.at(offset); if (pixel != 0) { flipped = 1u; } pixel ^= 1u; } } } writeRegister(Chip8::Register::VF, flipped); m_ioDevice.drawScreen(m_frameBuffer); } void CPU::executeSkipIfVxIsPressed() { const auto x = WordDecoder::readX(m_instruction); const auto key = static_cast<Chip8::Key>(m_registers.at(x)); if (m_ioDevice.isKeyPressed(key)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeSkipIfVxIsNotPressed() { const auto x = WordDecoder::readX(m_instruction); const auto key = static_cast<Chip8::Key>(m_registers.at(x)); if (!m_ioDevice.isKeyPressed(key)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeWaitPressedKeyToVx() { const auto pressedKey = m_ioDevice.getPressedKey(); if (pressedKey != Chip8::Key::NONE) { const auto x = WordDecoder::readX(m_instruction); m_registers.at(x) = static_cast<Chip8::BYTE>(pressedKey); m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeLoadVxBcdToI() { const auto x = WordDecoder::readX(m_instruction); const auto vx = m_registers.at(x); const auto hundreds = vx / 100; const auto tens = (vx / 10) % 10; const auto ones = (vx % 100) % 10; m_mmu.writeByte(hundreds, m_I); m_mmu.writeByte(tens, m_I + 1u); m_mmu.writeByte(ones, m_I + 2u); } void CPU::executeLoadRandomToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); const auto randomNumber = m_rndGenerator.get(); m_registers.at(x) = nn & randomNumber; } } //namespace Core8<commit_msg>Refactor CPU<commit_after>#include <algorithm> #include "CPU.hpp" #include "WordDecoder.hpp" namespace Core8 { CPU::CPU(MMU& mmu, IoDevice& ioDevice, RandomNumberGenerator& rndGenerator) : m_mmu{mmu}, m_ioDevice{ioDevice}, m_rndGenerator{rndGenerator}, m_dispatchTable{ {Chip8::OpCode::CLEAR_SCREEN, [this] () { clearDisplay(); }}, {Chip8::OpCode::JUMP, [this] () { jumpToNnn(); }}, {Chip8::OpCode::RETURN, [this] () { returnFromSubroutine(); }}, {Chip8::OpCode::CALL, [this] () { callNNN(); }}, {Chip8::OpCode::SKIP_IF_VX_EQUALS_NN, [this] () { skipIfVxEqualsNn(); }}, {Chip8::OpCode::SKIP_IF_VX_NOT_EQUALS_NN, [this] () { skipIfVxNotEqualsNn(); }}, {Chip8::OpCode::SKIP_IF_VX_EQUALS_VY, [this] () { skipIfVxEqualsVy(); }}, {Chip8::OpCode::SKIP_IF_VX_NOT_EQUALS_VY, [this] () { skipIfVxNotEqualsVy(); }}, {Chip8::OpCode::LOAD_NN_TO_VX, [this] () { loadNnToVx(); }}, {Chip8::OpCode::ADD_NN_TO_VX, [this] () { addNnToVx(); }}, {Chip8::OpCode::LOAD_VY_TO_VX, [this] () { loadVyToVx(); }}, {Chip8::OpCode::VX_OR_VY, [this] () { bitwiseVxOrVy(); }}, {Chip8::OpCode::VX_AND_VY, [this] () { bitwiseVxAndVy(); }}, {Chip8::OpCode::VX_XOR_VY, [this] () { bitwiseVxXorVy(); }}, {Chip8::OpCode::SHIFT_VX_RIGHT, [this] () { shiftVxRight(); }}, {Chip8::OpCode::SHIFT_VX_LEFT, [this] () { shiftVxLeft(); }}, {Chip8::OpCode::VX_PLUS_VY, [this] () { addVyToVx(); }}, {Chip8::OpCode::VX_MINUS_VY, [this] () { subVyFromVx(); }}, {Chip8::OpCode::SET_VX_TO_VY_MINUS_VX, [this] () { subVxFromVy(); }}, {Chip8::OpCode::JUMP_NNN_PLUS_V0, [this] () { jumpToNnnPlusV0(); }}, {Chip8::OpCode::LOAD_DELAY_TIMER_TO_VX, [this] () { loadDelayToVx(); }}, {Chip8::OpCode::LOAD_VX_TO_DELAY_TIMER, [this] () { loadVxToDelay(); }}, {Chip8::OpCode::LOAD_VX_TO_SOUND_TIMER, [this] () { loadVxToSound(); }}, {Chip8::OpCode::LOAD_NNN_TO_I, [this] () { loadNnnToI(); }}, {Chip8::OpCode::LOAD_V0_TO_VX_IN_ADDRESS_I, [this] () { loadRegistersToI(); }}, {Chip8::OpCode::LOAD_ADDRESS_I_TO_V0_TO_VX, [this] () { loadItoRegisters(); }}, {Chip8::OpCode::ADD_VX_TO_I, [this] () { addVxToI(); }}, {Chip8::OpCode::LOAD_FONT_SPRITE_ADDRESS_TO_I, [this] () { loadFontSpriteAddressToI(); }}, {Chip8::OpCode::DRAW, [this]() { draw(); }}, {Chip8::OpCode::SKIP_IF_VX_IS_PRESSED, [this] () { executeSkipIfVxIsPressed(); }}, {Chip8::OpCode::SKIP_IF_VX_IS_NOT_PRESSED, [this] () { executeSkipIfVxIsNotPressed(); }}, {Chip8::OpCode::LOAD_PRESSED_KEY_TO_VX, [this] () { executeWaitPressedKeyToVx(); }}, {Chip8::OpCode::LOAD_VX_BCD_TO_I, [this] () { executeLoadVxBcdToI(); }}, {Chip8::OpCode::LOAD_RANDOM_TO_VX, [this] () { executeLoadRandomToVx(); }} } { m_registers.fill(0x0); m_mmu.load(Chip8::FONT_SET, 0x0); } Chip8::BYTE CPU::readRegister(const Chip8::Register id) const { return m_registers.at(static_cast<std::size_t>(id)); } void CPU::writeRegister(const Chip8::Register id, const Chip8::BYTE value) { m_registers.at(static_cast<std::size_t>(id)) = value; } void CPU::loadToRegisters(const std::vector<Chip8::BYTE> values) { const auto size = std::min(values.size(), m_registers.size()); std::copy_n(std::begin(values), size, std::begin(m_registers)); } void CPU::cycle() { fetch(); decode(); execute(); updateDelayTimer(); updateSoundTimer(); } void CPU::execute(const Chip8::WORD instr) { m_instruction = instr; decode(); execute(); } void CPU::fetch() { m_instruction = m_mmu.readWord(m_pc); m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } void CPU::decode() { m_opcode = OpDecoder::decode(m_instruction); } void CPU::execute() { m_dispatchTable.at(m_opcode)(); } void CPU::updateDelayTimer() { if (m_delayTimer > 0) { --m_delayTimer; } } void CPU::updateSoundTimer() { if (m_soundTimer > 0) { --m_soundTimer; } } void CPU::clearDisplay() { m_frameBuffer.fill(0x0); m_ioDevice.drawScreen(m_frameBuffer); } void CPU::jumpToNnn() { m_pc = WordDecoder::readNNN(m_instruction); } void CPU::returnFromSubroutine() { m_pc = m_stack.at(--m_sp); } void CPU::callNNN() { m_stack.at(m_sp++) = m_pc; m_pc = WordDecoder::readNNN(m_instruction); } void CPU::skipIfVxEqualsNn() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); if (m_registers.at(x) == nn) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxNotEqualsNn() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); if (m_registers.at(x) != nn) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxEqualsVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); if (m_registers.at(x) == m_registers.at(y)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::skipIfVxNotEqualsVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); if (m_registers.at(x) != m_registers.at(y)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::loadNnToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); m_registers.at(x) = nn; } void CPU::addNnToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); m_registers.at(x) += nn; } void CPU::loadVyToVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) = m_registers.at(y); } void CPU::bitwiseVxOrVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) |= m_registers.at(y); } void CPU::bitwiseVxAndVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) &= m_registers.at(y); } void CPU::bitwiseVxXorVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); m_registers.at(x) ^= m_registers.at(y); } void CPU::shiftVxRight() { const auto x = WordDecoder::readX(m_instruction); const auto mask = static_cast<Chip8::BYTE>(0x1); auto& vx = m_registers.at(x); writeRegister(Chip8::Register::VF, vx & mask); vx >>= 1; } void CPU::shiftVxLeft() { const auto x = WordDecoder::readX(m_instruction); auto& vx = m_registers.at(x); writeRegister(Chip8::Register::VF, vx >> 7); vx <<= 1; } void CPU::addVyToVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasCarry = vy > (0xFF - vx); writeRegister(Chip8::Register::VF, hasCarry ? 0x1 : 0x0); vx += vy; } void CPU::subVyFromVx() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasBorrow = vy > vx; writeRegister(Chip8::Register::VF, hasBorrow ? 0x0 : 0x1); vx -= vy; } void CPU::subVxFromVy() { const auto x = WordDecoder::readX(m_instruction); const auto y = WordDecoder::readY(m_instruction); auto& vx = m_registers.at(x); const auto& vy = m_registers.at(y); const auto hasBorrow = vx > vy; writeRegister(Chip8::Register::VF, hasBorrow ? 0x0 : 0x1); vx = vy - vx; } void CPU::jumpToNnnPlusV0() { m_pc = WordDecoder::readNNN(m_instruction) + m_registers.at(0x0); } void CPU::loadDelayToVx() { const auto x = WordDecoder::readX(m_instruction); m_registers.at(x) = m_delayTimer; } void CPU::loadVxToDelay() { const auto x = WordDecoder::readX(m_instruction); m_delayTimer = m_registers.at(x); } void CPU::loadVxToSound() { const auto x = WordDecoder::readX(m_instruction); m_soundTimer = m_registers.at(x); } void CPU::loadNnnToI() { m_I = WordDecoder::readNNN(m_instruction); } void CPU::loadRegistersToI() { const auto x = WordDecoder::readX(m_instruction); std::copy_n(std::begin(m_registers), x, std::begin(m_mmu) + m_I); m_I += x + 1; } void CPU::loadItoRegisters() { const auto x = WordDecoder::readX(m_instruction); std::copy_n(std::begin(m_mmu) + m_I, x, std::begin(m_registers)); m_I += x + 1; } void CPU::addVxToI() { const auto x = WordDecoder::readX(m_instruction); m_I += m_registers.at(x); } void CPU::loadFontSpriteAddressToI() { const auto x = WordDecoder::readX(m_instruction); m_I = m_registers.at(x) * Chip8::CHAR_SPRITE_SIZE; } void CPU::draw() { const auto vx = WordDecoder::readX(m_instruction); const auto vy = WordDecoder::readY(m_instruction); const auto x = m_registers.at(vx); const auto y = m_registers.at(vy); const auto height = WordDecoder::readN(m_instruction); Chip8::BYTE flipped{0x0u}; for (auto line = 0u; line < height; ++line) { const auto rowPixels = m_mmu.readByte(m_I + line); for (auto row = 0u; row < Chip8::SPRITE_WIDTH; ++row) { if ((rowPixels & (0x80 >> row)) != 0) { const auto offset = (x + row + ((y + line) * 64)) % 2048; Chip8::BYTE& pixel = m_frameBuffer.at(offset); if (pixel != 0) { flipped = 1u; } pixel ^= 1u; } } } writeRegister(Chip8::Register::VF, flipped); m_ioDevice.drawScreen(m_frameBuffer); } void CPU::executeSkipIfVxIsPressed() { const auto x = WordDecoder::readX(m_instruction); const auto key = static_cast<Chip8::Key>(m_registers.at(x)); if (m_ioDevice.isKeyPressed(key)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeSkipIfVxIsNotPressed() { const auto x = WordDecoder::readX(m_instruction); const auto key = static_cast<Chip8::Key>(m_registers.at(x)); if (!m_ioDevice.isKeyPressed(key)) { m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeWaitPressedKeyToVx() { const auto pressedKey = m_ioDevice.getPressedKey(); if (pressedKey != Chip8::Key::NONE) { const auto x = WordDecoder::readX(m_instruction); m_registers.at(x) = static_cast<Chip8::BYTE>(pressedKey); m_pc += Chip8::INSTRUCTION_BYTE_SIZE; } } void CPU::executeLoadVxBcdToI() { const auto x = WordDecoder::readX(m_instruction); const auto vx = m_registers.at(x); const auto hundreds = vx / 100; const auto tens = (vx / 10) % 10; const auto ones = (vx % 100) % 10; m_mmu.writeByte(hundreds, m_I); m_mmu.writeByte(tens, m_I + 1u); m_mmu.writeByte(ones, m_I + 2u); } void CPU::executeLoadRandomToVx() { const auto x = WordDecoder::readX(m_instruction); const auto nn = WordDecoder::readNN(m_instruction); const auto randomNumber = m_rndGenerator.get(); m_registers.at(x) = nn & randomNumber; } } // namespace Core8<|endoftext|>
<commit_before>#include "Course.h" #include <iomanip> #include <iostream> #include <string> using namespace std; int main() { // main prompt bool isOpen = false; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE Course course; string input; // string openCourse; cout << "Welcome to grade-plus\n"; cout << "What would you like to do?\n"; cout.width(6); cout << "\tWORK on an existing Course [W]\n\tCREATE a new Course [C]\n\t$: "; // input loop while (true) { getline(cin, input); // open Course if (tolower(input[0]) == 'w') { cout << "Which Course: "; getline(cin, input); string name = input; cout << "Opening Course: " << name << "...\n"; course.load(name); isOpen = true; break; } // create Course else if (tolower(input[0]) == 'c') { cout << "Please enter a unique name\n"; cout << "Course Name: "; getline(cin, input); string name = input; cout << "Creating Course: " << name << endl; course.load(name); isOpen = true; break; } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; isOpen = false; break; } // invalid else { cout << "Invalid entry: " << input << endl; cout << "What would you like to do?\n"; continue; } } // opening loop // second loop while the course is open while (isOpen) { // cout << "LIST ALL THE COURSE DETAILS:\n"; cout << "\n"; cout << "Course Name: \t" << course.getName() << "\n"; cout << "\tSELECT students [S]\n\tSELECT assignments " "[A]\n\tSELECT categories [C]\n\tSELECT submissions [U]\n\tQUIT " "[Q]\n\t$: "; getline(cin, input); // students handler if (tolower(input[0]) == 's' || tolower(input[0]) == 'S') { course.printStudents(); cout << "\tADD student [A]\n\tREMOVE student [R]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add student if (tolower(input[0]) == 'a') { cout << "Student ID?: "; getline(cin, input); string id = input; cout << "Student first name?: "; getline(cin, input); string firstName = input; cout << "Student last name?: "; getline(cin, input); string lastName = input; cout << "Student name: " << firstName << " " << lastName << " Student ID: " << id << endl; course.addStudent(id, firstName, lastName); } // modify student else if (tolower(input[0]) == 'a') { cout << "Student ID: "; getline(cin, input); string id = input; cout << "Student first name (or press enter to keep current one): "; getline(cin, input); string firstName = input; cout << "Student last name (or press enter to keep current one): "; getline(cin, input); string lastName = input; cout << "Student name: " << firstName << " " << lastName << " Student ID: " << id << endl; course.updateStudent(id, firstName, lastName); } // drop student else if (tolower(input[0]) == 'r') { cout << "Remove student with ID: "; getline(cin, input); string id = input; // call drop student function on that student course.deleteStudent(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; isOpen = false; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // print students after all student related activities have been done cout << "Here's the current list roster for " << course.getName() << ":\n"; course.printStudents(); } // ASSIGNMENTS HANDLER else if (tolower(input[0]) == 'a') { cout << "Here's a current list of all the assignments in " << course.getName() << ":\n"; cout << "\t"; course.printAssignments(); cout << endl; cout.width(6); cout << "\tADD assignment [A]\n\tREMOVE assignment [R]\n\tMODIFY " "assignment [M]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add assignment if (tolower(input[0]) == 'a') { cout << "Adding a new assignment:\n"; cout << "Assignment name: "; getline(cin, input); string name = input; course.printCategories(); cout << "Category ID: "; getline(cin, input); int category = stoi(input); cout << "Points possible: "; getline(cin, input); int weight = stoi(input); course.addAssignment(category, name, weight); } // modify assignment else if (tolower(input[0]) == 'm') { cout << "Modify assignment with ID: "; getline(cin, input); int id = stoi(input); cout << "Assignment name (or press enter to keep current one): "; getline(cin, input); string name = input; course.printCategories(); cout << "Category ID (or press enter to keep current one): "; getline(cin, input); int category = atoi(input.c_str()); cout << "Points possible (or press enter to keep current one): "; getline(cin, input); int weight = atoi(input.c_str()); course.updateAssignment(id, category, name, weight); } // remove assignment else if (tolower(input[0]) == 'r') { cout << "Remove assignment with ID: "; getline(cin, input); int id = stoi(input); // cout << "Calling course.deleteAssignment(" << id << ")\n"; course.deleteAssignment(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // invalid else { cout << "Invalid entry: " << input << endl; continue; } cout << "Here's a current list of all the assignments in " << course.getName() << ":\n"; course.printAssignments(); } // CATEGORIES HANDLER else if (tolower(input[0]) == 'c') { course.printCategories(); cout.width(6); cout << "\tADD category [A]\n\tREMOVE category [R]\n\tMODIFY category " "[M]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add category if (tolower(input[0]) == 'a') { cout << "Adding a new category:\n"; cout << "Category name: "; getline(cin, input); string name = input; cout << "Weight: "; getline(cin, input); int weight = stoi(input); course.addCategory(name, weight); } // modify category else if (tolower(input[0]) == 'm') { cout << "Modify category with ID: "; getline(cin, input); int id = stoi(input); cout << "Category name (or press enter to keep current one): "; getline(cin, input); string name = input; cout << "Weight (or press enter to keep current one): "; getline(cin, input); int weight = atoi(input.c_str()); course.updateCategory(id, name, weight); } // remove category else if (tolower(input[0]) == 'r') { cout << "Remove category with ID: "; getline(cin, input); int id = stoi(input); course.deleteCategory(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // invalid else { cout << "Invalid entry: " << input << endl; continue; } } // SUBMITTED HANDLER else if (tolower(input[0]) == 'u') { course.printSubmitted(); cout.width(6); do { cout << "\tFILTER by student [S]\n\tFILTER by assignment [T]\n\tADD " "submission [A]\n\tREMOVE submission [R]\n\tMODIFY submission " "[M]\n\tGRADE submission [G]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // filter by student if (tolower(input[0]) == 's') { cout << "Student ID: "; getline(cin, input); string studentId = input; course.printSubmittedOfStudent(studentId); } // filter by assignment else if (tolower(input[0]) == 't') { cout << "Assignment ID: "; getline(cin, input); int assignmentId = stoi(input); course.printSubmittedOfAssignment(assignmentId); } } while (tolower(input[0]) == 's' || tolower(input[0]) == 't'); // add submitted if (tolower(input[0]) == 'a') { cout << "Adding a new submission:\n"; cout << "Assignment ID: "; getline(cin, input); int assignmentId = stoi(input); // stoi not working with addSubmitted cout << "Student ID: "; getline(cin, input); string studentId = input; course.addSubmitted(assignmentId, studentId, NULL); } // modify submitted else if (tolower(input[0]) == 'm') { cout << "Modify submission with ID: "; getline(cin, input); int id = stoi(input); cout << "Assignment ID (or press enter to keep current one): "; getline(cin, input); int assignmentId = stoi(input); cout << "Student ID (or press enter to keep current one): "; getline(cin, input); string studentId = input; course.updateSubmitted(id, assignmentId, studentId, NULL); } // remove submitted else if (tolower(input[0]) == 'r') { cout << "Remove submission with ID: "; getline(cin, input); int id = stoi(input); course.deleteSubmitted(id); } // grade submitted else if (tolower(input[0]) == 'g') { cout << "Grade submission with ID: "; getline(cin, input); int id = stoi(input); cout << "Points earned: "; getline(cin, input); double pointsEarned = stod(input); course.updateSubmitted(id, -1, "", pointsEarned); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE } // invalid else { cout << "Invalid entry: " << input << endl; continue; } } // else invalid else { cout << "Invalid entry: " << input << endl; continue; } } // while course is open } <commit_msg>Add ASCII art logo<commit_after>#include "Course.h" #include <iomanip> #include <iostream> #include <string> using namespace std; int main() { // main prompt bool isOpen = false; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE Course course; string input; // string openCourse; cout << " _____ __ ___ __ \n"; cout << " / ___/______ ____/ /__ ____/ _ \\/ /_ _____\n"; cout << "/ (_ / __/ _ `/ _ / -_)___/ ___/ / // (_-<\n"; cout << "\\___/_/ \\_,_/\\_,_/\\__/ /_/ /_/\\_,_/___/\n\n"; cout << "What would you like to do?\n"; cout.width(6); cout << "\tWORK on an existing Course [W]\n\tCREATE a new Course [C]\n\t$: "; // input loop while (true) { getline(cin, input); // open Course if (tolower(input[0]) == 'w') { cout << "Which Course: "; getline(cin, input); string name = input; cout << "Opening Course: " << name << "...\n"; course.load(name); isOpen = true; break; } // create Course else if (tolower(input[0]) == 'c') { cout << "Please enter a unique name\n"; cout << "Course Name: "; getline(cin, input); string name = input; cout << "Creating Course: " << name << endl; course.load(name); isOpen = true; break; } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; isOpen = false; break; } // invalid else { cout << "Invalid entry: " << input << endl; cout << "What would you like to do?\n"; continue; } } // opening loop // second loop while the course is open while (isOpen) { // cout << "LIST ALL THE COURSE DETAILS:\n"; cout << "\n"; cout << "Course Name: \t" << course.getName() << "\n"; cout << "\tSELECT students [S]\n\tSELECT assignments " "[A]\n\tSELECT categories [C]\n\tSELECT submissions [U]\n\tQUIT " "[Q]\n\t$: "; getline(cin, input); // students handler if (tolower(input[0]) == 's' || tolower(input[0]) == 'S') { course.printStudents(); cout << "\tADD student [A]\n\tREMOVE student [R]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add student if (tolower(input[0]) == 'a') { cout << "Student ID?: "; getline(cin, input); string id = input; cout << "Student first name?: "; getline(cin, input); string firstName = input; cout << "Student last name?: "; getline(cin, input); string lastName = input; cout << "Student name: " << firstName << " " << lastName << " Student ID: " << id << endl; course.addStudent(id, firstName, lastName); } // modify student else if (tolower(input[0]) == 'a') { cout << "Student ID: "; getline(cin, input); string id = input; cout << "Student first name (or press enter to keep current one): "; getline(cin, input); string firstName = input; cout << "Student last name (or press enter to keep current one): "; getline(cin, input); string lastName = input; cout << "Student name: " << firstName << " " << lastName << " Student ID: " << id << endl; course.updateStudent(id, firstName, lastName); } // drop student else if (tolower(input[0]) == 'r') { cout << "Remove student with ID: "; getline(cin, input); string id = input; // call drop student function on that student course.deleteStudent(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; isOpen = false; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // print students after all student related activities have been done cout << "Here's the current list roster for " << course.getName() << ":\n"; course.printStudents(); } // ASSIGNMENTS HANDLER else if (tolower(input[0]) == 'a') { cout << "Here's a current list of all the assignments in " << course.getName() << ":\n"; cout << "\t"; course.printAssignments(); cout << endl; cout.width(6); cout << "\tADD assignment [A]\n\tREMOVE assignment [R]\n\tMODIFY " "assignment [M]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add assignment if (tolower(input[0]) == 'a') { cout << "Adding a new assignment:\n"; cout << "Assignment name: "; getline(cin, input); string name = input; course.printCategories(); cout << "Category ID: "; getline(cin, input); int category = stoi(input); cout << "Points possible: "; getline(cin, input); int weight = stoi(input); course.addAssignment(category, name, weight); } // modify assignment else if (tolower(input[0]) == 'm') { cout << "Modify assignment with ID: "; getline(cin, input); int id = stoi(input); cout << "Assignment name (or press enter to keep current one): "; getline(cin, input); string name = input; course.printCategories(); cout << "Category ID (or press enter to keep current one): "; getline(cin, input); int category = atoi(input.c_str()); cout << "Points possible (or press enter to keep current one): "; getline(cin, input); int weight = atoi(input.c_str()); course.updateAssignment(id, category, name, weight); } // remove assignment else if (tolower(input[0]) == 'r') { cout << "Remove assignment with ID: "; getline(cin, input); int id = stoi(input); // cout << "Calling course.deleteAssignment(" << id << ")\n"; course.deleteAssignment(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // invalid else { cout << "Invalid entry: " << input << endl; continue; } cout << "Here's a current list of all the assignments in " << course.getName() << ":\n"; course.printAssignments(); } // CATEGORIES HANDLER else if (tolower(input[0]) == 'c') { course.printCategories(); cout.width(6); cout << "\tADD category [A]\n\tREMOVE category [R]\n\tMODIFY category " "[M]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // add category if (tolower(input[0]) == 'a') { cout << "Adding a new category:\n"; cout << "Category name: "; getline(cin, input); string name = input; cout << "Weight: "; getline(cin, input); int weight = stoi(input); course.addCategory(name, weight); } // modify category else if (tolower(input[0]) == 'm') { cout << "Modify category with ID: "; getline(cin, input); int id = stoi(input); cout << "Category name (or press enter to keep current one): "; getline(cin, input); string name = input; cout << "Weight (or press enter to keep current one): "; getline(cin, input); int weight = atoi(input.c_str()); course.updateCategory(id, name, weight); } // remove category else if (tolower(input[0]) == 'r') { cout << "Remove category with ID: "; getline(cin, input); int id = stoi(input); course.deleteCategory(id); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE break; } // invalid else { cout << "Invalid entry: " << input << endl; continue; } } // SUBMITTED HANDLER else if (tolower(input[0]) == 'u') { course.printSubmitted(); cout.width(6); do { cout << "\tFILTER by student [S]\n\tFILTER by assignment [T]\n\tADD " "submission [A]\n\tREMOVE submission [R]\n\tMODIFY submission " "[M]\n\tGRADE submission [G]\n\tQUIT [Q]\n\t$: "; getline(cin, input); // filter by student if (tolower(input[0]) == 's') { cout << "Student ID: "; getline(cin, input); string studentId = input; course.printSubmittedOfStudent(studentId); } // filter by assignment else if (tolower(input[0]) == 't') { cout << "Assignment ID: "; getline(cin, input); int assignmentId = stoi(input); course.printSubmittedOfAssignment(assignmentId); } } while (tolower(input[0]) == 's' || tolower(input[0]) == 't'); // add submitted if (tolower(input[0]) == 'a') { cout << "Adding a new submission:\n"; cout << "Assignment ID: "; getline(cin, input); int assignmentId = stoi(input); // stoi not working with addSubmitted cout << "Student ID: "; getline(cin, input); string studentId = input; course.addSubmitted(assignmentId, studentId, NULL); } // modify submitted else if (tolower(input[0]) == 'm') { cout << "Modify submission with ID: "; getline(cin, input); int id = stoi(input); cout << "Assignment ID (or press enter to keep current one): "; getline(cin, input); int assignmentId = stoi(input); cout << "Student ID (or press enter to keep current one): "; getline(cin, input); string studentId = input; course.updateSubmitted(id, assignmentId, studentId, NULL); } // remove submitted else if (tolower(input[0]) == 'r') { cout << "Remove submission with ID: "; getline(cin, input); int id = stoi(input); course.deleteSubmitted(id); } // grade submitted else if (tolower(input[0]) == 'g') { cout << "Grade submission with ID: "; getline(cin, input); int id = stoi(input); cout << "Points earned: "; getline(cin, input); double pointsEarned = stod(input); course.updateSubmitted(id, -1, "", pointsEarned); } // quit else if (tolower(input[0]) == 'q') { cout << "Goodbye\n"; !isOpen; // MUST REPLACE WITH MEMBER FUNCTION FOR COURSE } // invalid else { cout << "Invalid entry: " << input << endl; continue; } } // else invalid else { cout << "Invalid entry: " << input << endl; continue; } } // while course is open } <|endoftext|>
<commit_before>#include <cerrno> #include <cstring> #include <iostream> #include <sstream> #include "test_helpers.hxx" using namespace pqxx; // Simple test program for libpqxx's Large Objects interface. namespace { const std::string Contents = "Large object test contents"; void test_050() { connection conn; // Create a large object. largeobject Obj = perform( [&conn]() { work tx{conn}; const auto obj = largeobject(tx); tx.commit(); return obj; }); // Write to the large object, and play with it a little. perform( [&conn, &Obj]() { work tx{conn}; largeobjectaccess A(tx, Obj); const auto orgpos = A.ctell(), copyorgpos = A.ctell(); PQXX_CHECK_EQUAL(orgpos, 0, "Bad initial position in large object."); PQXX_CHECK_EQUAL(copyorgpos, orgpos, "ctell() affected positioning."); const largeobjectaccess::pos_type cxxorgpos = A.tell(); PQXX_CHECK_EQUAL(cxxorgpos, orgpos, "tell() reports bad position."); A.process_notice("Writing to large object #" + to_string(largeobject(A).id()) + "\n"); long Bytes = A.cwrite( Contents.c_str(), static_cast<int>(Contents.size())); PQXX_CHECK_EQUAL( Bytes, long(Contents.size()), "Wrote wrong number of bytes."); PQXX_CHECK_EQUAL( A.tell(), A.ctell(), "tell() is inconsistent with ctell()."); PQXX_CHECK_EQUAL(A.tell(), Bytes, "Bad large-object position."); char Buf[200]; const size_t Size = sizeof(Buf) - 1; PQXX_CHECK_EQUAL( A.cread(Buf, Size), 0, "Bad return value from cread() after writing."); PQXX_CHECK_EQUAL( size_t(A.cseek(0, std::ios::cur)), Contents.size(), "Unexpected position after cseek(0, cur)."); PQXX_CHECK_EQUAL( A.cseek(1, std::ios::beg), 1, "Unexpected cseek() result after seeking to position 1."); PQXX_CHECK_EQUAL( A.cseek(-1, std::ios::cur), 0, "Unexpected cseek() result after seeking -1 from position 1."); PQXX_CHECK(size_t(A.read(Buf, Size)) <= Size, "Got too many bytes."); PQXX_CHECK_EQUAL( std::string(Buf, std::string::size_type(Bytes)), Contents, "Large-object contents were mutilated."); tx.commit(); }); perform( [&conn, &Obj]() { work tx{conn}; Obj.remove(tx); tx.commit(); }); } PQXX_REGISTER_TEST(test_050); } // namespace <commit_msg>Fix another cast warning.<commit_after>#include <cerrno> #include <cstring> #include <iostream> #include <sstream> #include "test_helpers.hxx" using namespace pqxx; // Simple test program for libpqxx's Large Objects interface. namespace { const std::string Contents = "Large object test contents"; void test_050() { connection conn; // Create a large object. largeobject Obj = perform( [&conn]() { work tx{conn}; const auto obj = largeobject(tx); tx.commit(); return obj; }); // Write to the large object, and play with it a little. perform( [&conn, &Obj]() { work tx{conn}; largeobjectaccess A(tx, Obj); const auto orgpos = A.ctell(), copyorgpos = A.ctell(); PQXX_CHECK_EQUAL(orgpos, 0, "Bad initial position in large object."); PQXX_CHECK_EQUAL(copyorgpos, orgpos, "ctell() affected positioning."); const largeobjectaccess::pos_type cxxorgpos = A.tell(); PQXX_CHECK_EQUAL(cxxorgpos, orgpos, "tell() reports bad position."); A.process_notice("Writing to large object #" + to_string(largeobject(A).id()) + "\n"); int Bytes = check_cast<int>( A.cwrite(Contents.c_str(), static_cast<int>(Contents.size())), "test write"); PQXX_CHECK_EQUAL( Bytes, check_cast<int>(Contents.size(), "test cwrite()"), "Wrote wrong number of bytes."); PQXX_CHECK_EQUAL( A.tell(), A.ctell(), "tell() is inconsistent with ctell()."); PQXX_CHECK_EQUAL(A.tell(), Bytes, "Bad large-object position."); char Buf[200]; const size_t Size = sizeof(Buf) - 1; PQXX_CHECK_EQUAL( A.cread(Buf, Size), 0, "Bad return value from cread() after writing."); PQXX_CHECK_EQUAL( size_t(A.cseek(0, std::ios::cur)), Contents.size(), "Unexpected position after cseek(0, cur)."); PQXX_CHECK_EQUAL( A.cseek(1, std::ios::beg), 1, "Unexpected cseek() result after seeking to position 1."); PQXX_CHECK_EQUAL( A.cseek(-1, std::ios::cur), 0, "Unexpected cseek() result after seeking -1 from position 1."); PQXX_CHECK(size_t(A.read(Buf, Size)) <= Size, "Got too many bytes."); PQXX_CHECK_EQUAL( std::string(Buf, std::string::size_type(Bytes)), Contents, "Large-object contents were mutilated."); tx.commit(); }); perform( [&conn, &Obj]() { work tx{conn}; Obj.remove(tx); tx.commit(); }); } PQXX_REGISTER_TEST(test_050); } // namespace <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } else { //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <commit_msg>Honor STOP Gated bit when checking access states<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_query_cache_access_state.C /// @brief Check the stop level for the EX caches and sets boolean scomable parameters /// // *HWP HWP Owner: Christina Graves <[email protected]> // *HWP Backup HWP Owner: Greg Still <[email protected]> // *HWP FW Owner: Sangeetha T S <[email protected]> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS:SBE /// /// /// /// @verbatim /// High-level procedure flow: /// - For the quad target, read the Stop State History register in the PPM /// and use the actual stop level to determine if the quad has power and is being /// clocked. /// @endverbatim /// //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_scom_addresses.H> #include <p9_query_cache_access_state.H> // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t eq_clk_l2_pos[] = {8, 9}; const uint32_t eq_clk_l3_pos[] = {6, 7}; const uint32_t SSH_REG_STOP_LEVEL = 8; const uint32_t SSH_REG_STOP_LEVEL_LEN = 4; const uint32_t SSH_REG_STOP_GATED = 0; // ---------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------- fapi2::ReturnCode p9_query_cache_access_state( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, bool& o_l2_is_scomable, bool& o_l2_is_scannable, bool& o_l3_is_scomable, bool& o_l3_is_scannable) { fapi2::buffer<uint64_t> l_qsshsrc; uint32_t l_quadStopLevel = 0; fapi2::buffer<uint64_t> l_data64; bool l_is_scomable = 1; uint8_t l_chpltNumber = 0; uint32_t l_exPos = 0; uint8_t l_execution_platform = 0; uint32_t l_stop_state_reg = 0; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; FAPI_INF("> p9_query_cache_access_state..."); //Get the stop state from the SSHRC in the EQPPM //First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform) FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform), "Error: Failed to get platform"); if (l_execution_platform == 0x02) { l_stop_state_reg = EQ_PPM_SSHFSP; } else { l_stop_state_reg = EQ_PPM_SSHHYP; } FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), "Error reading data from QPPM SSHSRC"); //A unit is scommable if clocks are running //A unit is scannable if the unit is powered up //Extract the core stop state l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN); FAPI_DBG("EQ Stop State: EQ(%d)", l_quadStopLevel); //Set all attribtes to 1, then clear them based on the stop state o_l2_is_scomable = 1; o_l2_is_scannable = 1; o_l3_is_scomable = 1; o_l3_is_scannable = 1; //Looking at the stop states is only valid if quad is stop gated -- else it is fully running if (l_qsshsrc.getBit(SSH_REG_STOP_GATED)) { // STOP8 - Half Quad Deep Sleep // VSU, ISU are powered off // IFU, LSU are powered off // PC, Core EPS are powered off // L20-EX0 is clocked off if both cores are >= 8 // L20-EX1 is clocked off if both cores are >= 8 if (l_quadStopLevel >= 8) { o_l2_is_scomable = 0; } // STOP9 - Fast Winkle (lab use only) // Both cores and cache are clocked off if (l_quadStopLevel >= 9) { o_l3_is_scomable = 0; } // STOP11 - Deep Winkle // Both cores and cache are powered off if (l_quadStopLevel >= 11) { o_l2_is_scannable = 0; o_l3_is_scannable = 0; } else { //Read clock status to confirm stop state history is accurate //If we trust the stop state history, this could be removed to save on code size //Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), "Error reading data from EQ_CLOCK_STAT_SL"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber), "Error: Failed to get the position of the EX:0x%08X", i_target); l_exPos = l_chpltNumber % 2; l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]); if (o_l2_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l2_is_scomable = l_is_scomable; } l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]); if (o_l3_is_scomable != l_is_scomable) { FAPI_INF("Clock status didn't match stop state, overriding is_scomable status"); o_l3_is_scomable = l_is_scomable; } } } fapi_try_exit: FAPI_INF("< p9_query_cache_access_state..."); return fapi2::current_err; } <|endoftext|>
<commit_before>/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- Copyright (c) 2010-2012 Marcus Geelnard This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iostream> #include <list> #include <tinythread_t.h> #include <fast_mutex.h> using namespace std; using namespace tthread; // HACK: Mac OS X and early MinGW do not support thread-local storage #if defined(__APPLE__) || (defined(__MINGW32__) && (__GNUC__ < 4)) #define NO_TLS #endif // Thread local storage variable #ifndef NO_TLS thread_local int gLocalVar; #endif // Mutex + global count variable mutex gMutex; fast_mutex gFastMutex; atomic_flag gFlag(ATOMIC_FLAG_INIT); int gCount; atomic_int gAtomicCount; // Condition variable condition_variable gCond; // Thread function: Thread ID thread::id ThreadIDs(void * aArg) { cout << " My thread id is " << this_thread::get_id() << "." << endl; return this_thread::get_id(); } #ifndef NO_TLS // Thread function: Thread-local storage int ThreadTLS(void * aArg) { gLocalVar = 2; cout << " My gLocalVar is " << gLocalVar << "." << endl; return gLocalVar; } #endif // Thread function: Mutex locking int ThreadLock(void * aArg) { for(int i = 0; i < 10000; ++ i) { lock_guard<mutex> lock(gMutex); ++ gCount; } return gCount; } // Thread function: Fast mutex locking int ThreadLock2(void * aArg) { for(int i = 0; i < 10000; ++ i) { lock_guard<fast_mutex> lock(gFastMutex); ++ gCount; } return gCount; } // Thread function: Spin-lock locking int ThreadSpinLock(void * aArg) { for(int i = 0; i < 10000; ++ i) { // CPU-friendly spin-lock while (gFlag.test_and_set()) this_thread::yield(); ++ gCount; // Release lock gFlag.clear(); } return gCount; } // Thread function: Atomic count tthread::atomic_int ThreadAtomicCount(void * aArg) { for(int i = 0; i < 10000; ++ i) { ++ gAtomicCount; } return gAtomicCount; } // Thread function: Condition notifier bool ThreadCondition1(void * aArg) { lock_guard<mutex> lock(gMutex); -- gCount; gCond.notify_all(); return true; } // Thread function: Condition waiter bool ThreadCondition2(void * aArg) { cout << " Wating..." << flush; lock_guard<mutex> lock(gMutex); while(gCount > 0) { cout << "." << flush; gCond.wait(gMutex); } cout << "." << endl; return true; } // Thread function: Yield bool ThreadYield(void * aArg) { // Yield... this_thread::yield(); return true; } // Thread function: Detach bool ThreadDetach(void * aArg) { // We don't do anything much, just sleep a little... this_thread::sleep_for(chrono::milliseconds(100)); cout << " Detached thread finished." << endl; return true; } // This is the main program (i.e. the main thread) int main() { // Test 1: Show number of CPU cores in the system cout << "PART I: Info" << endl; cout << " Number of processor cores: " << thread::hardware_concurrency() << endl; // Test 2: thread IDs cout << endl << "PART II: Thread IDs" << endl; { // Show the main thread ID cout << " Main thread id is " << this_thread::get_id() << "." << endl; // Start a bunch of child threads - only run a single thread at a time threadt t1(ThreadIDs, 0); t1.join(); threadt t2(ThreadIDs, 0); t2.join(); threadt t3(ThreadIDs, 0); t3.join(); threadt t4(ThreadIDs, 0); t4.join(); } // Test 3: thread local storage cout << endl << "PART III: Thread local storage" << endl; #ifndef NO_TLS { // Clear the TLS variable (it should keep this value after all threads are // finished). gLocalVar = 1; cout << " Main gLocalVar is " << gLocalVar << "." << endl; // Start a child thread that modifies gLocalVar threadt t1(ThreadTLS, 0); t1.join(); // Check if the TLS variable has changed if(gLocalVar == 1) cout << " Main gLocalID was not changed by the child thread - OK!" << endl; else cout << " Main gLocalID was changed by the child thread - FAIL!" << endl; } #else cout << " TLS is not supported on this platform..." << endl; #endif // Test 4: mutex locking cout << endl << "PART IV: Mutex locking (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadLock, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 5: fast_mutex locking cout << endl << "PART V: Fast mutex locking (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadLock2, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 6: Atomic lock cout << endl << "PART VI: Atomic spin-lock (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadSpinLock, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 7: Atomic variable cout << endl << "PART VII: Atomic variable (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gAtomicCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadAtomicCount, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gAtomicCount = " << gAtomicCount << endl; } // Test 8: condition variable cout << endl << "PART VIII: Condition variable (40 + 1 threads)" << endl; { // Set the global counter to the number of threads to run. gCount = 40; // Start the waiting thread (it will wait for gCount to reach zero). threadt t1(ThreadCondition2, 0); // Start a bunch of child threads (these will decrease gCount by 1 when they // finish) list<thread *> threadList; for(int i = 0; i < 40; ++ i) threadList.push_back(new threadt(ThreadCondition1, 0)); // Wait for the waiting thread to finish t1.join(); // Wait for the other threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } } // Test 9: yield cout << endl << "PART IX: Yield (40 + 1 threads)" << endl; { // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 40; ++ i) threadList.push_back(new threadt(ThreadYield, 0)); // Yield... this_thread::yield(); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } } // Test 10: sleep cout << endl << "PART X: Sleep (10 x 100 ms)" << endl; { // Sleep... cout << " Sleeping" << flush; for(int i = 0; i < 10; ++ i) { this_thread::sleep_for(chrono::milliseconds(100)); cout << "." << flush; } cout << endl; } // Test 11: detach cout << endl << "PART XI: Detach" << endl; { threadt t(ThreadDetach, 0); t.detach(); cout << " Detached from thread." << endl; // Give the thread a chanse to finish too... this_thread::sleep_for(chrono::milliseconds(400)); } cout << endl << "Tests done!" << endl; } <commit_msg>fixing return of atomic int because of forbidden copy constructor<commit_after>/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- Copyright (c) 2010-2012 Marcus Geelnard This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iostream> #include <list> #include <tinythread_t.h> #include <fast_mutex.h> using namespace std; using namespace tthread; // HACK: Mac OS X and early MinGW do not support thread-local storage #if defined(__APPLE__) || (defined(__MINGW32__) && (__GNUC__ < 4)) #define NO_TLS #endif // Thread local storage variable #ifndef NO_TLS thread_local int gLocalVar; #endif // Mutex + global count variable mutex gMutex; fast_mutex gFastMutex; atomic_flag gFlag(ATOMIC_FLAG_INIT); int gCount; atomic_int gAtomicCount; // Condition variable condition_variable gCond; // Thread function: Thread ID thread::id ThreadIDs(void * aArg) { cout << " My thread id is " << this_thread::get_id() << "." << endl; return this_thread::get_id(); } #ifndef NO_TLS // Thread function: Thread-local storage int ThreadTLS(void * aArg) { gLocalVar = 2; cout << " My gLocalVar is " << gLocalVar << "." << endl; return gLocalVar; } #endif // Thread function: Mutex locking int ThreadLock(void * aArg) { for(int i = 0; i < 10000; ++ i) { lock_guard<mutex> lock(gMutex); ++ gCount; } return gCount; } // Thread function: Fast mutex locking int ThreadLock2(void * aArg) { for(int i = 0; i < 10000; ++ i) { lock_guard<fast_mutex> lock(gFastMutex); ++ gCount; } return gCount; } // Thread function: Spin-lock locking int ThreadSpinLock(void * aArg) { for(int i = 0; i < 10000; ++ i) { // CPU-friendly spin-lock while (gFlag.test_and_set()) this_thread::yield(); ++ gCount; // Release lock gFlag.clear(); } return gCount; } // Thread function: Atomic count int ThreadAtomicCount(void * aArg) { for(int i = 0; i < 10000; ++ i) { ++ gAtomicCount; } return gAtomicCount; } // Thread function: Condition notifier bool ThreadCondition1(void * aArg) { lock_guard<mutex> lock(gMutex); -- gCount; gCond.notify_all(); return true; } // Thread function: Condition waiter bool ThreadCondition2(void * aArg) { cout << " Wating..." << flush; lock_guard<mutex> lock(gMutex); while(gCount > 0) { cout << "." << flush; gCond.wait(gMutex); } cout << "." << endl; return true; } // Thread function: Yield bool ThreadYield(void * aArg) { // Yield... this_thread::yield(); return true; } // Thread function: Detach bool ThreadDetach(void * aArg) { // We don't do anything much, just sleep a little... this_thread::sleep_for(chrono::milliseconds(100)); cout << " Detached thread finished." << endl; return true; } // This is the main program (i.e. the main thread) int main() { // Test 1: Show number of CPU cores in the system cout << "PART I: Info" << endl; cout << " Number of processor cores: " << thread::hardware_concurrency() << endl; // Test 2: thread IDs cout << endl << "PART II: Thread IDs" << endl; { // Show the main thread ID cout << " Main thread id is " << this_thread::get_id() << "." << endl; // Start a bunch of child threads - only run a single thread at a time threadt t1(ThreadIDs, 0); t1.join(); threadt t2(ThreadIDs, 0); t2.join(); threadt t3(ThreadIDs, 0); t3.join(); threadt t4(ThreadIDs, 0); t4.join(); } // Test 3: thread local storage cout << endl << "PART III: Thread local storage" << endl; #ifndef NO_TLS { // Clear the TLS variable (it should keep this value after all threads are // finished). gLocalVar = 1; cout << " Main gLocalVar is " << gLocalVar << "." << endl; // Start a child thread that modifies gLocalVar threadt t1(ThreadTLS, 0); t1.join(); // Check if the TLS variable has changed if(gLocalVar == 1) cout << " Main gLocalID was not changed by the child thread - OK!" << endl; else cout << " Main gLocalID was changed by the child thread - FAIL!" << endl; } #else cout << " TLS is not supported on this platform..." << endl; #endif // Test 4: mutex locking cout << endl << "PART IV: Mutex locking (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadLock, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 5: fast_mutex locking cout << endl << "PART V: Fast mutex locking (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadLock2, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 6: Atomic lock cout << endl << "PART VI: Atomic spin-lock (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadSpinLock, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gCount = " << gCount << endl; } // Test 7: Atomic variable cout << endl << "PART VII: Atomic variable (100 threads x 10000 iterations)" << endl; { // Clear the global counter. gAtomicCount = 0; // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 100; ++ i) threadList.push_back(new threadt(ThreadAtomicCount, 0)); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } // Check the global count cout << " gAtomicCount = " << gAtomicCount << endl; } // Test 8: condition variable cout << endl << "PART VIII: Condition variable (40 + 1 threads)" << endl; { // Set the global counter to the number of threads to run. gCount = 40; // Start the waiting thread (it will wait for gCount to reach zero). threadt t1(ThreadCondition2, 0); // Start a bunch of child threads (these will decrease gCount by 1 when they // finish) list<thread *> threadList; for(int i = 0; i < 40; ++ i) threadList.push_back(new threadt(ThreadCondition1, 0)); // Wait for the waiting thread to finish t1.join(); // Wait for the other threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } } // Test 9: yield cout << endl << "PART IX: Yield (40 + 1 threads)" << endl; { // Start a bunch of child threads list<thread *> threadList; for(int i = 0; i < 40; ++ i) threadList.push_back(new threadt(ThreadYield, 0)); // Yield... this_thread::yield(); // Wait for the threads to finish list<thread *>::iterator it; for(it = threadList.begin(); it != threadList.end(); ++ it) { thread * t = *it; t->join(); delete t; } } // Test 10: sleep cout << endl << "PART X: Sleep (10 x 100 ms)" << endl; { // Sleep... cout << " Sleeping" << flush; for(int i = 0; i < 10; ++ i) { this_thread::sleep_for(chrono::milliseconds(100)); cout << "." << flush; } cout << endl; } // Test 11: detach cout << endl << "PART XI: Detach" << endl; { threadt t(ThreadDetach, 0); t.detach(); cout << " Detached from thread." << endl; // Give the thread a chanse to finish too... this_thread::sleep_for(chrono::milliseconds(400)); } cout << endl << "Tests done!" << endl; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <uvw.hpp> #ifdef _WIN32 #include <fcntl.h> #endif TEST(FileReq, OpenAndClose) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsOpenEvent = false; bool checkFsCloseEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::CLOSE>>([&checkFsCloseEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsCloseEvent); checkFsCloseEvent = true; }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([&checkFsOpenEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsOpenEvent); checkFsOpenEvent = true; request.close(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_WRONLY, 0644); #else request->open(filename, O_CREAT | O_WRONLY, 0644); #endif loop->run(); ASSERT_TRUE(checkFsOpenEvent); ASSERT_TRUE(checkFsCloseEvent); } TEST(FileReq, OpenAndCloseSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_WRONLY, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_WRONLY, 0644)); #endif ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, RW) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsWriteEvent = false; bool checkFsReadEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::READ>>([&checkFsReadEvent](const auto &event, auto &request) { ASSERT_FALSE(checkFsReadEvent); ASSERT_EQ(event.data[0], 42); checkFsReadEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::WRITE>>([&checkFsWriteEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsWriteEvent); checkFsWriteEvent = true; request.read(0, 1); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.write(std::unique_ptr<char[]>{new char[1]{ 42 }}, 1, 0); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsWriteEvent); ASSERT_TRUE(checkFsReadEvent); } TEST(FileReq, RWSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif auto writeR = request->writeSync(std::unique_ptr<char[]>{new char[1]{ 42 }}, 1, 0); ASSERT_TRUE(writeR.first); ASSERT_EQ(writeR.second, 1); auto readR = request->readSync(0, 1); ASSERT_TRUE(readR.first); ASSERT_EQ(readR.second.first[0], 42); ASSERT_EQ(readR.second.second, 1); ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, Stat) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsStatEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::FSTAT>>([&checkFsStatEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsStatEvent); checkFsStatEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.stat(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsStatEvent); } TEST(FileReq, StatSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif auto statR = request->statSync(); ASSERT_TRUE(statR.first); ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, Sync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsSyncEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::FSYNC>>([&checkFsSyncEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsSyncEvent); checkFsSyncEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.sync(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsSyncEvent); } TEST(FileReq, SyncSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif ASSERT_TRUE(request->syncSync()); ASSERT_TRUE(request->closeSync()); loop->run(); } /* TEST(FileReq, Datasync) { // TODO } TEST(FileReq, DatasyncSync) { // TODO } TEST(FileReq, Truncate) { // TODO } TEST(FileReq, TruncateSync) { // TODO } TEST(FileReq, SendFile) { // TODO } TEST(FileReq, SendFileSync) { // TODO } TEST(FileReq, Chmod) { // TODO } TEST(FileReq, ChmodSync) { // TODO } TEST(FileReq, Utime) { // TODO } TEST(FileReq, UtimeSync) { // TODO } TEST(FileReq, Chown) { // TODO } TEST(FileReq, ChownSync) { // TODO } TEST(FsReq, Unlink) { // TODO } TEST(FsReq, UnlinkSync) { // TODO } TEST(FsReq, Mkdir) { // TODO } TEST(FsReq, MkdirSync) { // TODO } TEST(FsReq, Mkdtemp) { // TODO } TEST(FsReq, MkdtempSync) { // TODO } TEST(FsReq, Rmdir) { // TODO } TEST(FsReq, RmdirSync) { // TODO } TEST(FsReq, Scandir) { // TODO } TEST(FsReq, ScandirSync) { // TODO } TEST(FsReq, Stat) { // TODO } TEST(FsReq, StatSync) { // TODO } TEST(FsReq, Lstat) { // TODO } TEST(FsReq, LstatSync) { // TODO } TEST(FsReq, Rename) { // TODO } TEST(FsReq, RenameSync) { // TODO } TEST(FsReq, Access) { // TODO } TEST(FsReq, AccessSync) { // TODO } TEST(FsReq, Chmod) { // TODO } TEST(FsReq, ChmodSync) { // TODO } TEST(FsReq, Utime) { // TODO } TEST(FsReq, UtimeSync) { // TODO } TEST(FsReq, Link) { // TODO } TEST(FsReq, LinkSync) { // TODO } TEST(FsReq, Symlink) { // TODO } TEST(FsReq, SymlinkSync) { // TODO } TEST(FsReq, Readlink) { // TODO } TEST(FsReq, ReadlinkSync) { // TODO } TEST(FsReq, Realpath) { // TODO } TEST(FsReq, RealpathSync) { // TODO } TEST(FsReq, Chown) { // TODO } TEST(FsReq, ChownSync) { // TODO } */ <commit_msg>tests: fs/FileReq/Datasync and fs/FileReq/DatasyncSync<commit_after>#include <gtest/gtest.h> #include <uvw.hpp> #ifdef _WIN32 #include <fcntl.h> #endif TEST(FileReq, OpenAndClose) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsOpenEvent = false; bool checkFsCloseEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::CLOSE>>([&checkFsCloseEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsCloseEvent); checkFsCloseEvent = true; }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([&checkFsOpenEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsOpenEvent); checkFsOpenEvent = true; request.close(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_WRONLY, 0644); #else request->open(filename, O_CREAT | O_WRONLY, 0644); #endif loop->run(); ASSERT_TRUE(checkFsOpenEvent); ASSERT_TRUE(checkFsCloseEvent); } TEST(FileReq, OpenAndCloseSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_WRONLY, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_WRONLY, 0644)); #endif ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, RW) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsWriteEvent = false; bool checkFsReadEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::READ>>([&checkFsReadEvent](const auto &event, auto &request) { ASSERT_FALSE(checkFsReadEvent); ASSERT_EQ(event.data[0], 42); checkFsReadEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::WRITE>>([&checkFsWriteEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsWriteEvent); checkFsWriteEvent = true; request.read(0, 1); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.write(std::unique_ptr<char[]>{new char[1]{ 42 }}, 1, 0); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsWriteEvent); ASSERT_TRUE(checkFsReadEvent); } TEST(FileReq, RWSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif auto writeR = request->writeSync(std::unique_ptr<char[]>{new char[1]{ 42 }}, 1, 0); ASSERT_TRUE(writeR.first); ASSERT_EQ(writeR.second, 1); auto readR = request->readSync(0, 1); ASSERT_TRUE(readR.first); ASSERT_EQ(readR.second.first[0], 42); ASSERT_EQ(readR.second.second, 1); ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, Stat) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsStatEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::FSTAT>>([&checkFsStatEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsStatEvent); checkFsStatEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.stat(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsStatEvent); } TEST(FileReq, StatSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif auto statR = request->statSync(); ASSERT_TRUE(statR.first); ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, Sync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsSyncEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::FSYNC>>([&checkFsSyncEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsSyncEvent); checkFsSyncEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.sync(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsSyncEvent); } TEST(FileReq, SyncSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif ASSERT_TRUE(request->syncSync()); ASSERT_TRUE(request->closeSync()); loop->run(); } TEST(FileReq, Datasync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkFsDatasyncEvent = false; request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::FDATASYNC>>([&checkFsDatasyncEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsDatasyncEvent); checkFsDatasyncEvent = true; request.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &request) { request.datasync(); }); #ifdef _WIN32 request->open(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644); #else request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); #endif loop->run(); ASSERT_TRUE(checkFsDatasyncEvent); } TEST(FileReq, DatasyncSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_CREAT | _O_RDWR | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_CREAT | O_RDWR | O_TRUNC, 0644)); #endif ASSERT_TRUE(request->datasyncSync()); ASSERT_TRUE(request->closeSync()); loop->run(); } /* TEST(FileReq, Truncate) { // TODO } TEST(FileReq, TruncateSync) { // TODO } TEST(FileReq, SendFile) { // TODO } TEST(FileReq, SendFileSync) { // TODO } TEST(FileReq, Chmod) { // TODO } TEST(FileReq, ChmodSync) { // TODO } TEST(FileReq, Utime) { // TODO } TEST(FileReq, UtimeSync) { // TODO } TEST(FileReq, Chown) { // TODO } TEST(FileReq, ChownSync) { // TODO } TEST(FsReq, Unlink) { // TODO } TEST(FsReq, UnlinkSync) { // TODO } TEST(FsReq, Mkdir) { // TODO } TEST(FsReq, MkdirSync) { // TODO } TEST(FsReq, Mkdtemp) { // TODO } TEST(FsReq, MkdtempSync) { // TODO } TEST(FsReq, Rmdir) { // TODO } TEST(FsReq, RmdirSync) { // TODO } TEST(FsReq, Scandir) { // TODO } TEST(FsReq, ScandirSync) { // TODO } TEST(FsReq, Stat) { // TODO } TEST(FsReq, StatSync) { // TODO } TEST(FsReq, Lstat) { // TODO } TEST(FsReq, LstatSync) { // TODO } TEST(FsReq, Rename) { // TODO } TEST(FsReq, RenameSync) { // TODO } TEST(FsReq, Access) { // TODO } TEST(FsReq, AccessSync) { // TODO } TEST(FsReq, Chmod) { // TODO } TEST(FsReq, ChmodSync) { // TODO } TEST(FsReq, Utime) { // TODO } TEST(FsReq, UtimeSync) { // TODO } TEST(FsReq, Link) { // TODO } TEST(FsReq, LinkSync) { // TODO } TEST(FsReq, Symlink) { // TODO } TEST(FsReq, SymlinkSync) { // TODO } TEST(FsReq, Readlink) { // TODO } TEST(FsReq, ReadlinkSync) { // TODO } TEST(FsReq, Realpath) { // TODO } TEST(FsReq, RealpathSync) { // TODO } TEST(FsReq, Chown) { // TODO } TEST(FsReq, ChownSync) { // TODO } */ <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <uvw.hpp> #ifdef _WIN32 #include <fcntl.h> #endif TEST(FileReq, OpenAndClose) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkErrorEvent = false; bool checkFsEvent = false; request->on<uvw::ErrorEvent>([&checkErrorEvent](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([&checkFsEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsEvent); checkFsEvent = true; request.close(); }); #ifdef _WIN32 request->open(filename, _O_RDWR | _O_CREAT, 0644); #else request->open(filename, O_RDWR | O_CREAT, 0644); #endif loop->run(); ASSERT_FALSE(checkErrorEvent); ASSERT_TRUE(checkFsEvent); } TEST(FileReq, OpenAndCloseSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_RDWR | _O_CREAT, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_RDWR | O_CREAT, 0644)); #endif ASSERT_TRUE(request->closeSync()); loop->run(); } /* TEST(FileReq, RW) { // TODO } TEST(FileReq, RWSync) { // TODO } TEST(FileReq, Stat) { // TODO } TEST(FileReq, StatSync) { // TODO } TEST(FileReq, Sync) { // TODO } TEST(FileReq, SyncSync) { // TODO } TEST(FileReq, Datasync) { // TODO } TEST(FileReq, DatasyncSync) { // TODO } TEST(FileReq, Truncate) { // TODO } TEST(FileReq, TruncateSync) { // TODO } TEST(FileReq, SendFile) { // TODO } TEST(FileReq, SendFileSync) { // TODO } TEST(FileReq, Chmod) { // TODO } TEST(FileReq, ChmodSync) { // TODO } TEST(FileReq, Utime) { // TODO } TEST(FileReq, UtimeSync) { // TODO } TEST(FileReq, Chown) { // TODO } TEST(FileReq, ChownSync) { // TODO } TEST(FsReq, Unlink) { // TODO } TEST(FsReq, UnlinkSync) { // TODO } TEST(FsReq, Mkdir) { // TODO } TEST(FsReq, MkdirSync) { // TODO } TEST(FsReq, Mkdtemp) { // TODO } TEST(FsReq, MkdtempSync) { // TODO } TEST(FsReq, Rmdir) { // TODO } TEST(FsReq, RmdirSync) { // TODO } TEST(FsReq, Scandir) { // TODO } TEST(FsReq, ScandirSync) { // TODO } TEST(FsReq, Stat) { // TODO } TEST(FsReq, StatSync) { // TODO } TEST(FsReq, Lstat) { // TODO } TEST(FsReq, LstatSync) { // TODO } TEST(FsReq, Rename) { // TODO } TEST(FsReq, RenameSync) { // TODO } TEST(FsReq, Access) { // TODO } TEST(FsReq, AccessSync) { // TODO } TEST(FsReq, Chmod) { // TODO } TEST(FsReq, ChmodSync) { // TODO } TEST(FsReq, Utime) { // TODO } TEST(FsReq, UtimeSync) { // TODO } TEST(FsReq, Link) { // TODO } TEST(FsReq, LinkSync) { // TODO } TEST(FsReq, Symlink) { // TODO } TEST(FsReq, SymlinkSync) { // TODO } TEST(FsReq, Readlink) { // TODO } TEST(FsReq, ReadlinkSync) { // TODO } TEST(FsReq, Realpath) { // TODO } TEST(FsReq, RealpathSync) { // TODO } TEST(FsReq, Chown) { // TODO } TEST(FsReq, ChownSync) { // TODO } */ <commit_msg>minor changes<commit_after>#include <gtest/gtest.h> #include <uvw.hpp> #ifdef _WIN32 #include <fcntl.h> #endif TEST(FileReq, OpenAndClose) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); bool checkErrorEvent = false; bool checkFsEvent = false; request->on<uvw::ErrorEvent>([&checkErrorEvent](const auto &, auto &) { FAIL(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([&checkFsEvent](const auto &, auto &request) { ASSERT_FALSE(checkFsEvent); checkFsEvent = true; request.close(); }); #ifdef _WIN32 request->open(filename, _O_RDWR | _O_CREAT | _O_TRUNC, 0644); #else request->open(filename, O_RDWR | O_CREAT | O_TRUNC, 0644); #endif loop->run(); ASSERT_FALSE(checkErrorEvent); ASSERT_TRUE(checkFsEvent); } TEST(FileReq, OpenAndCloseSync) { const std::string filename = std::string{TARGET_FS_DIR} + std::string{"/test.fs"}; auto loop = uvw::Loop::getDefault(); auto request = loop->resource<uvw::FileReq>(); #ifdef _WIN32 ASSERT_TRUE(request->openSync(filename, _O_RDWR | _O_CREAT | _O_TRUNC, 0644)); #else ASSERT_TRUE(request->openSync(filename, O_RDWR | O_CREAT | O_TRUNC, 0644)); #endif ASSERT_TRUE(request->closeSync()); loop->run(); } /* TEST(FileReq, RW) { // TODO } TEST(FileReq, RWSync) { // TODO } TEST(FileReq, Stat) { // TODO } TEST(FileReq, StatSync) { // TODO } TEST(FileReq, Sync) { // TODO } TEST(FileReq, SyncSync) { // TODO } TEST(FileReq, Datasync) { // TODO } TEST(FileReq, DatasyncSync) { // TODO } TEST(FileReq, Truncate) { // TODO } TEST(FileReq, TruncateSync) { // TODO } TEST(FileReq, SendFile) { // TODO } TEST(FileReq, SendFileSync) { // TODO } TEST(FileReq, Chmod) { // TODO } TEST(FileReq, ChmodSync) { // TODO } TEST(FileReq, Utime) { // TODO } TEST(FileReq, UtimeSync) { // TODO } TEST(FileReq, Chown) { // TODO } TEST(FileReq, ChownSync) { // TODO } TEST(FsReq, Unlink) { // TODO } TEST(FsReq, UnlinkSync) { // TODO } TEST(FsReq, Mkdir) { // TODO } TEST(FsReq, MkdirSync) { // TODO } TEST(FsReq, Mkdtemp) { // TODO } TEST(FsReq, MkdtempSync) { // TODO } TEST(FsReq, Rmdir) { // TODO } TEST(FsReq, RmdirSync) { // TODO } TEST(FsReq, Scandir) { // TODO } TEST(FsReq, ScandirSync) { // TODO } TEST(FsReq, Stat) { // TODO } TEST(FsReq, StatSync) { // TODO } TEST(FsReq, Lstat) { // TODO } TEST(FsReq, LstatSync) { // TODO } TEST(FsReq, Rename) { // TODO } TEST(FsReq, RenameSync) { // TODO } TEST(FsReq, Access) { // TODO } TEST(FsReq, AccessSync) { // TODO } TEST(FsReq, Chmod) { // TODO } TEST(FsReq, ChmodSync) { // TODO } TEST(FsReq, Utime) { // TODO } TEST(FsReq, UtimeSync) { // TODO } TEST(FsReq, Link) { // TODO } TEST(FsReq, LinkSync) { // TODO } TEST(FsReq, Symlink) { // TODO } TEST(FsReq, SymlinkSync) { // TODO } TEST(FsReq, Readlink) { // TODO } TEST(FsReq, ReadlinkSync) { // TODO } TEST(FsReq, Realpath) { // TODO } TEST(FsReq, RealpathSync) { // TODO } TEST(FsReq, Chown) { // TODO } TEST(FsReq, ChownSync) { // TODO } */ <|endoftext|>
<commit_before>#include "HFO.hpp" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <assert.h> #include <netdb.h> #include <iostream> #include <stdarg.h> #include <agent.h> #include <rcsc/common/basic_client.h> #include <rcsc/player/player_config.h> #include <rcsc/player/world_model.h> using namespace hfo; #define MAX_STEPS 100 HFOEnvironment::HFOEnvironment() { client = new rcsc::BasicClient(); agent = new Agent(); } HFOEnvironment::~HFOEnvironment() { delete client; delete agent; } void HFOEnvironment::connectToServer(feature_set_t feature_set, std::string config_dir, int server_port, std::string server_addr, std::string team_name, bool play_goalie, std::string record_dir) { agent->setFeatureSet(feature_set); rcsc::PlayerConfig& config = agent->mutable_config(); config.setConfigDir(config_dir); config.setPort(server_port); config.setHost(server_addr); config.setTeamName(team_name); config.setGoalie(play_goalie); if (!record_dir.empty()) { config.setLogDir(record_dir); config.setRecord(true); } if (!agent->init(client, 0, NULL)) { std::cerr << "Init failed" << std::endl; exit(1); } client->setClientMode(rcsc::BasicClient::ONLINE); if (!client->startAgent(agent)) { std::cerr << "Unable to start agent" << std::endl; exit(1); } // Do nothing until the agent begins getting state features act(NOOP); while (agent->getState().empty()) { if (!client->isServerAlive()) { std::cerr << "[ConnectToServer] Server Down!" << std::endl; exit(1); } ready_for_action = client->runStep(agent); if (ready_for_action) { agent->action(); } } // Step until it is time to act do { ready_for_action = client->runStep(agent); } while (!ready_for_action); agent->ProcessTrainerMessages(); agent->ProcessTeammateMessages(); agent->UpdateFeatures(); current_cycle = agent->currentTime().cycle(); } const std::vector<float>& HFOEnvironment::getState() { return agent->getState(); } void HFOEnvironment::act(action_t action, ...) { agent->setAction(action); int n_args = NumParams(action); std::vector<float> *params = agent->mutable_params(); params->resize(n_args); va_list vl; va_start(vl, action); for (int i = 0; i < n_args; ++i) { (*params)[i] = va_arg(vl, double); } va_end(vl); } void HFOEnvironment::act(action_t action, const std::vector<float>& params) { agent->setAction(action); int n_args = NumParams(action); assert(n_args == params.size()); std::vector<float> *agent_params = agent->mutable_params(); (*agent_params) = params; } void HFOEnvironment::say(const std::string& message) { agent->setSayMsg(message); } std::string HFOEnvironment::hear() { return agent->getHearMsg(); } int HFOEnvironment::getUnum() { return agent->getUnum(); } Player HFOEnvironment::playerOnBall() { return agent->getPlayerOnBall(); } status_t HFOEnvironment::step() { assert(agent->currentTime().cycle() == current_cycle); assert(ready_for_action); // Execute the action agent->executeAction(); // Advance the environment by one step do { ready_for_action = client->runStep(agent); if (!client->isServerAlive() || agent->getGameStatus() == SERVER_DOWN) { return SERVER_DOWN; } agent->ProcessTrainerMessages(); } while (agent->statusUpdateTime() <= current_cycle || !ready_for_action); // Update the state features agent->preAction(); assert(agent->currentTime().cycle() == (current_cycle + 1)); current_cycle = agent->currentTime().cycle(); status_t status = agent->getGameStatus(); // If the episode is over, take three NOOPs to refresh state features if (status != IN_GAME && status != SERVER_DOWN) { for (int i = 0; i < 3; ++i) { act(NOOP); if (step() == SERVER_DOWN) { return SERVER_DOWN; } } } return status; } <commit_msg>Simplify interface.<commit_after>#include "HFO.hpp" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <assert.h> #include <netdb.h> #include <iostream> #include <stdarg.h> #include <agent.h> #include <rcsc/common/basic_client.h> #include <rcsc/player/player_config.h> #include <rcsc/player/world_model.h> using namespace hfo; #define MAX_STEPS 100 HFOEnvironment::HFOEnvironment() { client = new rcsc::BasicClient(); agent = new Agent(); } HFOEnvironment::~HFOEnvironment() { delete client; delete agent; } void HFOEnvironment::connectToServer(feature_set_t feature_set, std::string config_dir, int server_port, std::string server_addr, std::string team_name, bool play_goalie, std::string record_dir) { agent->setFeatureSet(feature_set); rcsc::PlayerConfig& config = agent->mutable_config(); config.setConfigDir(config_dir); config.setPort(server_port); config.setHost(server_addr); config.setTeamName(team_name); config.setGoalie(play_goalie); if (!record_dir.empty()) { config.setLogDir(record_dir); config.setRecord(true); } if (!agent->init(client, 0, NULL)) { std::cerr << "Init failed" << std::endl; exit(1); } client->setClientMode(rcsc::BasicClient::ONLINE); if (!client->startAgent(agent)) { std::cerr << "Unable to start agent" << std::endl; exit(1); } // Do nothing until the agent begins getting state features act(NOOP); while (agent->getState().empty()) { if (!client->isServerAlive()) { std::cerr << "[ConnectToServer] Server Down!" << std::endl; exit(1); } ready_for_action = client->runStep(agent); if (ready_for_action) { agent->action(); } } // Step until it is time to act do { ready_for_action = client->runStep(agent); } while (!ready_for_action); agent->ProcessTrainerMessages(); agent->ProcessTeammateMessages(); agent->UpdateFeatures(); current_cycle = agent->currentTime().cycle(); } const std::vector<float>& HFOEnvironment::getState() { return agent->getState(); } void HFOEnvironment::act(action_t action, ...) { agent->setAction(action); int n_args = NumParams(action); std::vector<float> *params = agent->mutable_params(); params->resize(n_args); va_list vl; va_start(vl, action); for (int i = 0; i < n_args; ++i) { (*params)[i] = va_arg(vl, double); } va_end(vl); } void HFOEnvironment::act(action_t action, const std::vector<float>& params) { agent->setAction(action); int n_args = NumParams(action); assert(n_args == params.size()); std::vector<float> *agent_params = agent->mutable_params(); (*agent_params) = params; } void HFOEnvironment::say(const std::string& message) { agent->setSayMsg(message); } std::string HFOEnvironment::hear() { return agent->getHearMsg(); } int HFOEnvironment::getUnum() { return agent->getUnum(); } Player HFOEnvironment::playerOnBall() { return agent->getPlayerOnBall(); } status_t HFOEnvironment::step() { // Execute the action agent->executeAction(); // Advance the environment by one step do { ready_for_action = client->runStep(agent); if (!client->isServerAlive() || agent->getGameStatus() == SERVER_DOWN) { return SERVER_DOWN; } agent->ProcessTrainerMessages(); } while (agent->statusUpdateTime() <= current_cycle || !ready_for_action); // Update the state features agent->preAction(); current_cycle = agent->currentTime().cycle(); status_t status = agent->getGameStatus(); // If the episode is over, take three NOOPs to refresh state features if (status != IN_GAME && status != SERVER_DOWN) { for (int i = 0; i < 3; ++i) { act(NOOP); step(); } } return status; } <|endoftext|>
<commit_before>#include "picross.h" using namespace std; int main(int argc, char** argv) { ifstream f; //f.open(argv[1]); f.open("Fichiers\ Test/tipoisson.txt"); if(!f.is_open()) { cerr<<"probleme d'ouverture du fichier"<<endl; return 1; } else { /* On lit le fichier texte et construit le Picross */ size_t nbl, nbc; f>>nbl>>nbc; Picross P(nbl,nbc); f.ignore(); //le '\n' P.remplirTabListe(f); //on rempli les lignes des cases sures P.solCasesSure(0); //subterfuge pour finir tipoisson et valider le test des methodes int* T=new int [5]; for(size_t i=0; i<5; i++) { T[i]=1; } P.pushMat(0, T, 1); cout<<P; //on check si les listes sont verifiées dans mat P.setLignesFinies(0); P.setLignesFinies(1); //on check si le picross est fini sur toutes les listes cout << "isPicrossFini : " << P.isPicrossFini() << endl; //verification methode inverseTab T[4]=0; afftableau(T,5); cout << "inverseTab : " << endl; P.inverseTab(T,5); afftableau(T,5); //cout << P.inverseListe(P.getLignes()[1]); // P.SLPG(P.getColonneMat(1),P.getMat().getNbl(),P.getColonnes()[1].getPremier()); } f.close(); return 0; } <commit_msg>Ajout test inverseListe<commit_after>#include "picross.h" using namespace std; int main(int argc, char** argv) { ifstream f; //f.open(argv[1]); f.open("Fichiers\ Test/tipoisson.txt"); if(!f.is_open()) { cerr<<"probleme d'ouverture du fichier"<<endl; return 1; } else { /* On lit le fichier texte et construit le Picross */ size_t nbl, nbc; f>>nbl>>nbc; Picross P(nbl,nbc); f.ignore(); //le '\n' P.remplirTabListe(f); //on rempli les lignes des cases sures P.solCasesSure(0); //subterfuge pour finir tipoisson et valider le test des methodes int* T=new int [5]; for(size_t i=0; i<5; i++) { T[i]=1; } P.pushMat(0, T, 1); cout<<P; //on check si les listes sont verifiées dans mat P.setLignesFinies(0); P.setLignesFinies(1); //on check si le picross est fini sur toutes les listes cout << "isPicrossFini : " << P.isPicrossFini() << endl; //verification methode inverseTab T[4]=0; afftableau(T,5); cout << "inverseTab : " << endl; P.inverseTab(T,5); afftableau(T,5); Liste L; L.putFin(1); L.putFin(2); L.putFin(3); cout << L; cout << P.inverseListe(L); // P.SLPG(P.getColonneMat(1),P.getMat().getNbl(),P.getColonnes()[1].getPremier()); } f.close(); return 0; } <|endoftext|>
<commit_before>/* * Super Entity Game Server Project * http://segs.sf.net/ * Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt) * This software is licensed! (See License.txt for details) * */ //#define ACE_NTRACE 0 #include "Servers/HandlerLocator.h" #include "Servers/MessageBus.h" #include "Servers/MessageBusEndpoint.h" #include "Servers/InternalEvents.h" #include "SEGSTimer.h" #include "Settings.h" #include "Logging.h" #include "version.h" ////////////////////////////////////////////////////////////////////////// #include "AuthServer.h" #include "Servers/MapServer/MapServer.h" #include "Servers/GameServer/GameServer.h" #include "Servers/GameDatabase/GameDBSync.h" #include "Servers/AuthDatabase/AuthDBSync.h" ////////////////////////////////////////////////////////////////////////// #include <ace/ACE.h> #include <ace/Singleton.h> #include <ace/Log_Record.h> #include <ace/INET_Addr.h> #include <ace/Reactor.h> #include <ace/TP_Reactor.h> #include <ace/INET_Addr.h> #include <ace/OS_main.h> //Included to enable file logging #include <ace/streams.h> //Included to enable file logging #include <QtCore/QCoreApplication> #include <QtCore/QLoggingCategory> #include <QtCore/QSettings> #include <QtCore/QCommandLineParser> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QElapsedTimer> #include <thread> #include <mutex> #include <stdlib.h> #include <memory> #define TIMED_LOG(x,msg) {\ QDebug log(qDebug());\ log << msg << "..."; \ QElapsedTimer timer;\ timer.start();\ x;\ log << "done in"<<float(timer.elapsed())/1000.0f<<"s";\ } namespace { static bool s_event_loop_is_done=false; //!< this is set to true when ace reactor is finished. static std::unique_ptr<AuthServer> g_auth_server; // this is a global for now. static std::unique_ptr<GameServer> g_game_server; static std::unique_ptr<MapServer> g_map_server; static std::unique_ptr<MessageBus> g_message_bus; struct MessageBusMonitor : public EventProcessor { MessageBusEndpoint m_endpoint; MessageBusMonitor() : m_endpoint(*this) { m_endpoint.subscribe(MessageBus::ALL_EVENTS); activate(); } // EventProcessor interface public: void dispatch(SEGSEvent *ev) { switch(ev->type()) { case Internal_EventTypes::evServiceStatus: on_service_status(static_cast<ServiceStatusMessage *>(ev)); break; default: ;//qDebug() << "Unhandled message bus monitor command" <<ev->info(); } } private: void on_service_status(ServiceStatusMessage *msg); }; static std::unique_ptr<MessageBusMonitor> s_bus_monitor; static void shutDownServers() { if (GlobalTimerQueue::instance()->thr_count()) { GlobalTimerQueue::instance()->deactivate(); } if(g_game_server && g_game_server->thr_count()) { g_game_server->ShutDown(); } if(g_map_server && g_map_server->thr_count()) { g_map_server->ShutDown(); } if(g_auth_server && g_auth_server->thr_count()) { g_auth_server->ShutDown(); } if(s_bus_monitor && s_bus_monitor->thr_count()) { s_bus_monitor->putq(SEGSEvent::s_ev_finish.shallow_copy()); } if(g_message_bus && g_message_bus->thr_count()) { g_message_bus->putq(SEGSEvent::s_ev_finish.shallow_copy()); } s_event_loop_is_done = true; } void MessageBusMonitor::on_service_status(ServiceStatusMessage *msg) { if (msg->m_data.status_value != 0) { qCritical().noquote() << msg->m_data.status_message; shutDownServers(); } else qInfo() << msg->m_data.status_message; } // this event stops main processing loop of the whole server class ServerStopper : public ACE_Event_Handler { public: ServerStopper(int signum) // when instantiated adds itself to current reactor { ACE_Reactor::instance()->register_handler(signum, this); } // Called when object is signaled by OS. int handle_signal(int, siginfo_t */*s_i*/, ucontext_t */*u_c*/) { shutDownServers(); return 0; } }; bool CreateServers() { static ReloadConfigMessage reload_config; GlobalTimerQueue::instance()->activate(); TIMED_LOG( { g_message_bus.reset(new MessageBus); HandlerLocator::setMessageBus(g_message_bus.get()); g_message_bus->ReadConfigAndRestart(); } ,"Creating message bus"); TIMED_LOG(s_bus_monitor.reset(new MessageBusMonitor),"Starting message bus monitor"); TIMED_LOG(startAuthDBSync(),"Starting auth db service"); TIMED_LOG({ g_auth_server.reset(new AuthServer); g_auth_server->activate(); },"Starting auth service"); // AdminServer::instance()->ReadConfig(); // AdminServer::instance()->Run(); TIMED_LOG(startGameDBSync(1),"Starting game(1) db service"); TIMED_LOG({ g_game_server.reset(new GameServer(1)); g_game_server->activate(); },"Starting game(1) server"); TIMED_LOG({ g_map_server.reset(new MapServer(1)); g_map_server->sett_game_server_owner(1); g_map_server->activate(); },"Starting map server"); qDebug() << "Asking AuthServer to load configuration and begin listening for external connections."; g_auth_server->putq(reload_config.shallow_copy()); qDebug() << "Asking GameServer(0) to load configuration on begin listening for external connections."; g_game_server->putq(reload_config.shallow_copy()); qDebug() << "Asking MapServer to load configuration on begin listening for external connections."; g_map_server->putq(reload_config.shallow_copy()); // server_manger->AddGameServer(game_instance); return true; } std::mutex log_mutex; void segsLogMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { std::lock_guard<std::mutex> lock(log_mutex); QFile segs_log_target; segs_log_target.setFileName("output.log"); if (!segs_log_target.open(QFile::WriteOnly | QFile::Append)) { fprintf(stderr,"Failed to open log file in write mode, will procede with console only logging"); } QTextStream fileLog(&segs_log_target); QByteArray localMsg = msg.toLocal8Bit(); QString message; switch (type) { case QtDebugMsg: message = QString("Debug : %1").arg(localMsg.constData()); break; case QtInfoMsg: // no prefix for informational messages message = localMsg.constData(); break; case QtWarningMsg: message = QString("Warning : %1").arg(localMsg.constData()); break; case QtCriticalMsg: message = QString("Critical: %1").arg(localMsg.constData()); break; case QtFatalMsg: message = QString("Fatal error %1").arg(localMsg.constData()); } fprintf(stdout, "%s\n", qPrintable(message)); if (type != QtInfoMsg && segs_log_target.isOpen()) { fileLog << message << "\n"; fileLog.flush(); } if (type == QtFatalMsg) { fflush(stdout); abort(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // End of anonymous namespace /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ACE_INT32 ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { setLoggingFilter(); // Set QT Logging filters qInstallMessageHandler(segsLogMessageOutput); QCoreApplication q_app(argc,argv); QCoreApplication::setOrganizationDomain("segs.nemerle.eu"); QCoreApplication::setOrganizationName("SEGS Project"); QCoreApplication::setApplicationName("segs_server"); QCoreApplication::setApplicationVersion(VersionInfo::getAuthVersion()); QCommandLineParser parser; parser.setApplicationDescription("SEGS - CoX server"); parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({ {{"f","config"}, "Use the provided settings file, default value is <settings.cfg>", "filename","settings.cfg"} }); parser.process(q_app); if(parser.isSet("help")||parser.isSet("version")) return 0; Settings::setSettingsPath(parser.value("config")); // set settings.cfg from args ACE_Sig_Set interesting_signals; interesting_signals.sig_add(SIGINT); interesting_signals.sig_add(SIGHUP); const size_t N_THREADS = 1; //std::unique_ptr<ACE_Reactor> old_instance(ACE_Reactor::instance(&new_reactor)); // this will delete old instance when app finishes ServerStopper st(SIGINT); // it'll register itself with current reactor, and shut it down on sigint ACE_Reactor::instance()->register_handler(interesting_signals,&st); // Print out startup copyright messages qInfo().noquote() << VersionInfo::getCopyright(); qInfo().noquote() << VersionInfo::getAuthVersion(); qInfo().noquote() << "main"; bool no_err = CreateServers(); if(!no_err) { ACE_Reactor::instance()->end_reactor_event_loop(); return -1; } // process all queued qt messages here. ACE_Time_Value event_processing_delay(0,1000*5); while( !s_event_loop_is_done ) { ACE_Reactor::instance()->handle_events(&event_processing_delay); QCoreApplication::processEvents(); } GlobalTimerQueue::instance()->wait(); g_game_server->wait(); g_map_server->wait(); g_auth_server->wait(); s_bus_monitor->wait(); g_message_bus->wait(); g_game_server.reset(); g_map_server.reset(); g_auth_server.reset(); s_bus_monitor.reset(); g_message_bus.reset(); ACE_Reactor::instance()->handle_events(&event_processing_delay); ACE_Reactor::instance()->remove_handler(interesting_signals); ACE_Reactor::end_event_loop(); return 0; } <commit_msg>Reduce number of allocations in segsLogMessageOutput<commit_after>/* * Super Entity Game Server Project * http://segs.sf.net/ * Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt) * This software is licensed! (See License.txt for details) * */ //#define ACE_NTRACE 0 #include "Servers/HandlerLocator.h" #include "Servers/MessageBus.h" #include "Servers/MessageBusEndpoint.h" #include "Servers/InternalEvents.h" #include "SEGSTimer.h" #include "Settings.h" #include "Logging.h" #include "version.h" ////////////////////////////////////////////////////////////////////////// #include "AuthServer.h" #include "Servers/MapServer/MapServer.h" #include "Servers/GameServer/GameServer.h" #include "Servers/GameDatabase/GameDBSync.h" #include "Servers/AuthDatabase/AuthDBSync.h" ////////////////////////////////////////////////////////////////////////// #include <ace/ACE.h> #include <ace/Singleton.h> #include <ace/Log_Record.h> #include <ace/INET_Addr.h> #include <ace/Reactor.h> #include <ace/TP_Reactor.h> #include <ace/INET_Addr.h> #include <ace/OS_main.h> //Included to enable file logging #include <ace/streams.h> //Included to enable file logging #include <QtCore/QCoreApplication> #include <QtCore/QLoggingCategory> #include <QtCore/QSettings> #include <QtCore/QCommandLineParser> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QElapsedTimer> #include <thread> #include <mutex> #include <stdlib.h> #include <memory> #define TIMED_LOG(x,msg) {\ QDebug log(qDebug());\ log << msg << "..."; \ QElapsedTimer timer;\ timer.start();\ x;\ log << "done in"<<float(timer.elapsed())/1000.0f<<"s";\ } namespace { static bool s_event_loop_is_done=false; //!< this is set to true when ace reactor is finished. static std::unique_ptr<AuthServer> g_auth_server; // this is a global for now. static std::unique_ptr<GameServer> g_game_server; static std::unique_ptr<MapServer> g_map_server; static std::unique_ptr<MessageBus> g_message_bus; struct MessageBusMonitor : public EventProcessor { MessageBusEndpoint m_endpoint; MessageBusMonitor() : m_endpoint(*this) { m_endpoint.subscribe(MessageBus::ALL_EVENTS); activate(); } // EventProcessor interface public: void dispatch(SEGSEvent *ev) { switch(ev->type()) { case Internal_EventTypes::evServiceStatus: on_service_status(static_cast<ServiceStatusMessage *>(ev)); break; default: ;//qDebug() << "Unhandled message bus monitor command" <<ev->info(); } } private: void on_service_status(ServiceStatusMessage *msg); }; static std::unique_ptr<MessageBusMonitor> s_bus_monitor; static void shutDownServers() { if (GlobalTimerQueue::instance()->thr_count()) { GlobalTimerQueue::instance()->deactivate(); } if(g_game_server && g_game_server->thr_count()) { g_game_server->ShutDown(); } if(g_map_server && g_map_server->thr_count()) { g_map_server->ShutDown(); } if(g_auth_server && g_auth_server->thr_count()) { g_auth_server->ShutDown(); } if(s_bus_monitor && s_bus_monitor->thr_count()) { s_bus_monitor->putq(SEGSEvent::s_ev_finish.shallow_copy()); } if(g_message_bus && g_message_bus->thr_count()) { g_message_bus->putq(SEGSEvent::s_ev_finish.shallow_copy()); } s_event_loop_is_done = true; } void MessageBusMonitor::on_service_status(ServiceStatusMessage *msg) { if (msg->m_data.status_value != 0) { qCritical().noquote() << msg->m_data.status_message; shutDownServers(); } else qInfo().noquote() << msg->m_data.status_message; } // this event stops main processing loop of the whole server class ServerStopper : public ACE_Event_Handler { public: ServerStopper(int signum) // when instantiated adds itself to current reactor { ACE_Reactor::instance()->register_handler(signum, this); } // Called when object is signaled by OS. int handle_signal(int, siginfo_t */*s_i*/, ucontext_t */*u_c*/) { shutDownServers(); return 0; } }; bool CreateServers() { static ReloadConfigMessage reload_config; GlobalTimerQueue::instance()->activate(); TIMED_LOG( { g_message_bus.reset(new MessageBus); HandlerLocator::setMessageBus(g_message_bus.get()); g_message_bus->ReadConfigAndRestart(); } ,"Creating message bus"); TIMED_LOG(s_bus_monitor.reset(new MessageBusMonitor),"Starting message bus monitor"); TIMED_LOG(startAuthDBSync(),"Starting auth db service"); TIMED_LOG({ g_auth_server.reset(new AuthServer); g_auth_server->activate(); },"Starting auth service"); // AdminServer::instance()->ReadConfig(); // AdminServer::instance()->Run(); TIMED_LOG(startGameDBSync(1),"Starting game(1) db service"); TIMED_LOG({ g_game_server.reset(new GameServer(1)); g_game_server->activate(); },"Starting game(1) server"); TIMED_LOG({ g_map_server.reset(new MapServer(1)); g_map_server->sett_game_server_owner(1); g_map_server->activate(); },"Starting map server"); qDebug() << "Asking AuthServer to load configuration and begin listening for external connections."; g_auth_server->putq(reload_config.shallow_copy()); qDebug() << "Asking GameServer(0) to load configuration on begin listening for external connections."; g_game_server->putq(reload_config.shallow_copy()); qDebug() << "Asking MapServer to load configuration on begin listening for external connections."; g_map_server->putq(reload_config.shallow_copy()); // server_manger->AddGameServer(game_instance); return true; } std::mutex log_mutex; void segsLogMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { std::lock_guard<std::mutex> lock(log_mutex); static char log_buffer[4096]={0}; static char category_text[256]; log_buffer[0] = 0; category_text[0] = 0; if(strcmp(context.category,"default")!=0) snprintf(category_text,256,"[%s]",context.category); QFile segs_log_target; segs_log_target.setFileName("output.log"); if (!segs_log_target.open(QFile::WriteOnly | QFile::Append)) { fprintf(stderr,"Failed to open log file in write mode, will procede with console only logging"); } QByteArray localMsg = msg.toLocal8Bit(); switch (type) { case QtDebugMsg: snprintf(log_buffer,4096,"%sDebug : %s\n",category_text,localMsg.constData()); break; case QtInfoMsg: // no prefix for informational messages snprintf(log_buffer,4096,"%s: %s\n",category_text,localMsg.constData()); break; case QtWarningMsg: snprintf(log_buffer,4096,"%sWarning : %s\n",category_text,localMsg.constData()); break; case QtCriticalMsg: snprintf(log_buffer,4096,"%sCritical: %s\n",category_text,localMsg.constData()); break; case QtFatalMsg: snprintf(log_buffer,4096,"%sFatal: %s\n",category_text,localMsg.constData()); } fprintf(stdout, "%s", log_buffer); if (type != QtInfoMsg && segs_log_target.isOpen()) { segs_log_target.write(log_buffer); } if (type == QtFatalMsg) { fflush(stdout); segs_log_target.close(); abort(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // End of anonymous namespace /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ACE_INT32 ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { setLoggingFilter(); // Set QT Logging filters qInstallMessageHandler(segsLogMessageOutput); QCoreApplication q_app(argc,argv); QCoreApplication::setOrganizationDomain("segs.nemerle.eu"); QCoreApplication::setOrganizationName("SEGS Project"); QCoreApplication::setApplicationName("segs_server"); QCoreApplication::setApplicationVersion(VersionInfo::getAuthVersion()); QCommandLineParser parser; parser.setApplicationDescription("SEGS - CoX server"); parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({ {{"f","config"}, "Use the provided settings file, default value is <settings.cfg>", "filename","settings.cfg"} }); parser.process(q_app); if(parser.isSet("help")||parser.isSet("version")) return 0; Settings::setSettingsPath(parser.value("config")); // set settings.cfg from args ACE_Sig_Set interesting_signals; interesting_signals.sig_add(SIGINT); interesting_signals.sig_add(SIGHUP); ServerStopper st(SIGINT); // it'll register itself with current reactor, and shut it down on sigint ACE_Reactor::instance()->register_handler(interesting_signals,&st); // Print out startup copyright messages qInfo().noquote() << VersionInfo::getCopyright(); qInfo().noquote() << VersionInfo::getAuthVersion(); qInfo().noquote() << "main"; bool no_err = CreateServers(); if(!no_err) { ACE_Reactor::instance()->end_reactor_event_loop(); return -1; } // process all queued qt messages here. ACE_Time_Value event_processing_delay(0,1000*5); while( !s_event_loop_is_done ) { ACE_Reactor::instance()->handle_events(&event_processing_delay); QCoreApplication::processEvents(); } GlobalTimerQueue::instance()->wait(); g_game_server->wait(); g_map_server->wait(); g_auth_server->wait(); s_bus_monitor->wait(); g_message_bus->wait(); g_game_server.reset(); g_map_server.reset(); g_auth_server.reset(); s_bus_monitor.reset(); g_message_bus.reset(); ACE_Reactor::instance()->handle_events(&event_processing_delay); ACE_Reactor::instance()->remove_handler(interesting_signals); ACE_Reactor::end_event_loop(); return 0; } <|endoftext|>
<commit_before>/** * @file logistic_regression_impl.hpp * @author Sumedh Ghaisas * * Implementation of the LogisticRegression class. This implementation supports * L2-regularization. */ #ifndef __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP #define __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP // In case it hasn't been included yet. #include "logistic_regression.hpp" namespace mlpack { namespace regression { template<template<typename> class OptimizerType> LogisticRegression<OptimizerType>::LogisticRegression( arma::mat& predictors, arma::vec& responses, const double lambda) : predictors(predictors), responses(responses), errorFunction(LogisticRegressionFunction(predictors, responses, lambda)), optimizer(OptimizerType<LogisticRegressionFunction>(errorFunction)), lambda(lambda) { parameters.zeros(predictors.n_rows + 1); } template<template<typename> class OptimizerType> LogisticRegression<OptimizerType>::LogisticRegression( arma::mat& predictors, arma::vec& responses, const arma::mat& initialPoint, const double lambda) : predictors(predictors), responses(responses), errorFunction(LogisticRegressionFunction(predictors, responses)), optimizer(OptimizerType<LogisticRegressionFunction>(errorFunction)), lambda(lambda) { parameters.zeros(predictors.n_rows + 1); } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::LearnModel() { //add rows of ones to predictors arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); double out; Timer::Start("logistic_regression_optimization"); out = optimizer.Optimize(parameters); Timer::Stop("logistic_regression_optimization"); //shed the added rows predictors.shed_row(0); return out; } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::ComputeError( arma::mat& predictors, const arma::vec& responses) { // Here we add the row of ones to the predictors. arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); // double out = errorFunction.Evaluate(predictors, responses, parameters); predictors.shed_row(0); // return out; return 0.0; } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::ComputeAccuracy( arma::mat& predictors, const arma::vec& responses, const double decisionBoundary) { arma::vec tempResponses; Predict(predictors, tempResponses, decisionBoundary); int count = 0; for (size_t i = 0; i < responses.n_rows; i++) if (responses(i, 0) == tempResponses(i, 0)) count++; return (double) (count * 100) / responses.n_rows; } template <template<typename> class OptimizerType> void LogisticRegression<OptimizerType>::Predict( arma::mat& predictors, arma::vec& responses, const double decisionBoundary) { //add rows of ones to predictors arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); responses = arma::floor( errorFunction.getSigmoid(arma::trans(predictors) * parameters) - decisionBoundary * arma::ones<arma::vec>(predictors.n_cols, 1)) + arma::ones<arma::vec>(predictors.n_cols); //shed the added rows predictors.shed_row(0); } }; // namespace regression }; // namespace mlpack #endif // __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP <commit_msg>Break Predict() instead of the whole build.<commit_after>/** * @file logistic_regression_impl.hpp * @author Sumedh Ghaisas * * Implementation of the LogisticRegression class. This implementation supports * L2-regularization. */ #ifndef __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP #define __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP // In case it hasn't been included yet. #include "logistic_regression.hpp" namespace mlpack { namespace regression { template<template<typename> class OptimizerType> LogisticRegression<OptimizerType>::LogisticRegression( arma::mat& predictors, arma::vec& responses, const double lambda) : predictors(predictors), responses(responses), errorFunction(LogisticRegressionFunction(predictors, responses, lambda)), optimizer(OptimizerType<LogisticRegressionFunction>(errorFunction)), lambda(lambda) { parameters.zeros(predictors.n_rows + 1); } template<template<typename> class OptimizerType> LogisticRegression<OptimizerType>::LogisticRegression( arma::mat& predictors, arma::vec& responses, const arma::mat& initialPoint, const double lambda) : predictors(predictors), responses(responses), errorFunction(LogisticRegressionFunction(predictors, responses)), optimizer(OptimizerType<LogisticRegressionFunction>(errorFunction)), lambda(lambda) { parameters.zeros(predictors.n_rows + 1); } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::LearnModel() { //add rows of ones to predictors arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); double out; Timer::Start("logistic_regression_optimization"); out = optimizer.Optimize(parameters); Timer::Stop("logistic_regression_optimization"); //shed the added rows predictors.shed_row(0); return out; } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::ComputeError( arma::mat& predictors, const arma::vec& responses) { // Here we add the row of ones to the predictors. arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); // double out = errorFunction.Evaluate(predictors, responses, parameters); predictors.shed_row(0); // return out; return 0.0; } template <template<typename> class OptimizerType> double LogisticRegression<OptimizerType>::ComputeAccuracy( arma::mat& predictors, const arma::vec& responses, const double decisionBoundary) { arma::vec tempResponses; Predict(predictors, tempResponses, decisionBoundary); int count = 0; for (size_t i = 0; i < responses.n_rows; i++) if (responses(i, 0) == tempResponses(i, 0)) count++; return (double) (count * 100) / responses.n_rows; } template <template<typename> class OptimizerType> void LogisticRegression<OptimizerType>::Predict( arma::mat& predictors, arma::vec& responses, const double decisionBoundary) { //add rows of ones to predictors arma::rowvec ones; ones.ones(predictors.n_cols); predictors.insert_rows(0, ones); // responses = arma::floor( // errorFunction.getSigmoid(arma::trans(predictors) * parameters) - // decisionBoundary * arma::ones<arma::vec>(predictors.n_cols, 1)) + // arma::ones<arma::vec>(predictors.n_cols); //shed the added rows predictors.shed_row(0); } }; // namespace regression }; // namespace mlpack #endif // __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "webkit/glue/plugins/plugin_list.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/string_util.h" #include "base/time.h" #include "net/base/mime_util.h" #include "webkit/default_plugin/plugin_main.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/webkit_glue.h" #include "googleurl/src/gurl.h" namespace NPAPI { base::LazyInstance<PluginList> g_singleton(base::LINKER_INITIALIZED); // static PluginList* PluginList::Singleton() { return g_singleton.Pointer(); } bool PluginList::PluginsLoaded() { AutoLock lock(lock_); return plugins_loaded_; } void PluginList::ResetPluginsLoaded() { AutoLock lock(lock_); plugins_loaded_ = false; } void PluginList::AddExtraPluginPath(const FilePath& plugin_path) { AutoLock lock(lock_); extra_plugin_paths_.push_back(plugin_path); } void PluginList::AddExtraPluginDir(const FilePath& plugin_dir) { AutoLock lock(lock_); extra_plugin_dirs_.push_back(plugin_dir); } void PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) { AutoLock lock(lock_); internal_plugins_.push_back(info); } bool PluginList::ReadPluginInfo(const FilePath &filename, WebPluginInfo* info, const PluginEntryPoints** entry_points) { { AutoLock lock(lock_); for (size_t i = 0; i < internal_plugins_.size(); ++i) { if (filename == internal_plugins_[i].path) { *entry_points = &internal_plugins_[i].entry_points; return CreateWebPluginInfo(internal_plugins_[i], info); } } } // Not an internal plugin. *entry_points = NULL; return PluginLib::ReadWebPluginInfo(filename, info); } bool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi, WebPluginInfo* info) { std::vector<std::string> mime_types, file_extensions; std::vector<std::wstring> descriptions; SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types); SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions); SplitString(pvi.type_descriptions, '|', &descriptions); info->mime_types.clear(); if (mime_types.empty()) return false; info->name = pvi.product_name; info->desc = pvi.file_description; info->version = pvi.file_version; info->path = pvi.path; for (size_t i = 0; i < mime_types.size(); ++i) { WebPluginMimeType mime_type; mime_type.mime_type = StringToLowerASCII(mime_types[i]); if (file_extensions.size() > i) SplitString(file_extensions[i], ',', &mime_type.file_extensions); if (descriptions.size() > i) { mime_type.description = descriptions[i]; // On Windows, the description likely has a list of file extensions // embedded in it (e.g. "SurfWriter file (*.swr)"). Remove an extension // list from the description if it is present. size_t ext = mime_type.description.find(L"(*"); if (ext != std::wstring::npos) { if (ext > 1 && mime_type.description[ext -1] == ' ') ext--; mime_type.description.erase(ext); } } info->mime_types.push_back(mime_type); } return true; } PluginList::PluginList() : plugins_loaded_(false) { PlatformInit(); #if defined(OS_WIN) const PluginVersionInfo default_plugin = { FilePath(kDefaultPluginLibraryName), L"Default Plug-in", L"Provides functionality for installing third-party plug-ins", L"1", L"*", L"", L"", { default_plugin::NP_GetEntryPoints, default_plugin::NP_Initialize, default_plugin::NP_Shutdown } }; internal_plugins_.push_back(default_plugin); #endif } void PluginList::LoadPlugins(bool refresh) { // Don't want to hold the lock while loading new plugins, so we don't block // other methods if they're called on other threads. std::vector<FilePath> extra_plugin_paths; std::vector<FilePath> extra_plugin_dirs; { AutoLock lock(lock_); if (plugins_loaded_ && !refresh) return; extra_plugin_paths = extra_plugin_paths_; extra_plugin_dirs = extra_plugin_dirs_; } base::TimeTicks start_time = base::TimeTicks::Now(); std::vector<WebPluginInfo> new_plugins; std::vector<FilePath> directories_to_scan; GetPluginDirectories(&directories_to_scan); for (size_t i = 0; i < extra_plugin_paths.size(); ++i) LoadPlugin(extra_plugin_paths[i], &new_plugins); for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) { LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins); } for (size_t i = 0; i < directories_to_scan.size(); ++i) { LoadPluginsFromDir(directories_to_scan[i], &new_plugins); } if (webkit_glue::IsDefaultPluginEnabled()) LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins); base::TimeTicks end_time = base::TimeTicks::Now(); base::TimeDelta elapsed = end_time - start_time; DLOG(INFO) << "Loaded plugin list in " << elapsed.InMilliseconds() << " ms."; AutoLock lock(lock_); plugins_ = new_plugins; plugins_loaded_ = true; } void PluginList::LoadPlugin(const FilePath &path, std::vector<WebPluginInfo>* plugins) { WebPluginInfo plugin_info; const PluginEntryPoints* entry_points; if (!ReadPluginInfo(path, &plugin_info, &entry_points)) return; if (!ShouldLoadPlugin(plugin_info, plugins)) return; if (path.value() != kDefaultPluginLibraryName #if defined(OS_WIN) && !defined(NDEBUG) && path.BaseName().value() != L"npspy.dll" // Make an exception for NPSPY #endif ) { for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) { // TODO: don't load global handlers for now. // WebKit hands to the Plugin before it tries // to handle mimeTypes on its own. const std::string &mime_type = plugin_info.mime_types[i].mime_type; if (mime_type == "*" ) return; } } plugins->push_back(plugin_info); } bool PluginList::FindPlugin(const std::string& mime_type, bool allow_wildcard, WebPluginInfo* info) { DCHECK(mime_type == StringToLowerASCII(mime_type)); LoadPlugins(false); AutoLock lock(lock_); for (size_t i = 0; i < plugins_.size(); ++i) { if (SupportsType(plugins_[i], mime_type, allow_wildcard)) { *info = plugins_[i]; return true; } } return false; } bool PluginList::FindPlugin(const GURL &url, std::string* actual_mime_type, WebPluginInfo* info) { LoadPlugins(false); AutoLock lock(lock_); std::string path = url.path(); std::string::size_type last_dot = path.rfind('.'); if (last_dot == std::string::npos) return false; std::string extension = StringToLowerASCII(std::string(path, last_dot+1)); for (size_t i = 0; i < plugins_.size(); ++i) { if (SupportsExtension(plugins_[i], extension, actual_mime_type)) { *info = plugins_[i]; return true; } } return false; } bool PluginList::SupportsType(const WebPluginInfo& info, const std::string &mime_type, bool allow_wildcard) { // Webkit will ask for a plugin to handle empty mime types. if (mime_type.empty()) return false; for (size_t i = 0; i < info.mime_types.size(); ++i) { const WebPluginMimeType& mime_info = info.mime_types[i]; if (net::MatchesMimeType(mime_info.mime_type, mime_type)) { if (!allow_wildcard && mime_info.mime_type == "*") { continue; } return true; } } return false; } bool PluginList::SupportsExtension(const WebPluginInfo& info, const std::string &extension, std::string* actual_mime_type) { for (size_t i = 0; i < info.mime_types.size(); ++i) { const WebPluginMimeType& mime_type = info.mime_types[i]; for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) { if (mime_type.file_extensions[j] == extension) { if (actual_mime_type) *actual_mime_type = mime_type.mime_type; return true; } } } return false; } void PluginList::GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { LoadPlugins(refresh); AutoLock lock(lock_); *plugins = plugins_; } bool PluginList::GetPluginInfo(const GURL& url, const std::string& mime_type, bool allow_wildcard, WebPluginInfo* info, std::string* actual_mime_type) { bool found = FindPlugin(mime_type, allow_wildcard, info); if (!found || (info->path.value() == kDefaultPluginLibraryName)) { WebPluginInfo info2; if (FindPlugin(url, actual_mime_type, &info2)) { found = true; *info = info2; } } return found; } bool PluginList::GetPluginInfoByPath(const FilePath& plugin_path, WebPluginInfo* info) { LoadPlugins(false); AutoLock lock(lock_); for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path == plugin_path) { *info = plugins_[i]; return true; } } return false; } void PluginList::Shutdown() { // TODO } } // namespace NPAPI <commit_msg>Fix registration of internal plugins broken by rev 23501<commit_after>// Copyright (c) 2006-2008 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 "webkit/glue/plugins/plugin_list.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/string_util.h" #include "base/time.h" #include "net/base/mime_util.h" #include "webkit/default_plugin/plugin_main.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_lib.h" #include "webkit/glue/webkit_glue.h" #include "googleurl/src/gurl.h" namespace NPAPI { base::LazyInstance<PluginList> g_singleton(base::LINKER_INITIALIZED); // static PluginList* PluginList::Singleton() { return g_singleton.Pointer(); } bool PluginList::PluginsLoaded() { AutoLock lock(lock_); return plugins_loaded_; } void PluginList::ResetPluginsLoaded() { AutoLock lock(lock_); plugins_loaded_ = false; } void PluginList::AddExtraPluginPath(const FilePath& plugin_path) { AutoLock lock(lock_); extra_plugin_paths_.push_back(plugin_path); } void PluginList::AddExtraPluginDir(const FilePath& plugin_dir) { AutoLock lock(lock_); extra_plugin_dirs_.push_back(plugin_dir); } void PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) { AutoLock lock(lock_); internal_plugins_.push_back(info); } bool PluginList::ReadPluginInfo(const FilePath &filename, WebPluginInfo* info, const PluginEntryPoints** entry_points) { { AutoLock lock(lock_); for (size_t i = 0; i < internal_plugins_.size(); ++i) { if (filename == internal_plugins_[i].path) { *entry_points = &internal_plugins_[i].entry_points; return CreateWebPluginInfo(internal_plugins_[i], info); } } } // Not an internal plugin. *entry_points = NULL; return PluginLib::ReadWebPluginInfo(filename, info); } bool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi, WebPluginInfo* info) { std::vector<std::string> mime_types, file_extensions; std::vector<std::wstring> descriptions; SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types); SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions); SplitString(pvi.type_descriptions, '|', &descriptions); info->mime_types.clear(); if (mime_types.empty()) return false; info->name = pvi.product_name; info->desc = pvi.file_description; info->version = pvi.file_version; info->path = pvi.path; for (size_t i = 0; i < mime_types.size(); ++i) { WebPluginMimeType mime_type; mime_type.mime_type = StringToLowerASCII(mime_types[i]); if (file_extensions.size() > i) SplitString(file_extensions[i], ',', &mime_type.file_extensions); if (descriptions.size() > i) { mime_type.description = descriptions[i]; // On Windows, the description likely has a list of file extensions // embedded in it (e.g. "SurfWriter file (*.swr)"). Remove an extension // list from the description if it is present. size_t ext = mime_type.description.find(L"(*"); if (ext != std::wstring::npos) { if (ext > 1 && mime_type.description[ext -1] == ' ') ext--; mime_type.description.erase(ext); } } info->mime_types.push_back(mime_type); } return true; } PluginList::PluginList() : plugins_loaded_(false) { PlatformInit(); #if defined(OS_WIN) const PluginVersionInfo default_plugin = { FilePath(kDefaultPluginLibraryName), L"Default Plug-in", L"Provides functionality for installing third-party plug-ins", L"1", L"*", L"", L"", { default_plugin::NP_GetEntryPoints, default_plugin::NP_Initialize, default_plugin::NP_Shutdown } }; internal_plugins_.push_back(default_plugin); #endif } void PluginList::LoadPlugins(bool refresh) { // Don't want to hold the lock while loading new plugins, so we don't block // other methods if they're called on other threads. std::vector<FilePath> extra_plugin_paths; std::vector<FilePath> extra_plugin_dirs; std::vector<PluginVersionInfo> internal_plugins; { AutoLock lock(lock_); if (plugins_loaded_ && !refresh) return; extra_plugin_paths = extra_plugin_paths_; extra_plugin_dirs = extra_plugin_dirs_; internal_plugins = internal_plugins_; } base::TimeTicks start_time = base::TimeTicks::Now(); std::vector<WebPluginInfo> new_plugins; std::vector<FilePath> directories_to_scan; GetPluginDirectories(&directories_to_scan); // Load internal plugins first so that, if both an internal plugin and a // "discovered" plugin want to handle the same type, the internal plugin // will have precedence. for (size_t i = 0; i < internal_plugins.size(); ++i) { if (internal_plugins[i].path.value() == kDefaultPluginLibraryName) continue; LoadPlugin(internal_plugins[i].path, &new_plugins); } for (size_t i = 0; i < extra_plugin_paths.size(); ++i) LoadPlugin(extra_plugin_paths[i], &new_plugins); for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) { LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins); } for (size_t i = 0; i < directories_to_scan.size(); ++i) { LoadPluginsFromDir(directories_to_scan[i], &new_plugins); } // Load the default plugin last. if (webkit_glue::IsDefaultPluginEnabled()) LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins); base::TimeTicks end_time = base::TimeTicks::Now(); base::TimeDelta elapsed = end_time - start_time; DLOG(INFO) << "Loaded plugin list in " << elapsed.InMilliseconds() << " ms."; AutoLock lock(lock_); plugins_ = new_plugins; plugins_loaded_ = true; } void PluginList::LoadPlugin(const FilePath &path, std::vector<WebPluginInfo>* plugins) { WebPluginInfo plugin_info; const PluginEntryPoints* entry_points; if (!ReadPluginInfo(path, &plugin_info, &entry_points)) return; if (!ShouldLoadPlugin(plugin_info, plugins)) return; if (path.value() != kDefaultPluginLibraryName #if defined(OS_WIN) && !defined(NDEBUG) && path.BaseName().value() != L"npspy.dll" // Make an exception for NPSPY #endif ) { for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) { // TODO: don't load global handlers for now. // WebKit hands to the Plugin before it tries // to handle mimeTypes on its own. const std::string &mime_type = plugin_info.mime_types[i].mime_type; if (mime_type == "*" ) return; } } plugins->push_back(plugin_info); } bool PluginList::FindPlugin(const std::string& mime_type, bool allow_wildcard, WebPluginInfo* info) { DCHECK(mime_type == StringToLowerASCII(mime_type)); LoadPlugins(false); AutoLock lock(lock_); for (size_t i = 0; i < plugins_.size(); ++i) { if (SupportsType(plugins_[i], mime_type, allow_wildcard)) { *info = plugins_[i]; return true; } } return false; } bool PluginList::FindPlugin(const GURL &url, std::string* actual_mime_type, WebPluginInfo* info) { LoadPlugins(false); AutoLock lock(lock_); std::string path = url.path(); std::string::size_type last_dot = path.rfind('.'); if (last_dot == std::string::npos) return false; std::string extension = StringToLowerASCII(std::string(path, last_dot+1)); for (size_t i = 0; i < plugins_.size(); ++i) { if (SupportsExtension(plugins_[i], extension, actual_mime_type)) { *info = plugins_[i]; return true; } } return false; } bool PluginList::SupportsType(const WebPluginInfo& info, const std::string &mime_type, bool allow_wildcard) { // Webkit will ask for a plugin to handle empty mime types. if (mime_type.empty()) return false; for (size_t i = 0; i < info.mime_types.size(); ++i) { const WebPluginMimeType& mime_info = info.mime_types[i]; if (net::MatchesMimeType(mime_info.mime_type, mime_type)) { if (!allow_wildcard && mime_info.mime_type == "*") { continue; } return true; } } return false; } bool PluginList::SupportsExtension(const WebPluginInfo& info, const std::string &extension, std::string* actual_mime_type) { for (size_t i = 0; i < info.mime_types.size(); ++i) { const WebPluginMimeType& mime_type = info.mime_types[i]; for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) { if (mime_type.file_extensions[j] == extension) { if (actual_mime_type) *actual_mime_type = mime_type.mime_type; return true; } } } return false; } void PluginList::GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { LoadPlugins(refresh); AutoLock lock(lock_); *plugins = plugins_; } bool PluginList::GetPluginInfo(const GURL& url, const std::string& mime_type, bool allow_wildcard, WebPluginInfo* info, std::string* actual_mime_type) { bool found = FindPlugin(mime_type, allow_wildcard, info); if (!found || (info->path.value() == kDefaultPluginLibraryName)) { WebPluginInfo info2; if (FindPlugin(url, actual_mime_type, &info2)) { found = true; *info = info2; } } return found; } bool PluginList::GetPluginInfoByPath(const FilePath& plugin_path, WebPluginInfo* info) { LoadPlugins(false); AutoLock lock(lock_); for (size_t i = 0; i < plugins_.size(); ++i) { if (plugins_[i].path == plugin_path) { *info = plugins_[i]; return true; } } return false; } void PluginList::Shutdown() { // TODO } } // namespace NPAPI <|endoftext|>
<commit_before>// // eventmodel.cpp // Luves // // Created by hashdata on 16/9/30. // Copyright © 2016年 hashdata. All rights reserved. // #include "eventmodel.h" namespace luves { // //IO复用模型 // std::map<int, Channel *> EventModel::channel_fd_map_; void EventModel::AddChannel(Channel *channel) { if (channel->GetIsListen()) //获取listen套接字 listen_fd_=channel->GetFd(); channel_fd_map_[channel->GetFd()]=channel; EV_SET(&monitor_events[monitor_nums_], channel->GetFd(),channel->GetEvent(), EV_ADD|EV_ENABLE, 0, 0, NULL); monitor_nums_++; } void EventModel::DeleteChannel(Channel * channel) { channel_fd_map_.erase(channel->GetFd()); EV_SET(&monitor_events[monitor_nums_], channel->GetFd(),channel->GetEvent(), EV_DELETE|EV_ENABLE, 0, 0, NULL); monitor_nums_--; } void EventModel::UpdateChannel(Channel * channel) { } void EventModel::RunModel(int64_t waittime) { //struct timespec time_out={static_cast<__darwin_time_t>(0.001*waittime),0}; int nev=kevent(kq_,monitor_events,monitor_nums_,trigger_events,1024,NULL); trigger_channel_list_.clear(); for (int i=0; i<nev; i++) { if (trigger_events[i].flags & EV_ERROR) { ERROR_LOG("kqueue return error %d %s",errno,strerror(errno)); //kqueue error exit(1); } else if ((trigger_events[i].ident==listen_fd_ )||((trigger_events[i].flags & EVFILT_READ)&& is_hsha_==false)) //default or connnect coming { auto event=&trigger_events[i]; auto channel=channel_fd_map_.find(int(event->ident))->second; channel->SetActiveEvent(event->flags); trigger_channel_list_.push_back(channel_fd_map_.find(int(event->ident))->second); } else if (trigger_events[i].flags & EVFILT_READ && is_hsha_) //the server of model is hsha { ThreadsPool::AddTask(int(trigger_events[i].ident)); } } } ChannelList & EventModel::GetTriggerPtr() { return trigger_channel_list_; } } <commit_msg>Delete eventmodel.cpp<commit_after><|endoftext|>
<commit_before>#include "yaml-cpp/yaml.h" #include "yaml-cpp/eventhandler.h" #include <fstream> #include <iostream> #include <vector> struct Params { bool hasFile; std::string fileName; }; Params ParseArgs(int argc, char **argv) { Params p; std::vector<std::string> args(argv + 1, argv + argc); return p; } class NullEventHandler: public YAML::EventHandler { public: virtual void OnDocumentStart(const YAML::Mark&) {} virtual void OnDocumentEnd() {} virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {} virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {} virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {} virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnSequenceEnd() {} virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnMapEnd() {} }; void parse(std::istream& input) { try { YAML::Parser parser(input); YAML::Node doc; while(parser.GetNextDocument(doc)) { YAML::Emitter emitter; emitter << doc; std::cout << emitter.c_str() << "\n"; } } catch(const YAML::Exception& e) { std::cerr << e.what() << "\n"; } } int main(int argc, char **argv) { Params p = ParseArgs(argc, argv); if(argc > 1) { std::ifstream fin; fin.open(argv[1]); parse(fin); } else { parse(std::cin); } return 0; } <commit_msg>Added old parse utility<commit_after>#include "yaml-cpp/yaml.h" #include "yaml-cpp/eventhandler.h" #include <fstream> #include <iostream> #include <vector> struct Params { bool hasFile; std::string fileName; }; Params ParseArgs(int argc, char **argv) { Params p; std::vector<std::string> args(argv + 1, argv + argc); return p; } class NullEventHandler: public YAML::EventHandler { public: virtual void OnDocumentStart(const YAML::Mark&) {} virtual void OnDocumentEnd() {} virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {} virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {} virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {} virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnSequenceEnd() {} virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnMapEnd() {} }; void parse(std::istream& input) { try { YAML::Node doc = YAML::Load(input); std::cout << doc << "\n"; } catch(const YAML::Exception& e) { std::cerr << e.what() << "\n"; } } int main(int argc, char **argv) { Params p = ParseArgs(argc, argv); if(argc > 1) { std::ifstream fin; fin.open(argv[1]); parse(fin); } else { parse(std::cin); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "wifi_tests.h" using namespace utest::v1; #if defined(MBED_CONF_APP_WIFI_SECURE_SSID) void wifi_connect_params_channel_fail(void) { WiFiInterface *wifi = get_interface(); if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) { TEST_IGNORE_MESSAGE("set_channel() not supported"); return; } nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_UNSECURE); TEST_ASSERT(error == NSAPI_ERROR_CONNECTION_TIMEOUT || error == NSAPI_ERROR_NO_CONNECTION); wifi->set_channel(0); } #endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID) <commit_msg>Fix WIFI_CONNECT_PARAMS_CHANNEL_FAIL testcase.<commit_after>/* * Copyright (c) 2017, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "wifi_tests.h" using namespace utest::v1; #if defined(MBED_CONF_APP_WIFI_SECURE_SSID) void wifi_connect_params_channel_fail(void) { WiFiInterface *wifi = get_interface(); if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) { TEST_IGNORE_MESSAGE("set_channel() not supported"); return; } uint8_t wrong_channel = 1 + (MBED_CONF_APP_WIFI_CH_SECURE%10); nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), wrong_channel); TEST_ASSERT(error == NSAPI_ERROR_CONNECTION_TIMEOUT || error == NSAPI_ERROR_NO_CONNECTION); wifi->set_channel(0); } #endif // defined(MBED_CONF_APP_WIFI_SECURE_SSID) <|endoftext|>
<commit_before>/* * Copyright (c) 2019, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if ((!defined(TARGET_PSA)) || (!defined(MBEDTLS_PSA_CRYPTO_C)) || (!defined(COMPONENT_PSA_SRV_IPC))) #error [NOT_SUPPORTED] These tests can run only on SPM-enabled targets and where Mbed Crypto is ON - skipping. #endif #include <stdio.h> #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "psa/crypto.h" #include "entropy.h" #include "entropy_poll.h" #include "test_partition_proxy.h" #include "psa/lifecycle.h" using namespace utest::v1; #if defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) #if !defined(MAX) #define MAX(a,b) (((a)>(b))?(a):(b)) #endif #define MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE \ MAX(MBEDTLS_ENTROPY_MIN_PLATFORM, MBEDTLS_ENTROPY_BLOCK_SIZE) void inject_entropy() { uint8_t seed[MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE] = { 0 }; for (int i = 0; i < MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE; ++i) { seed[i] = i; } mbedtls_psa_inject_entropy(seed, MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE); } #endif // defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) utest::v1::status_t case_setup_handler(const Case *const source, const size_t index_of_case) { psa_status_t status = mbed_psa_reboot_and_request_new_security_state(PSA_LIFECYCLE_ASSEMBLY_AND_TEST); TEST_ASSERT_EQUAL(PSA_SUCCESS, status); status = psa_crypto_init(); #if defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) if (status == PSA_ERROR_INSUFFICIENT_ENTROPY) { inject_entropy(); status = psa_crypto_init(); } #endif TEST_ASSERT_EQUAL(PSA_SUCCESS, status); return greentea_case_setup_handler(source, index_of_case); } utest::v1::status_t case_teardown_handler(const Case *const source, const size_t passed, const size_t failed, const failure_t failure) { psa_status_t status = mbed_psa_reboot_and_request_new_security_state(PSA_LIFECYCLE_ASSEMBLY_AND_TEST); TEST_ASSERT_EQUAL(PSA_SUCCESS, status); mbedtls_psa_crypto_free(); return greentea_case_teardown_handler(source, passed, failed, failure); } utest::v1::status_t test_setup(const size_t number_of_cases) { #ifndef NO_GREENTEA GREENTEA_SETUP(120, "default_auto"); #endif return verbose_test_setup_handler(number_of_cases); } int main(void) { return (1); } <commit_msg>Add acl test - open other partitions' key<commit_after>/* * Copyright (c) 2019, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if ((!defined(TARGET_PSA)) || (!defined(MBEDTLS_PSA_CRYPTO_C)) || (!defined(COMPONENT_PSA_SRV_IPC))) #error [NOT_SUPPORTED] These tests can run only on SPM-enabled targets and where Mbed Crypto is ON - skipping. #endif #include <stdio.h> #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "psa/crypto.h" #include "entropy.h" #include "entropy_poll.h" #include "test_partition_proxy.h" #include "psa/lifecycle.h" using namespace utest::v1; #if defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) #if !defined(MAX) #define MAX(a,b) (((a)>(b))?(a):(b)) #endif #define MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE \ MAX(MBEDTLS_ENTROPY_MIN_PLATFORM, MBEDTLS_ENTROPY_BLOCK_SIZE) void inject_entropy() { uint8_t seed[MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE] = { 0 }; for (int i = 0; i < MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE; ++i) { seed[i] = i; } mbedtls_psa_inject_entropy(seed, MBEDTLS_PSA_INJECT_ENTROPY_MIN_SIZE); } #endif // defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) void test_open_other_partition_key(void) { static const psa_key_id_t key_id = 999; static const psa_key_type_t key_type = PSA_KEY_TYPE_AES; static const psa_key_usage_t key_usage = PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT; static const psa_algorithm_t key_alg = PSA_ALG_CBC_NO_PADDING; static const size_t key_bits = 128; psa_key_handle_t key_handle = 0; /* via test partition - create a key, set key policy, generate key material and close */ TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_create_persistent_key(key_id, &key_handle)); TEST_ASSERT_NOT_EQUAL(0, key_handle); TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_set_key_policy(key_handle, key_usage, key_alg)); TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_generate_key(key_handle, key_type, key_bits)); TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_close_key(key_handle)); /* via test partition - reopen the key created by the test partition */ key_handle = 0; TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_open_persistent_key(key_id, &key_handle)); TEST_ASSERT_NOT_EQUAL(0, key_handle); /* via test partition - close the key created by the test partition */ TEST_ASSERT_EQUAL(PSA_SUCCESS, test_partition_crypto_close_key(key_handle)); /* try to open the key created by the test partition */ TEST_ASSERT_EQUAL(PSA_ERROR_DOES_NOT_EXIST, psa_open_key(PSA_KEY_LIFETIME_PERSISTENT, key_id, &key_handle)); } utest::v1::status_t case_setup_handler(const Case *const source, const size_t index_of_case) { psa_status_t status = mbed_psa_reboot_and_request_new_security_state(PSA_LIFECYCLE_ASSEMBLY_AND_TEST); TEST_ASSERT_EQUAL(PSA_SUCCESS, status); status = psa_crypto_init(); #if defined(MBEDTLS_ENTROPY_NV_SEED) || defined(COMPONENT_PSA_SRV_IPC) if (status == PSA_ERROR_INSUFFICIENT_ENTROPY) { inject_entropy(); status = psa_crypto_init(); } #endif TEST_ASSERT_EQUAL(PSA_SUCCESS, status); return greentea_case_setup_handler(source, index_of_case); } utest::v1::status_t case_teardown_handler(const Case *const source, const size_t passed, const size_t failed, const failure_t failure) { psa_status_t status = mbed_psa_reboot_and_request_new_security_state(PSA_LIFECYCLE_ASSEMBLY_AND_TEST); TEST_ASSERT_EQUAL(PSA_SUCCESS, status); mbedtls_psa_crypto_free(); return greentea_case_teardown_handler(source, passed, failed, failure); } utest::v1::status_t test_setup(const size_t number_of_cases) { #ifndef NO_GREENTEA GREENTEA_SETUP(120, "default_auto"); #endif return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("open other partitions' key", case_setup_handler, test_open_other_partition_key, case_teardown_handler), }; Specification specification(test_setup, cases); int main(void) { return !Harness::run(specification); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.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 above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "itkFixedArray.h" #include "otbLandsatTMIndices.h" int otbLandsatTMIndexVis(int argc, char * argv[]) { typedef double OutputPixelType; typedef itk::FixedArray< double, 8 > InputPixelType; typedef otb::Functor::LandsatTM::Vis<InputPixelType, OutputPixelType> FunctorType; FunctorType visFunct = FunctorType(); double TM1 = (::atof(argv[1])); double TM2 = (::atof(argv[2])); double TM3 = (::atof(argv[3])); double TM4 = (::atof(argv[4])); double TM5 = (::atof(argv[5])); double TM61 = (::atof(argv[6])); double TM62 = (::atof(argv[7])); double TM7 = (::atof(argv[8])); double goodResult = (TM1+TM2+TM3)/3.0; std::cout << goodResult ; InputPixelType pixel; pixel[0] = TM1; pixel[1] = TM2; pixel[2] = TM3; pixel[3] = TM4; pixel[4] = TM5; pixel[5] = TM61; pixel[6] = TM62; pixel[7] = TM7; double result = visFunct(pixel); std::cout << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; return EXIT_SUCCESS; } <commit_msg>TEST: Landsat TM MIRTIR index<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.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 above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "itkFixedArray.h" #include "otbLandsatTMIndices.h" int otbLandsatTMIndexMIRTIR(int argc, char * argv[]) { typedef double OutputPixelType; typedef itk::FixedArray< double, 8 > InputPixelType; typedef otb::Functor::LandsatTM::MIRTIR<InputPixelType, OutputPixelType> FunctorType; FunctorType mirtirFunct = FunctorType(); double TM1 = (::atof(argv[1])); double TM2 = (::atof(argv[2])); double TM3 = (::atof(argv[3])); double TM4 = (::atof(argv[4])); double TM5 = (::atof(argv[5])); double TM61 = (::atof(argv[6])); double TM62 = (::atof(argv[7])); double TM7 = (::atof(argv[8])); double goodResult = (1-TM5)*TM62; std::cout << goodResult ; InputPixelType pixel; pixel[0] = TM1; pixel[1] = TM2; pixel[2] = TM3; pixel[3] = TM4; pixel[4] = TM5; pixel[5] = TM61; pixel[6] = TM62; pixel[7] = TM7; double result = mirtirFunct(pixel); std::cout << " " << result << std::endl; if( result!=goodResult ) return EXIT_FAILURE; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "amftest.hpp" #include "amf.hpp" #include "types/amfarray.hpp" #include "types/amfdouble.hpp" #include "types/amfinteger.hpp" #include "types/amfobject.hpp" TEST(ArraySerializationTest, EmptyArray) { AmfArray array; isEqual(v8 { 0x09, 0x01, 0x01 }, array); } TEST(ArraySerializationTest, StrictIntArray) { AmfInteger v0(0); AmfInteger v1(1); AmfInteger v2(2); AmfInteger v3(3); std::vector<AmfInteger> dense {{ v0, v1, v2, v3 }}; AmfArray array(dense); isEqual(v8 { 0x09, 0x09, 0x01, 0x04, 0x00, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03 }, array); } TEST(ArraySerializationTest, StrictMixedArray) { AmfInteger v0(0); AmfString v1("value"); AmfDouble v2(3.1); AmfObjectTraits traits("", true, false); AmfObject v3(traits); AmfArray array; array.push_back(v0); array.push_back(v1); array.push_back(v2); array.push_back(v3); isEqual(v8 { 0x09, 0x09, 0x01, 0x04, 0x00, 0x06, 0x0b, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x05, 0x40, 0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0x0a, 0x0b, 0x01, 0x01 }, array); } TEST(ArraySerializationTest, AssociativeOnlyArray) { std::map<std::string, AmfInteger> sparse; sparse["bar"] = AmfInteger(17); sparse["foo"] = AmfInteger(0); AmfArray array(std::vector<AmfInteger> { }, sparse); isEqual(v8 { 0x09, // AMF_ARRAY 0x01, // 0 dense elements // assoc-values 0x07, 0x62, 0x61, 0x72, // UTF-8-vr "bar" 0x04, 0x11, // AmfInteger 17 0x07, 0x66, 0x6f, 0x6f, // UTF-8-vr "foo" 0x04, 0x00, // AmfInteger 0 0x01 // end of assoc-values }, array); } TEST(ArraySerializationTest, AssociativeDenseArray) { std::map<std::string, AmfInteger> sparse; sparse["sparseVal"] = AmfInteger(0xbeef); AmfString v("foobar"); std::vector<AmfString> vec { v }; AmfArray array(vec, sparse); isEqual(v8 { 0x09, // AMF_ARRAY 0x03, // 1 dense element // assoc-values // UTF-8-vr "sparseVal" 0x13, 0x73, 0x70, 0x61, 0x72, 0x73, 0x65, 0x56, 0x61, 0x6c, // AmfInteger 0xbeef 0x04, 0x82, 0xfd, 0x6f, 0x01, // end of assoc-values // dense elements // AmfString "foobar" 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, }, array); } TEST(ArraySerializationTest, AssociativeDenseArrayUtilityFunctions) { AmfInteger v0(0xbeef); AmfString v1("foobar"); AmfArray array; array.push_back(v1); array.insert("sparseVal", v0); isEqual(v8 { 0x09, // AMF_ARRAY 0x03, // 1 dense element // assoc-values // UTF-8-vr "sparseVal" 0x13, 0x73, 0x70, 0x61, 0x72, 0x73, 0x65, 0x56, 0x61, 0x6c, // AmfInteger 0xbeef 0x04, 0x82, 0xfd, 0x6f, 0x01, // end of assoc-values // dense elements // AmfString "foobar" 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, }, array); } <commit_msg>Add testcase for nested arrays.<commit_after>#include "amftest.hpp" #include "amf.hpp" #include "types/amfarray.hpp" #include "types/amfdouble.hpp" #include "types/amfinteger.hpp" #include "types/amfobject.hpp" TEST(ArraySerializationTest, EmptyArray) { AmfArray array; isEqual(v8 { 0x09, 0x01, 0x01 }, array); } TEST(ArraySerializationTest, StrictIntArray) { AmfInteger v0(0); AmfInteger v1(1); AmfInteger v2(2); AmfInteger v3(3); std::vector<AmfInteger> dense {{ v0, v1, v2, v3 }}; AmfArray array(dense); isEqual(v8 { 0x09, 0x09, 0x01, 0x04, 0x00, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03 }, array); } TEST(ArraySerializationTest, StrictMixedArray) { AmfInteger v0(0); AmfString v1("value"); AmfDouble v2(3.1); AmfObjectTraits traits("", true, false); AmfObject v3(traits); AmfArray array; array.push_back(v0); array.push_back(v1); array.push_back(v2); array.push_back(v3); isEqual(v8 { 0x09, 0x09, 0x01, 0x04, 0x00, 0x06, 0x0b, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x05, 0x40, 0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcd, 0x0a, 0x0b, 0x01, 0x01 }, array); } TEST(ArraySerializationTest, AssociativeOnlyArray) { std::map<std::string, AmfInteger> sparse; sparse["bar"] = AmfInteger(17); sparse["foo"] = AmfInteger(0); AmfArray array(std::vector<AmfInteger> { }, sparse); isEqual(v8 { 0x09, // AMF_ARRAY 0x01, // 0 dense elements // assoc-values 0x07, 0x62, 0x61, 0x72, // UTF-8-vr "bar" 0x04, 0x11, // AmfInteger 17 0x07, 0x66, 0x6f, 0x6f, // UTF-8-vr "foo" 0x04, 0x00, // AmfInteger 0 0x01 // end of assoc-values }, array); } TEST(ArraySerializationTest, AssociativeDenseArray) { std::map<std::string, AmfInteger> sparse; sparse["sparseVal"] = AmfInteger(0xbeef); AmfString v("foobar"); std::vector<AmfString> vec { v }; AmfArray array(vec, sparse); isEqual(v8 { 0x09, // AMF_ARRAY 0x03, // 1 dense element // assoc-values // UTF-8-vr "sparseVal" 0x13, 0x73, 0x70, 0x61, 0x72, 0x73, 0x65, 0x56, 0x61, 0x6c, // AmfInteger 0xbeef 0x04, 0x82, 0xfd, 0x6f, 0x01, // end of assoc-values // dense elements // AmfString "foobar" 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, }, array); } TEST(ArraySerializationTest, AssociativeDenseArrayUtilityFunctions) { AmfInteger v0(0xbeef); AmfString v1("foobar"); AmfArray array; array.push_back(v1); array.insert("sparseVal", v0); isEqual(v8 { 0x09, // AMF_ARRAY 0x03, // 1 dense element // assoc-values // UTF-8-vr "sparseVal" 0x13, 0x73, 0x70, 0x61, 0x72, 0x73, 0x65, 0x56, 0x61, 0x6c, // AmfInteger 0xbeef 0x04, 0x82, 0xfd, 0x6f, 0x01, // end of assoc-values // dense elements // AmfString "foobar" 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, }, array); } TEST(ArraySerializationTest, ArrayOfArrays) { AmfInteger v0(0xbeef); AmfString v1("foobar"); AmfArray array; array.push_back(v0); array.push_back(v1); AmfArray outerArray; outerArray.push_back(array); outerArray.push_back(array); isEqual(v8 { 0x09, 0x05, 0x01, 0x09, 0x05, 0x01, 0x04, 0x82, 0xfd, 0x6f, 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x09, 0x05, 0x01, 0x04, 0x82, 0xfd, 0x6f, 0x06, 0x0d, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72 }, outerArray); } <|endoftext|>
<commit_before>// codegen #include <nan.h> using node::ObjectWrap; using namespace v8; #include <iostream> #include <string> #include <map> #include <vector> #include "codegen.h" class TypeWrapper : public ObjectWrap { TypeWrapper(TypeHandle *t) : Type(t) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall() || args.Length() == 0 || !args[0]->IsExternal()) { return NanThrowError("Cannot instantiate type directly, use factory"); } Handle<External> handle = Handle<External>::Cast(args[0]); TypeHandle *t = static_cast<TypeHandle *>(handle->Value()); TypeWrapper *instance = new TypeWrapper(t); instance->Wrap(args.This()); NanReturnValue(args.This()); } static NAN_METHOD(ToString) { NanScope(); TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(args.This()); std::string name = wrapper->Type->toString(); NanReturnValue(NanNew(name)); } static Handle<Value> wrapType(TypeHandle *type) { NanEscapableScope(); Handle<Value> argv[1] = { NanNew<External>((void *)type) }; return NanEscapeScope(NanNew(constructor)->NewInstance(1, argv)); } public: TypeHandle *Type; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(TypeWrapper::New); tmpl->SetClassName(NanNew<String>("Type")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tmpl, "toString", TypeWrapper::ToString); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } static NAN_METHOD(GetVoidTy) { NanScope(); NanReturnValue(wrapType(new VoidTypeHandle())); } static NAN_METHOD(GetFunctionTy) { NanScope(); TypeHandle *returns; std::vector<TypeHandle *> takes; if (args.Length() == 0) { returns = new VoidTypeHandle(); } else { Local<Object> handle = args[0]->ToObject(); if (!NanHasInstance(prototype, handle)) { return NanThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); returns = wrapper->Type; } for (unsigned i = 1, e = args.Length(); i < e; i += 1) { Local<Object> handle = args[i]->ToObject(); if (!NanHasInstance(prototype, handle)) { return NanThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); takes.push_back(wrapper->Type); } NanReturnValue(wrapType(new FunctionTypeHandle(returns, takes))); } }; class FunctionBuilderWrapper : public ObjectWrap { explicit FunctionBuilderWrapper(FunctionBuilder *builder) : Builder(builder) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall() || args.Length() == 0 || !args[0]->IsExternal()) { return NanThrowError("Cannot instantiate type directly, use factory"); } Handle<External> handle = Handle<External>::Cast(args[0]); FunctionBuilder *fb = static_cast<FunctionBuilder *>(handle->Value()); FunctionBuilderWrapper *instance = new FunctionBuilderWrapper(fb); instance->Wrap(args.This()); NanReturnValue(args.This()); } public: FunctionBuilder *Builder; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { NanScope(); Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(FunctionBuilderWrapper::New); tmpl->SetClassName(NanNew("FunctionBuilder")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } }; class CodeUnitWrapper : public ObjectWrap { explicit CodeUnitWrapper(CodeUnit *unit) : Unit(unit) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall()) { const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = NanNew(constructor); NanReturnValue(cons->NewInstance(argc, argv)); } else { if (!args[0]->IsString()) { return NanThrowError("Must provide file name."); } Local<String> filename = args[0].As<String>(); String::Utf8Value encoded(filename); CodeUnit *unit = new CodeUnit(*encoded); CodeUnitWrapper *wrapper = new CodeUnitWrapper(unit); wrapper->Wrap(args.This()); NanReturnValue(args.This()); } } void dumpModule() { Unit->dumpModule(); } static NAN_METHOD(Dump) { NanScope(); CodeUnitWrapper *self = ObjectWrap::Unwrap<CodeUnitWrapper>(args.This()); self->dumpModule(); NanReturnUndefined(); } static NAN_METHOD(MakeFunction) { NanEscapableScope(); CodeUnitWrapper *self = ObjectWrap::Unwrap<CodeUnitWrapper>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return NanThrowError("Must provide function name"); } Local<String> fnname = args[0].As<String>(); String::Utf8Value encoded(fnname); if (args.Length() == 1) { return NanThrowError("Must provide function type"); } Local<Object> handle = args[1]->ToObject(); if (!NanHasInstance(TypeWrapper::prototype, handle)) { return NanThrowError("Must provide function type"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); FunctionBuilder *builder = self->Unit->MakeFunction(*encoded, wrapper->Type); if (!builder) { return NanThrowError("Unable to create function (is name unique?)"); } Handle<Value> argv[1] = { NanNew<External>((void *)builder) }; NanReturnValue(NanEscapeScope(NanNew(FunctionBuilderWrapper::constructor)->NewInstance(1, argv))); } public: CodeUnit *Unit; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { NanScope(); Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(CodeUnitWrapper::New); tmpl->SetClassName(NanNew<String>("CodeUnit")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tmpl, "dump", CodeUnitWrapper::Dump); NODE_SET_PROTOTYPE_METHOD(tmpl, "makeFunction", CodeUnitWrapper::MakeFunction); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } }; Persistent<FunctionTemplate> FunctionBuilderWrapper::prototype; Persistent<Function> FunctionBuilderWrapper::constructor; Persistent<FunctionTemplate> TypeWrapper::prototype; Persistent<Function> TypeWrapper::constructor; Persistent<FunctionTemplate> CodeUnitWrapper::prototype; Persistent<Function> CodeUnitWrapper::constructor; void Init(Handle<Object> exports, Handle<Object> module) { TypeWrapper::Init(); CodeUnitWrapper::Init(); FunctionBuilderWrapper::Init(); Local<Function> getVoidTy = NanNew<Function>(TypeWrapper::GetVoidTy); exports->Set(NanNew<String>("getVoidTy"), getVoidTy); Local<Function> getFunctionTy = NanNew<Function>(TypeWrapper::GetFunctionTy); exports->Set(NanNew<String>("getFunctionTy"), getFunctionTy); Local<Function> codeUnit = NanNew(CodeUnitWrapper::constructor); exports->Set(NanNew<String>("CodeUnit"), codeUnit); } NODE_MODULE(codegen, Init) <commit_msg>fix return<commit_after>// codegen #include <nan.h> using node::ObjectWrap; using namespace v8; #include <iostream> #include <string> #include <map> #include <vector> #include "codegen.h" class TypeWrapper : public ObjectWrap { TypeWrapper(TypeHandle *t) : Type(t) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall() || args.Length() == 0 || !args[0]->IsExternal()) { return NanThrowError("Cannot instantiate type directly, use factory"); } Handle<External> handle = Handle<External>::Cast(args[0]); TypeHandle *t = static_cast<TypeHandle *>(handle->Value()); TypeWrapper *instance = new TypeWrapper(t); instance->Wrap(args.This()); NanReturnValue(args.This()); } static NAN_METHOD(ToString) { NanScope(); TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(args.This()); std::string name = wrapper->Type->toString(); NanReturnValue(NanNew(name)); } static Handle<Value> wrapType(TypeHandle *type) { NanEscapableScope(); Handle<Value> argv[1] = { NanNew<External>((void *)type) }; return NanEscapeScope(NanNew(constructor)->NewInstance(1, argv)); } public: TypeHandle *Type; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(TypeWrapper::New); tmpl->SetClassName(NanNew<String>("Type")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tmpl, "toString", TypeWrapper::ToString); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } static NAN_METHOD(GetVoidTy) { NanScope(); NanReturnValue(wrapType(new VoidTypeHandle())); } static NAN_METHOD(GetFunctionTy) { NanScope(); TypeHandle *returns; std::vector<TypeHandle *> takes; if (args.Length() == 0) { returns = new VoidTypeHandle(); } else { Local<Object> handle = args[0]->ToObject(); if (!NanHasInstance(prototype, handle)) { return NanThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); returns = wrapper->Type; } for (unsigned i = 1, e = args.Length(); i < e; i += 1) { Local<Object> handle = args[i]->ToObject(); if (!NanHasInstance(prototype, handle)) { return NanThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); takes.push_back(wrapper->Type); } NanReturnValue(wrapType(new FunctionTypeHandle(returns, takes))); } }; class FunctionBuilderWrapper : public ObjectWrap { explicit FunctionBuilderWrapper(FunctionBuilder *builder) : Builder(builder) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall() || args.Length() == 0 || !args[0]->IsExternal()) { return NanThrowError("Cannot instantiate type directly, use factory"); } Handle<External> handle = Handle<External>::Cast(args[0]); FunctionBuilder *fb = static_cast<FunctionBuilder *>(handle->Value()); FunctionBuilderWrapper *instance = new FunctionBuilderWrapper(fb); instance->Wrap(args.This()); NanReturnValue(args.This()); } public: FunctionBuilder *Builder; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { NanScope(); Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(FunctionBuilderWrapper::New); tmpl->SetClassName(NanNew("FunctionBuilder")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } }; class CodeUnitWrapper : public ObjectWrap { explicit CodeUnitWrapper(CodeUnit *unit) : Unit(unit) {} static NAN_METHOD(New) { NanScope(); if (!args.IsConstructCall()) { const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = NanNew(constructor); NanReturnValue(cons->NewInstance(argc, argv)); } else { if (!args[0]->IsString()) { return NanThrowError("Must provide file name."); } Local<String> filename = args[0].As<String>(); String::Utf8Value encoded(filename); CodeUnit *unit = new CodeUnit(*encoded); CodeUnitWrapper *wrapper = new CodeUnitWrapper(unit); wrapper->Wrap(args.This()); NanReturnValue(args.This()); } } void dumpModule() { Unit->dumpModule(); } static NAN_METHOD(Dump) { NanScope(); CodeUnitWrapper *self = ObjectWrap::Unwrap<CodeUnitWrapper>(args.This()); self->dumpModule(); NanReturnUndefined(); } static NAN_METHOD(MakeFunction) { NanEscapableScope(); CodeUnitWrapper *self = ObjectWrap::Unwrap<CodeUnitWrapper>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return NanThrowError("Must provide function name"); } Local<String> fnname = args[0].As<String>(); String::Utf8Value encoded(fnname); if (args.Length() == 1) { return NanThrowError("Must provide function type"); } Local<Object> handle = args[1]->ToObject(); if (!NanHasInstance(TypeWrapper::prototype, handle)) { return NanThrowError("Must provide function type"); } TypeWrapper *wrapper = ObjectWrap::Unwrap<TypeWrapper>(handle); FunctionBuilder *builder = self->Unit->MakeFunction(*encoded, wrapper->Type); if (!builder) { return NanThrowError("Unable to create function (is name unique?)"); } Handle<Value> argv[1] = { NanNew<External>((void *)builder) }; NanReturnValue(NanNew(FunctionBuilderWrapper::constructor)->NewInstance(1, argv)); } public: CodeUnit *Unit; static Persistent<FunctionTemplate> prototype; static Persistent<Function> constructor; static void Init() { NanScope(); Local<FunctionTemplate> tmpl = NanNew<FunctionTemplate>(CodeUnitWrapper::New); tmpl->SetClassName(NanNew<String>("CodeUnit")); tmpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tmpl, "dump", CodeUnitWrapper::Dump); NODE_SET_PROTOTYPE_METHOD(tmpl, "makeFunction", CodeUnitWrapper::MakeFunction); NanAssignPersistent(prototype, tmpl); NanAssignPersistent(constructor, tmpl->GetFunction()); } }; Persistent<FunctionTemplate> FunctionBuilderWrapper::prototype; Persistent<Function> FunctionBuilderWrapper::constructor; Persistent<FunctionTemplate> TypeWrapper::prototype; Persistent<Function> TypeWrapper::constructor; Persistent<FunctionTemplate> CodeUnitWrapper::prototype; Persistent<Function> CodeUnitWrapper::constructor; void Init(Handle<Object> exports, Handle<Object> module) { TypeWrapper::Init(); CodeUnitWrapper::Init(); FunctionBuilderWrapper::Init(); Local<Function> getVoidTy = NanNew<Function>(TypeWrapper::GetVoidTy); exports->Set(NanNew<String>("getVoidTy"), getVoidTy); Local<Function> getFunctionTy = NanNew<Function>(TypeWrapper::GetFunctionTy); exports->Set(NanNew<String>("getFunctionTy"), getFunctionTy); Local<Function> codeUnit = NanNew(CodeUnitWrapper::constructor); exports->Set(NanNew<String>("CodeUnit"), codeUnit); } NODE_MODULE(codegen, Init) <|endoftext|>
<commit_before>#include <stdexcept> #include <map> #include <xorg/gtest/xorg-gtest.h> #include <linux/input.h> #include <X11/Xlib.h> #define XK_LATIN1 #include <X11/keysymdef.h> #include <X11/XF86keysym.h> #include <X11/Xutil.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> #include "input-driver-test.h" typedef std::pair <int, KeySym> Key_Pair; typedef std::multimap<std::string, Key_Pair> Keys_Map; typedef Keys_Map::iterator keys_mapIter; typedef std::vector<Key_Pair> MultiMedia_Keys_Map; typedef MultiMedia_Keys_Map::iterator multimediakeys_mapIter; class EvdevDriverXKBTest : public InputDriverTest { virtual void SetUp() { dev = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "keyboards/AT Translated Set 2 Keyboard.desc" ) ); // Define a map of pair to hold each key/keysym per layout // US, QWERTY => qwerty Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Q, XK_q))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_W, XK_w))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Y, XK_y))); // German, QWERTY => qwertz Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Q, XK_q))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_W, XK_w))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Y, XK_z))); // French, QWERTY => azerty Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Q, XK_a))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_W, XK_z))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Y, XK_y))); // Define a vector of pair to hold each key/keysym for multimedia Multimedia_Keys.push_back (Key_Pair (KEY_MUTE, XF86XK_AudioMute)); Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEUP, XF86XK_AudioRaiseVolume)); Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEDOWN, XF86XK_AudioLowerVolume)); Multimedia_Keys.push_back (Key_Pair (KEY_PLAYPAUSE, XF86XK_AudioPlay)); Multimedia_Keys.push_back (Key_Pair (KEY_NEXTSONG, XF86XK_AudioNext)); Multimedia_Keys.push_back (Key_Pair (KEY_PREVIOUSSONG, XF86XK_AudioPrev)); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog(const std::string &prefix) { server.SetOption("-logfile", "/tmp/Xorg-evdev-driver-xkb.log"); server.SetOption("-config", "/tmp/evdev-driver-xkb.conf"); config.AddDefaultScreenWithDriver(); config.AddInputSection("evdev", "--device--", "Option \"CoreKeyboard\" \"on\"\n" "Option \"XkbRules\" \"xorg\"\n" "Option \"XkbModel\" \"dellusbmm\"\n" "Option \"XkbLayout\" \""+ prefix + "\"\n" "Option \"Device\" \"" + dev->GetDeviceNode() + "\""); config.WriteConfig("/tmp/evdev-driver-xkb.conf"); } protected: std::auto_ptr<xorg::testing::evemu::Device> dev; Keys_Map Keys; MultiMedia_Keys_Map Multimedia_Keys; }; TEST_P(EvdevDriverXKBTest, DeviceExists) { std::string param; int ndevices; XIDeviceInfo *info; info = XIQueryDevice(Display(), XIAllDevices, &ndevices); bool found = false; while(ndevices--) { if (strcmp(info[ndevices].name, "--device--") == 0) { ASSERT_EQ(found, false) << "Duplicate device" << std::endl; found = true; } } ASSERT_EQ(found, true); XIFreeDeviceInfo(info); } void play_key_pair (::Display *display, xorg::testing::evemu::Device *dev, Key_Pair pair) { dev->PlayOne(EV_KEY, pair.first, 1, 1); dev->PlayOne(EV_KEY, pair.first, 0, 1); XSync(display, False); ASSERT_NE(XPending(display), 0) << "No event pending" << std::endl; XEvent press; XNextEvent(display, &press); KeySym sym = XKeycodeToKeysym(display, press.xkey.keycode, 0); ASSERT_NE(NoSymbol, sym) << "No keysym for keycode " << press.xkey.keycode << std::endl; ASSERT_EQ(pair.second, sym) << "Keysym not matching for keycode " << press.xkey.keycode << std::endl; XSync(display, False); while (XPending(display)) XNextEvent(display, &press); } TEST_P(EvdevDriverXKBTest, KeyboardLayout) { std::string layout = GetParam(); XSelectInput(Display(), DefaultRootWindow(Display()), KeyPressMask | KeyReleaseMask); /* the server takes a while to start up bust the devices may not respond to events yet. Add a noop call that just delays everything long enough for this test to work */ XInternAtom(Display(), "foo", True); XFlush(Display()); keys_mapIter it; std::pair<keys_mapIter, keys_mapIter> keyRange = Keys.equal_range(layout); for (it = keyRange.first; it != keyRange.second; ++it) play_key_pair (Display(), dev.get(), (*it).second); // Now test multimedia keys multimediakeys_mapIter m_it; for (m_it = Multimedia_Keys.begin(); m_it != Multimedia_Keys.end(); m_it++) play_key_pair (Display(), dev.get(), (*m_it)); } INSTANTIATE_TEST_CASE_P(, EvdevDriverXKBTest, ::testing::Values("us", "de", "fr")); class EvdevDriverMouseTest : public InputDriverTest { public: virtual void SetUp() { dev = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "mice/PIXART USB OPTICAL MOUSE-HWHEEL.desc" ) ); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog(const std::string &prefix) { server.SetOption("-logfile", "/tmp/Xorg-evdev-driver-mouse.log"); server.SetOption("-config", "/tmp/evdev-driver-mouse.conf"); config.AddDefaultScreenWithDriver(); config.AddInputSection("evdev", "--device--", "Option \"CorePointer\" \"on\"\n" "Option \"Device\" \"" + dev->GetDeviceNode() + "\""); config.WriteConfig("/tmp/evdev-driver-mouse.conf"); } protected: std::auto_ptr<xorg::testing::evemu::Device> dev; }; void scroll_wheel_event(::Display *display, xorg::testing::evemu::Device *dev, int axis, int value, int button) { dev->PlayOne(EV_REL, axis, value, 1); XSync(display, False); ASSERT_NE(XPending(display), 0) << "No event pending" << std::endl; XEvent btn; int nevents = 0; while(XPending(display)) { XNextEvent(display, &btn); ASSERT_EQ(btn.xbutton.type, ButtonPress); ASSERT_EQ(btn.xbutton.button, button); XNextEvent(display, &btn); ASSERT_EQ(btn.xbutton.type, ButtonRelease); ASSERT_EQ(btn.xbutton.button, button); nevents++; } ASSERT_EQ(nevents, abs(value)); } TEST_F(EvdevDriverMouseTest, ScrollWheel) { XSelectInput(Display(), DefaultRootWindow(Display()), ButtonPressMask | ButtonReleaseMask); /* the server takes a while to start up bust the devices may not respond to events yet. Add a noop call that just delays everything long enough for this test to work */ XInternAtom(Display(), "foo", True); XFlush(Display()); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 1, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 2, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 3, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -1, 5); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -2, 5); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -3, 5); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 1, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 2, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 3, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -1, 6); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -2, 6); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -3, 6); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>evdev: check DeviceNode property<commit_after>#include <stdexcept> #include <map> #include <xorg/gtest/xorg-gtest.h> #include <linux/input.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #define XK_LATIN1 #include <X11/keysymdef.h> #include <X11/XF86keysym.h> #include <X11/Xutil.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> #include "input-driver-test.h" typedef std::pair <int, KeySym> Key_Pair; typedef std::multimap<std::string, Key_Pair> Keys_Map; typedef Keys_Map::iterator keys_mapIter; typedef std::vector<Key_Pair> MultiMedia_Keys_Map; typedef MultiMedia_Keys_Map::iterator multimediakeys_mapIter; class EvdevDriverXKBTest : public InputDriverTest { virtual void SetUp() { dev = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "keyboards/AT Translated Set 2 Keyboard.desc" ) ); // Define a map of pair to hold each key/keysym per layout // US, QWERTY => qwerty Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Q, XK_q))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_W, XK_w))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Y, XK_y))); // German, QWERTY => qwertz Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Q, XK_q))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_W, XK_w))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Y, XK_z))); // French, QWERTY => azerty Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Q, XK_a))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_W, XK_z))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_E, XK_e))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_R, XK_r))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_T, XK_t))); Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Y, XK_y))); // Define a vector of pair to hold each key/keysym for multimedia Multimedia_Keys.push_back (Key_Pair (KEY_MUTE, XF86XK_AudioMute)); Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEUP, XF86XK_AudioRaiseVolume)); Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEDOWN, XF86XK_AudioLowerVolume)); Multimedia_Keys.push_back (Key_Pair (KEY_PLAYPAUSE, XF86XK_AudioPlay)); Multimedia_Keys.push_back (Key_Pair (KEY_NEXTSONG, XF86XK_AudioNext)); Multimedia_Keys.push_back (Key_Pair (KEY_PREVIOUSSONG, XF86XK_AudioPrev)); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog(const std::string &prefix) { server.SetOption("-logfile", "/tmp/Xorg-evdev-driver-xkb.log"); server.SetOption("-config", "/tmp/evdev-driver-xkb.conf"); config.AddDefaultScreenWithDriver(); config.AddInputSection("evdev", "--device--", "Option \"CoreKeyboard\" \"on\"\n" "Option \"XkbRules\" \"xorg\"\n" "Option \"XkbModel\" \"dellusbmm\"\n" "Option \"XkbLayout\" \""+ prefix + "\"\n" "Option \"Device\" \"" + dev->GetDeviceNode() + "\""); config.WriteConfig("/tmp/evdev-driver-xkb.conf"); } protected: std::auto_ptr<xorg::testing::evemu::Device> dev; Keys_Map Keys; MultiMedia_Keys_Map Multimedia_Keys; }; TEST_P(EvdevDriverXKBTest, DeviceExists) { std::string param; int ndevices; XIDeviceInfo *info; info = XIQueryDevice(Display(), XIAllDevices, &ndevices); bool found = false; while(ndevices--) { if (strcmp(info[ndevices].name, "--device--") == 0) { ASSERT_EQ(found, false) << "Duplicate device" << std::endl; found = true; } } ASSERT_EQ(found, true); XIFreeDeviceInfo(info); } void play_key_pair (::Display *display, xorg::testing::evemu::Device *dev, Key_Pair pair) { dev->PlayOne(EV_KEY, pair.first, 1, 1); dev->PlayOne(EV_KEY, pair.first, 0, 1); XSync(display, False); ASSERT_NE(XPending(display), 0) << "No event pending" << std::endl; XEvent press; XNextEvent(display, &press); KeySym sym = XKeycodeToKeysym(display, press.xkey.keycode, 0); ASSERT_NE(NoSymbol, sym) << "No keysym for keycode " << press.xkey.keycode << std::endl; ASSERT_EQ(pair.second, sym) << "Keysym not matching for keycode " << press.xkey.keycode << std::endl; XSync(display, False); while (XPending(display)) XNextEvent(display, &press); } TEST_P(EvdevDriverXKBTest, KeyboardLayout) { std::string layout = GetParam(); XSelectInput(Display(), DefaultRootWindow(Display()), KeyPressMask | KeyReleaseMask); /* the server takes a while to start up bust the devices may not respond to events yet. Add a noop call that just delays everything long enough for this test to work */ XInternAtom(Display(), "foo", True); XFlush(Display()); keys_mapIter it; std::pair<keys_mapIter, keys_mapIter> keyRange = Keys.equal_range(layout); for (it = keyRange.first; it != keyRange.second; ++it) play_key_pair (Display(), dev.get(), (*it).second); // Now test multimedia keys multimediakeys_mapIter m_it; for (m_it = Multimedia_Keys.begin(); m_it != Multimedia_Keys.end(); m_it++) play_key_pair (Display(), dev.get(), (*m_it)); } INSTANTIATE_TEST_CASE_P(, EvdevDriverXKBTest, ::testing::Values("us", "de", "fr")); class EvdevDriverMouseTest : public InputDriverTest { public: virtual void SetUp() { dev = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "mice/PIXART USB OPTICAL MOUSE-HWHEEL.desc" ) ); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog(const std::string &prefix) { server.SetOption("-logfile", "/tmp/Xorg-evdev-driver-mouse.log"); server.SetOption("-config", "/tmp/evdev-driver-mouse.conf"); config.AddDefaultScreenWithDriver(); config.AddInputSection("evdev", "--device--", "Option \"CorePointer\" \"on\"\n" "Option \"Device\" \"" + dev->GetDeviceNode() + "\""); config.WriteConfig("/tmp/evdev-driver-mouse.conf"); } protected: std::auto_ptr<xorg::testing::evemu::Device> dev; }; void scroll_wheel_event(::Display *display, xorg::testing::evemu::Device *dev, int axis, int value, int button) { dev->PlayOne(EV_REL, axis, value, 1); XSync(display, False); ASSERT_NE(XPending(display), 0) << "No event pending" << std::endl; XEvent btn; int nevents = 0; while(XPending(display)) { XNextEvent(display, &btn); ASSERT_EQ(btn.xbutton.type, ButtonPress); ASSERT_EQ(btn.xbutton.button, button); XNextEvent(display, &btn); ASSERT_EQ(btn.xbutton.type, ButtonRelease); ASSERT_EQ(btn.xbutton.button, button); nevents++; } ASSERT_EQ(nevents, abs(value)); } TEST_F(EvdevDriverMouseTest, ScrollWheel) { XSelectInput(Display(), DefaultRootWindow(Display()), ButtonPressMask | ButtonReleaseMask); /* the server takes a while to start up bust the devices may not respond to events yet. Add a noop call that just delays everything long enough for this test to work */ XInternAtom(Display(), "foo", True); XFlush(Display()); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 1, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 2, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, 3, 4); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -1, 5); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -2, 5); scroll_wheel_event(Display(), dev.get(), REL_WHEEL, -3, 5); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 1, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 2, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, 3, 7); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -1, 6); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -2, 6); scroll_wheel_event(Display(), dev.get(), REL_HWHEEL, -3, 6); } TEST_F(EvdevDriverMouseTest, DevNode) { Atom node_prop = XInternAtom(Display(), "Device Node", True); ASSERT_NE(node_prop, None) << "This requires server 1.11"; int deviceid = -1; XIDeviceInfo *info; int ndevices; info = XIQueryDevice(Display(), XIAllDevices, &ndevices); while (ndevices--) { if (strcmp(info[ndevices].name, "--device--") == 0) deviceid = info[ndevices].deviceid; } XIFreeDeviceInfo(info); ASSERT_NE(deviceid, -1) << "Failed to find device."; Atom type; int format; unsigned long nitems, bytes_after; char *data; XIGetProperty(Display(), deviceid, node_prop, 0, 100, False, AnyPropertyType, &type, &format, &nitems, &bytes_after, (unsigned char**)&data); ASSERT_EQ(type, XA_STRING); std::string devnode(data); ASSERT_EQ(devnode.compare(dev->GetDeviceNode()), 0); XFree(data); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL #define SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL #include <sofa/core/visual/VisualParams.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #ifdef SOFA_HAVE_EIGEN2 #include <sofa/component/linearsolver/EigenSparseMatrix.h> #endif #include <sofa/core/MultiMapping.inl> #include <iostream> using std::cerr; using std::endl; namespace sofa { namespace component { namespace mapping { using namespace sofa::core; template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::bwdInit() { // for now we suppose that we only have two parents if (this->fromModels.size()!=2 ) { serr<<" ERROR, for now SubsetMultiMapping is programmed to have only two parents and not"<< this->fromModels.size()<<sendl; return; } m_numParents = 2; std::cout<<" bwd Init Call "<<std::endl; int s0 = this->fromModels[0]->getSize(); int s1 = this->fromModels[1]->getSize(); std::cout<<"size from [0] = "<<s0<<" - size from [1] = "<<s1<<std::endl; std::cout << "init inherit"<<std::endl; Inherit::init(); std::cout << "assert"<<std::endl; assert( indexPairs.getValue().size()%2==0 ); const unsigned indexPairSize = indexPairs.getValue().size()/2; std::cout << "resize"<<std::endl; this->toModels[0]->resize( indexPairSize ); s0 = this->fromModels[0]->getSize(); s1 = this->fromModels[1]->getSize(); std::cout<<"size from [0]"<<s0<<" - size from [1]"<<s1<<std::endl; unsigned Nin = TIn::deriv_total_size, Nout = Nin; std::cout<<"before delete"<<std::endl; for( unsigned i=0; i<baseMatrices.size(); i++ ) delete baseMatrices[i]; std::cout<<"after delete"<<std::endl; //#ifdef SOFA_HAVE_EIGEN2 // std::cout<<"SOFA_HAVE_EIGEN2"<<std::endl; // typedef linearsolver::EigenSparseMatrix<TIn,TOut> Jacobian; // baseMatrices.resize( this->getFrom().size() ); // vector<Jacobian*> jacobians( this->getFrom().size() ); // for(unsigned i=0; i<baseMatrices.size(); i++ ) // { // baseMatrices[i] = jacobians[i] = new linearsolver::EigenSparseMatrix<TIn,TOut>; // jacobians[i]->resize(Nout*indexPairSize,Nin*this->fromModels[i]->readPositions().size() ); // each jacobian has the same number of rows // } // // fill the jacobians // for(unsigned i=0; i<indexPairSize; i++) // { // unsigned parent = indexPairs.getValue()[i*2]; // Jacobian* jacobian = jacobians[parent]; // unsigned bcol = indexPairs.getValue()[i*2+1]; // parent particle // for(unsigned k=0; k<Nin; k++ ) // { // unsigned row = i*Nout + k; // jacobian->insertBack( row, Nin*bcol +k, (SReal)1. ); // } // } //// // fill the jacobians //// vector<unsigned> rowIndex(this->getFrom().size(),0); // current block row index in each jacobian //// for(unsigned i=0; i<indexPairSize; i++) //// { //// unsigned parent = indexPairs[i*2]; //// Jacobian* jacobian = jacobians[parent]; //// unsigned& brow = rowIndex[parent]; //// unsigned bcol = indexPairs[i*2+1]; // parent particle //// for(unsigned k=0; k<Nin; k++ ) //// { ////// baseMatrices[ indexPairs[i*2] ]->set( Nout*i+k, Nin*indexPairs[i*2+1], (SReal)1. ); //// jacobian->beginRow(Nout*brow+k); //// jacobian->insertBack( Nout*brow+k, Nin*bcol +k, (SReal)1. ); //// } //// brow++; //// } // // finalize the jacobians // for(unsigned i=0; i<baseMatrices.size(); i++ ) // { // baseMatrices[i]->compress(); // } //#else for( unsigned i=0; i<matricesJ.size(); i++ ) delete matricesJ[i]; baseMatrices.resize( this->getFrom().size() ); matricesJ.resize( this->getFrom().size() ); for(unsigned i=0; i<matricesJ.size(); i++ ) { baseMatrices[i] = matricesJ[i] = new Jacobian(); matricesJ[i]->resize(Nout*indexPairSize,Nin*this->fromModels[i]->readPositions().size() ); // each jacobian has the same number of rows } // fill the jacobians for(unsigned i=0; i<indexPairSize; i++) { unsigned parent = indexPairs.getValue()[i*2]; Jacobian* jacobian = matricesJ[parent]; unsigned bcol = indexPairs.getValue()[i*2+1]; // parent particle for(unsigned k=0; k<Nin; k++ ) { unsigned row = i*Nout + k; jacobian->set( row, Nin*bcol +k, (SReal)1. ); } } // finalize the jacobians for(unsigned i=0; i<baseMatrices.size(); i++ ) { baseMatrices[i]->compress(); } //#endif } template <class TIn, class TOut> SubsetMultiMapping<TIn, TOut>::~SubsetMultiMapping() { for(unsigned i=0; i<baseMatrices.size(); i++ ) { delete baseMatrices[i]; } } #ifdef SOFA_HAVE_EIGEN2 template <class TIn, class TOut> const helper::vector<sofa::defaulttype::BaseMatrix*>* SubsetMultiMapping<TIn, TOut>::getJs() { return &baseMatrices; } #endif template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::addPoint( const core::BaseState* from, int index) { // find the index of the parent state unsigned i; for(i=0; i<this->fromModels.size(); i++) if(this->fromModels.get(i)==from ) break; if(i==this->fromModels.size()) { serr<<"SubsetMultiMapping<TIn, TOut>::addPoint, parent "<<from->getName()<<" not found !"<< sendl; assert(0); } vector<unsigned>& indexPairsVector = *indexPairs.beginEdit(); indexPairsVector.push_back(i); indexPairsVector.push_back(index); indexPairs.endEdit(); } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::apply(const vecOutVecCoord& outPos, const vecConstInVecCoord& inPos) { OutVecCoord& out = *outPos[0]; out.resize(indexPairs.getValue().size()/2); for(unsigned i=0; i<out.size(); i++) { // cerr<<"SubsetMultiMapping<TIn, TOut>::apply, i = "<< i <<", indexPair = " << indexPairs[i*2] << ", " << indexPairs[i*2+1] <<", inPos size = "<< inPos.size() <<", inPos[i] = " << (*inPos[indexPairs[i*2]]) << endl; // cerr<<"SubsetMultiMapping<TIn, TOut>::apply, out = "<< out << endl; out[i] = (*inPos[indexPairs.getValue()[i*2]]) [indexPairs.getValue()[i*2+1]]; } } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJ(const helper::vector< typename SubsetMultiMapping<TIn, TOut>::OutVecDeriv*>& outDeriv, const helper::vector<const InVecDeriv*>& inDeriv) { OutVecDeriv& out = *outDeriv[0]; out.resize(indexPairs.getValue().size()/2); for(unsigned i=0; i<out.size(); i++) { out[i] = (*inDeriv[indexPairs.getValue()[i*2]])[indexPairs.getValue()[i*2+1]]; } } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJT( const helper::vector<InMatrixDeriv* >& dOut, const helper::vector<const OutMatrixDeriv* >& dIn) { vector<unsigned> indexP = indexPairs.getValue(); // hypothesis: one child only: const OutMatrixDeriv* in = dIn[0]; if (dOut.size() != m_numParents) { serr<<"problem with number of output constraint matrices"<<sendl; return; } typename OutMatrixDeriv::RowConstIterator rowItEnd = in->end(); // loop on the constraints defined on the child of the mapping for (typename OutMatrixDeriv::RowConstIterator rowIt = in->begin(); rowIt != rowItEnd; ++rowIt) { typename OutMatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename OutMatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // A constraint can be shared by several nodes, // these nodes can be linked to 2 different parent. // we need to add a line to each parent that is concerned by the constraint while (colIt != colItEnd) { unsigned int index_parent= indexP[colIt.index()*2]; // 0 or 1 (for now...) // writeLine provide an iterator on the line... if this line does not exist, the line is created: typename InMatrixDeriv::RowIterator o = dOut[index_parent]->writeLine(rowIt.index()); // for each col of the constraint direction, it adds a col in the corresponding parent's constraint direction if(indexPairs.getValue()[colIt.index()*2+1] < this->fromModels[index_parent]->getSize()) o.addCol(indexP[colIt.index()*2+1], colIt.val()); ++colIt; } } // std::cout<<" dIn ="<<(*dIn[0])<<std::endl; // std::cout<<" dOut ="<<(*dOut[0])<<" "<<(*dOut[1])<<std::endl; } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJT(const helper::vector<typename SubsetMultiMapping<TIn, TOut>::InVecDeriv*>& parentDeriv , const helper::vector<const OutVecDeriv*>& childDeriv ) { // hypothesis: one child only: const InVecDeriv& cder = *childDeriv[0]; for(unsigned i=0; i<cder.size(); i++) { (*parentDeriv[indexPairs.getValue()[i*2]])[indexPairs.getValue()[i*2+1]] += cder[i]; } } } // namespace mapping } // namespace component } // namespace sofa #endif //SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL <commit_msg>SubsetMultiMapping: commented debug messages<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL #define SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL #include <sofa/core/visual/VisualParams.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #ifdef SOFA_HAVE_EIGEN2 #include <sofa/component/linearsolver/EigenSparseMatrix.h> #endif #include <sofa/core/MultiMapping.inl> #include <iostream> using std::cerr; using std::endl; namespace sofa { namespace component { namespace mapping { using namespace sofa::core; template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::bwdInit() { // for now we suppose that we only have two parents if (this->fromModels.size()!=2 ) { serr<<" ERROR, for now SubsetMultiMapping is programmed to have only two parents and not"<< this->fromModels.size()<<sendl; return; } m_numParents = 2; // std::cout<<" bwd Init Call "<<std::endl; int s0 = this->fromModels[0]->getSize(); int s1 = this->fromModels[1]->getSize(); // std::cout<<"size from [0] = "<<s0<<" - size from [1] = "<<s1<<std::endl; // std::cout << "init inherit"<<std::endl; Inherit::init(); // std::cout << "assert"<<std::endl; assert( indexPairs.getValue().size()%2==0 ); const unsigned indexPairSize = indexPairs.getValue().size()/2; // std::cout << "resize"<<std::endl; this->toModels[0]->resize( indexPairSize ); s0 = this->fromModels[0]->getSize(); s1 = this->fromModels[1]->getSize(); // std::cout<<"size from [0]"<<s0<<" - size from [1]"<<s1<<std::endl; unsigned Nin = TIn::deriv_total_size, Nout = Nin; // std::cout<<"before delete"<<std::endl; for( unsigned i=0; i<baseMatrices.size(); i++ ) delete baseMatrices[i]; // std::cout<<"after delete"<<std::endl; //#ifdef SOFA_HAVE_EIGEN2 // std::cout<<"SOFA_HAVE_EIGEN2"<<std::endl; // typedef linearsolver::EigenSparseMatrix<TIn,TOut> Jacobian; // baseMatrices.resize( this->getFrom().size() ); // vector<Jacobian*> jacobians( this->getFrom().size() ); // for(unsigned i=0; i<baseMatrices.size(); i++ ) // { // baseMatrices[i] = jacobians[i] = new linearsolver::EigenSparseMatrix<TIn,TOut>; // jacobians[i]->resize(Nout*indexPairSize,Nin*this->fromModels[i]->readPositions().size() ); // each jacobian has the same number of rows // } // // fill the jacobians // for(unsigned i=0; i<indexPairSize; i++) // { // unsigned parent = indexPairs.getValue()[i*2]; // Jacobian* jacobian = jacobians[parent]; // unsigned bcol = indexPairs.getValue()[i*2+1]; // parent particle // for(unsigned k=0; k<Nin; k++ ) // { // unsigned row = i*Nout + k; // jacobian->insertBack( row, Nin*bcol +k, (SReal)1. ); // } // } //// // fill the jacobians //// vector<unsigned> rowIndex(this->getFrom().size(),0); // current block row index in each jacobian //// for(unsigned i=0; i<indexPairSize; i++) //// { //// unsigned parent = indexPairs[i*2]; //// Jacobian* jacobian = jacobians[parent]; //// unsigned& brow = rowIndex[parent]; //// unsigned bcol = indexPairs[i*2+1]; // parent particle //// for(unsigned k=0; k<Nin; k++ ) //// { ////// baseMatrices[ indexPairs[i*2] ]->set( Nout*i+k, Nin*indexPairs[i*2+1], (SReal)1. ); //// jacobian->beginRow(Nout*brow+k); //// jacobian->insertBack( Nout*brow+k, Nin*bcol +k, (SReal)1. ); //// } //// brow++; //// } // // finalize the jacobians // for(unsigned i=0; i<baseMatrices.size(); i++ ) // { // baseMatrices[i]->compress(); // } //#else for( unsigned i=0; i<matricesJ.size(); i++ ) delete matricesJ[i]; baseMatrices.resize( this->getFrom().size() ); matricesJ.resize( this->getFrom().size() ); for(unsigned i=0; i<matricesJ.size(); i++ ) { baseMatrices[i] = matricesJ[i] = new Jacobian(); matricesJ[i]->resize(Nout*indexPairSize,Nin*this->fromModels[i]->readPositions().size() ); // each jacobian has the same number of rows } // fill the jacobians for(unsigned i=0; i<indexPairSize; i++) { unsigned parent = indexPairs.getValue()[i*2]; Jacobian* jacobian = matricesJ[parent]; unsigned bcol = indexPairs.getValue()[i*2+1]; // parent particle for(unsigned k=0; k<Nin; k++ ) { unsigned row = i*Nout + k; jacobian->set( row, Nin*bcol +k, (SReal)1. ); } } // finalize the jacobians for(unsigned i=0; i<baseMatrices.size(); i++ ) { baseMatrices[i]->compress(); } //#endif } template <class TIn, class TOut> SubsetMultiMapping<TIn, TOut>::~SubsetMultiMapping() { for(unsigned i=0; i<baseMatrices.size(); i++ ) { delete baseMatrices[i]; } } #ifdef SOFA_HAVE_EIGEN2 template <class TIn, class TOut> const helper::vector<sofa::defaulttype::BaseMatrix*>* SubsetMultiMapping<TIn, TOut>::getJs() { return &baseMatrices; } #endif template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::addPoint( const core::BaseState* from, int index) { // find the index of the parent state unsigned i; for(i=0; i<this->fromModels.size(); i++) if(this->fromModels.get(i)==from ) break; if(i==this->fromModels.size()) { serr<<"SubsetMultiMapping<TIn, TOut>::addPoint, parent "<<from->getName()<<" not found !"<< sendl; assert(0); } vector<unsigned>& indexPairsVector = *indexPairs.beginEdit(); indexPairsVector.push_back(i); indexPairsVector.push_back(index); indexPairs.endEdit(); } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::apply(const vecOutVecCoord& outPos, const vecConstInVecCoord& inPos) { OutVecCoord& out = *outPos[0]; out.resize(indexPairs.getValue().size()/2); for(unsigned i=0; i<out.size(); i++) { // cerr<<"SubsetMultiMapping<TIn, TOut>::apply, i = "<< i <<", indexPair = " << indexPairs[i*2] << ", " << indexPairs[i*2+1] <<", inPos size = "<< inPos.size() <<", inPos[i] = " << (*inPos[indexPairs[i*2]]) << endl; // cerr<<"SubsetMultiMapping<TIn, TOut>::apply, out = "<< out << endl; out[i] = (*inPos[indexPairs.getValue()[i*2]]) [indexPairs.getValue()[i*2+1]]; } } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJ(const helper::vector< typename SubsetMultiMapping<TIn, TOut>::OutVecDeriv*>& outDeriv, const helper::vector<const InVecDeriv*>& inDeriv) { OutVecDeriv& out = *outDeriv[0]; out.resize(indexPairs.getValue().size()/2); for(unsigned i=0; i<out.size(); i++) { out[i] = (*inDeriv[indexPairs.getValue()[i*2]])[indexPairs.getValue()[i*2+1]]; } } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJT( const helper::vector<InMatrixDeriv* >& dOut, const helper::vector<const OutMatrixDeriv* >& dIn) { vector<unsigned> indexP = indexPairs.getValue(); // hypothesis: one child only: const OutMatrixDeriv* in = dIn[0]; if (dOut.size() != m_numParents) { serr<<"problem with number of output constraint matrices"<<sendl; return; } typename OutMatrixDeriv::RowConstIterator rowItEnd = in->end(); // loop on the constraints defined on the child of the mapping for (typename OutMatrixDeriv::RowConstIterator rowIt = in->begin(); rowIt != rowItEnd; ++rowIt) { typename OutMatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename OutMatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // A constraint can be shared by several nodes, // these nodes can be linked to 2 different parent. // we need to add a line to each parent that is concerned by the constraint while (colIt != colItEnd) { unsigned int index_parent= indexP[colIt.index()*2]; // 0 or 1 (for now...) // writeLine provide an iterator on the line... if this line does not exist, the line is created: typename InMatrixDeriv::RowIterator o = dOut[index_parent]->writeLine(rowIt.index()); // for each col of the constraint direction, it adds a col in the corresponding parent's constraint direction if(indexPairs.getValue()[colIt.index()*2+1] < this->fromModels[index_parent]->getSize()) o.addCol(indexP[colIt.index()*2+1], colIt.val()); ++colIt; } } // std::cout<<" dIn ="<<(*dIn[0])<<std::endl; // std::cout<<" dOut ="<<(*dOut[0])<<" "<<(*dOut[1])<<std::endl; } template <class TIn, class TOut> void SubsetMultiMapping<TIn, TOut>::applyJT(const helper::vector<typename SubsetMultiMapping<TIn, TOut>::InVecDeriv*>& parentDeriv , const helper::vector<const OutVecDeriv*>& childDeriv ) { // hypothesis: one child only: const InVecDeriv& cder = *childDeriv[0]; for(unsigned i=0; i<cder.size(); i++) { (*parentDeriv[indexPairs.getValue()[i*2]])[indexPairs.getValue()[i*2+1]] += cder[i]; } } } // namespace mapping } // namespace component } // namespace sofa #endif //SOFA_COMPONENT_MAPPING_SUBSETMULTIMAPPING_INL <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PressureAction.h" #include "Factory.h" #include "FEProblem.h" #include "Conversion.h" registerMooseAction("TensorMechanicsApp", PressureAction, "add_bc"); InputParameters PressureAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription("Set up Pressure boundary conditions"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary", "The list of boundary IDs from the mesh where the pressure will be applied"); params.addParam<std::vector<VariableName>>( "displacements", "The displacements appropriate for the simulation geometry and coordinate system"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_x", "The save_in variables for x displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_y", "The save_in variables for y displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_z", "The save_in variables for z displacement"); params.addParam<Real>("factor", 1.0, "The factor to use in computing the pressure"); params.addParam<bool>("use_displaced_mesh", true, "Whether to use the displaced mesh."); params.addParam<Real>("hht_alpha", 0, "alpha parameter for mass dependent numerical damping induced " "by HHT time integration scheme"); params.addDeprecatedParam<Real>( "alpha", "alpha parameter for HHT time integration", "Please use hht_alpha"); params.addParam<FunctionName>("function", "The function that describes the pressure"); params.addParam<bool>("use_automatic_differentiation", false, "Flag to use automatic differentiation (AD) objects when possible"); return params; } PressureAction::PressureAction(const InputParameters & params) : Action(params), _use_ad(getParam<bool>("use_automatic_differentiation")) { _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_x")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_y")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_z")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_x")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_y")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_z")); } void PressureAction::act() { std::string ad_prepend = ""; if (_use_ad) ad_prepend = "AD"; std::string kernel_name = ad_prepend + "Pressure"; std::vector<VariableName> displacements = getParam<std::vector<VariableName>>("displacements"); // Create pressure BCs for (unsigned int i = 0; i < displacements.size(); ++i) { // Create unique kernel name for each of the components std::string unique_kernel_name = kernel_name + "_" + _name + "_" + Moose::stringify(i); InputParameters params = _factory.getValidParams(kernel_name); params.applyParameters(parameters(), {"factor"}); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<Real>("alpha") = isParamValid("alpha") ? getParam<Real>("alpha") : getParam<Real>("hht_alpha"); params.set<NonlinearVariableName>("variable") = displacements[i]; if (_has_save_in_vars[i]) params.set<std::vector<AuxVariableName>>("save_in") = _save_in_vars[i]; if (_use_ad) params.set<Real>("constant") = getParam<Real>("factor"); else params.set<Real>("factor") = getParam<Real>("factor"); _problem->addBoundaryCondition(kernel_name, unique_kernel_name, params); } } <commit_msg>'constant' is deprecated in Pressure BC.<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PressureAction.h" #include "Factory.h" #include "FEProblem.h" #include "Conversion.h" registerMooseAction("TensorMechanicsApp", PressureAction, "add_bc"); InputParameters PressureAction::validParams() { InputParameters params = Action::validParams(); params.addClassDescription("Set up Pressure boundary conditions"); params.addRequiredParam<std::vector<BoundaryName>>( "boundary", "The list of boundary IDs from the mesh where the pressure will be applied"); params.addParam<std::vector<VariableName>>( "displacements", "The displacements appropriate for the simulation geometry and coordinate system"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_x", "The save_in variables for x displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_y", "The save_in variables for y displacement"); params.addParam<std::vector<AuxVariableName>>("save_in_disp_z", "The save_in variables for z displacement"); params.addParam<Real>("factor", 1.0, "The factor to use in computing the pressure"); params.addParam<bool>("use_displaced_mesh", true, "Whether to use the displaced mesh."); params.addParam<Real>("hht_alpha", 0, "alpha parameter for mass dependent numerical damping induced " "by HHT time integration scheme"); params.addDeprecatedParam<Real>( "alpha", "alpha parameter for HHT time integration", "Please use hht_alpha"); params.addParam<FunctionName>("function", "The function that describes the pressure"); params.addParam<bool>("use_automatic_differentiation", false, "Flag to use automatic differentiation (AD) objects when possible"); return params; } PressureAction::PressureAction(const InputParameters & params) : Action(params), _use_ad(getParam<bool>("use_automatic_differentiation")) { _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_x")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_y")); _save_in_vars.push_back(getParam<std::vector<AuxVariableName>>("save_in_disp_z")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_x")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_y")); _has_save_in_vars.push_back(params.isParamValid("save_in_disp_z")); } void PressureAction::act() { std::string ad_prepend = ""; if (_use_ad) ad_prepend = "AD"; std::string kernel_name = ad_prepend + "Pressure"; std::vector<VariableName> displacements = getParam<std::vector<VariableName>>("displacements"); // Create pressure BCs for (unsigned int i = 0; i < displacements.size(); ++i) { // Create unique kernel name for each of the components std::string unique_kernel_name = kernel_name + "_" + _name + "_" + Moose::stringify(i); InputParameters params = _factory.getValidParams(kernel_name); params.applyParameters(parameters(), {"factor"}); params.set<bool>("use_displaced_mesh") = getParam<bool>("use_displaced_mesh"); params.set<Real>("alpha") = isParamValid("alpha") ? getParam<Real>("alpha") : getParam<Real>("hht_alpha"); params.set<NonlinearVariableName>("variable") = displacements[i]; if (_has_save_in_vars[i]) params.set<std::vector<AuxVariableName>>("save_in") = _save_in_vars[i]; params.set<Real>("factor") = getParam<Real>("factor"); _problem->addBoundaryCondition(kernel_name, unique_kernel_name, params); } } <|endoftext|>
<commit_before> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <liblogger.h> using namespace liblogger; #include "examples.h" int main(int argc, char ** argv) { pid_t pid = fork(); if (pid == 0) { int ret = system("../logmq/logmq"); exit(WEXITSTATUS(ret)); } if (pid < 0) abort(); LogManager::Add(new LogMQ()); examples(); LogManager::RemoveAll(); if (kill(pid, SIGTERM) < 0) abort(); int status = 0; if (waitpid(pid, &status, 0) < 0) abort(); return 0; } <commit_msg>Workaround race in test<commit_after> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <liblogger.h> using namespace liblogger; #include "examples.h" int main(int argc, char ** argv) { pid_t pid = fork(); if (pid == 0) { int ret = system("../logmq/logmq"); exit(WEXITSTATUS(ret)); } if (pid < 0) abort(); sleep(2); //Poor workaround for race if we start before the child LogManager::Add(new LogMQ()); examples(); LogManager::RemoveAll(); if (kill(pid, SIGTERM) < 0) abort(); int status = 0; if (waitpid(pid, &status, 0) < 0) abort(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2015 Cotton Seed This file is part of arachne-pnr. Arachne-pnr is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "util.hh" #include "netlist.hh" #include "line_parser.hh" #include "bitvector.hh" #include "casting.hh" #include <cctype> #include <cstring> #include <istream> #include <fstream> #include <iostream> #include <string> class BlifParser : public LineParser { BitVector stobv(const std::string &s_); public: BlifParser(const std::string &f, std::istream &s_) : LineParser(f, s_) {} Design *parse(); }; BitVector BlifParser::stobv(const std::string &s_) { int n = s_.size(); BitVector bv(n); for (int i = 0; i < n; ++i) { char c = s_[(n - 1) - i]; if (c == '1') bv[i] = true; else if (c == '0' || c == 'x' || c == 'X') ; else fatal("invalid character in integer constant"); } return bv; } Design * BlifParser::parse() { Design *d = new Design; d->create_standard_models(); Model *io_model = d->find_model("SB_IO"); Model *top = nullptr; std::vector<std::pair<Net *, Net *>> unify; Instance *inst = nullptr; for (;;) { if (eof()) goto M; read_line(); if (line.empty()) continue; if (line[0] == '.') { L: std::string cmd = words[0]; if (cmd == ".model") { if (words.size() != 2) fatal("invalid .model directive"); assert(top == nullptr); top = new Model(d, words[1]); d->set_top(top); } else if (cmd == ".inputs") { for (unsigned i = 1; i < words.size(); i ++) { Port *port = top->find_port(words[i]); if (port) { if (port->direction() == Direction::OUT) port->set_direction(Direction::INOUT); } else port = top->add_port(words[i], Direction::IN); Net *net = top->find_or_add_net(words[i]); port->connect(net); } } else if (cmd == ".outputs") { for (unsigned i = 1; i < words.size(); i ++) { Port *port = top->find_port(words[i]); if (port) { if (port->direction() == Direction::IN) port->set_direction(Direction::INOUT); } else port = top->add_port(words[i], Direction::OUT); Net *net = top->find_or_add_net(words[i]); port->connect(net); } } else if (cmd == ".names") { LexicalPosition names_lp = lp; Net *names_net = nullptr; unsigned n = words.size(); if (n == 2) { names_net = top->find_or_add_net(words[1]); names_net->set_is_constant(true); names_net->set_constant(Value::ZERO); } else if (n == 3) { unify.push_back(std::make_pair(top->find_or_add_net(words[1]), top->find_or_add_net(words[2]))); } else fatal("invalid .names directive"); bool saw11 = false; for (;;) { if (eof()) { if (n == 3 && !saw11) names_lp.fatal("invalid .names directive"); goto M; } read_line(); if (line.empty()) continue; if (line[0] == '.') { if (n == 3 && !saw11) names_lp.fatal("invalid .names directive"); goto L; } if (words.size() != n - 1) fatal("invalid .names entry"); if (n == 2) { const std::string &output = words[0]; if (output == "1") names_net->set_constant(Value::ONE); else if (output != "0") fatal("invalid .names entry"); } else { assert(n == 3); if (words[0] != "1" || words[1] != "1") fatal("invalid .names entry"); saw11 = true; } } } else if (cmd == ".gate") { if (words.size() < 2) fatal("invalid .gate directive, missing name"); const std::string &n = words[1]; Model *inst_of = d->find_model(n); if (!inst_of) fatal(fmt("unknown model `" << n << "'")); inst = top->add_instance(inst_of); for (unsigned i = 2; i < words.size(); i ++) { const std::string &w = words[i]; std::size_t p = w.find('='); if (p == std::string::npos) fatal("invalid formal-actual"); std::string formal(w, 0, p), actual(w, p+1); if (actual.empty()) continue; Port *port = inst->find_port(formal); if (!port) fatal(fmt("unknown formal `" << formal << "'")); Net *net = top->find_or_add_net(actual); port->connect(net); } } else if (cmd == ".attr") { if (words.size() != 3) fatal("invalid .attr directive"); if (!inst) fatal("no gate for .attr directive"); if (words[2][0] == '"') { assert(words[2].back() == '"'); inst->set_attr(words[1], Const(lp, words[2].substr(1, words[2].size() - 2))); } else { inst->set_attr(words[1], Const(lp, stobv(words[2]))); } } else if (cmd == ".param") { if (words.size() != 3) fatal("invalid .param directive"); if (!inst) fatal("no gate for .param directive"); if (words[2][0] == '"') { assert(words[2].back() == '"'); inst->set_param(words[1], Const(lp, words[2].substr(1, words[2].size() - 2))); } else { inst->set_param(words[1], Const(lp, stobv(words[2]))); } } else if (cmd == ".end") goto M; else fatal("unknown directive"); } else fatal("expected directive"); } M: // unify std::map<Net *, Net *, IdLess> replacement; for (const auto &p : unify) { // n1 drives n2 Net *n1 = p.first, *n2 = p.second; Net *r = n1; while (Net *t = lookup_or_default(replacement, r, nullptr)) r = t; Net *x = n1; while (x != r) { auto i = replacement.find(x); assert(i != replacement.end()); x = i->second; i->second = r; } if (n2 == r) fatal(".names cycle\n"); n2->replace(r); extend(replacement, n2, r); } for (const auto &p : replacement) { Net *n = p.first; top->remove_net(n); delete n; } for (const auto &p : top->ports()) { if (p.second->is_bidir()) { Net *n = p.second->connection(); if (n) { Port *q = p.second->connection_other_port(); if (!q || !isa<Instance>(q->node()) || cast<Instance>(q->node())->instance_of() != io_model || q->name() != "PACKAGE_PIN") fatal(fmt("toplevel inout port '" << p.second->name () << "' not connected to SB_IO PACKAGE_PIN")); } } } std::set<Net *, IdLess> boundary_nets; for (Instance *inst2 : top->instances()) { if (inst2->instance_of() == io_model) { Port *p = inst2->find_port("PACKAGE_PIN"); Net *n = p->connection(); Port *q = p->connection_other_port(); if (!n || !q || !isa<Model>(q->node())) fatal("SB_IO PACKAGE_PIN not connected to toplevel port"); extend(boundary_nets, n); } } for (const auto &p : top->nets()) { Net *n = p.second; if (contains(boundary_nets, n)) continue; int n_drivers = 0; if (n->is_constant()) ++n_drivers; for (Port *p2 : n->connections()) { if (p2->is_output()) ++n_drivers; } if (n_drivers > 1) fatal(fmt("net `" << n->name() << "' has multiple drivers")); } return d; } Design * read_blif(const std::string &filename) { std::string expanded = expand_filename(filename); std::ifstream fs(expanded); if (fs.fail()) fatal(fmt("read_blif: failed to open `" << expanded << "': " << strerror(errno))); BlifParser parser(filename, fs); return parser.parse(); } Design * read_blif(const std::string &filename, std::istream &s) { BlifParser parser(filename, s); return parser.parse(); } <commit_msg>blif: Check the top model has been defined<commit_after>/* Copyright (C) 2015 Cotton Seed This file is part of arachne-pnr. Arachne-pnr is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "util.hh" #include "netlist.hh" #include "line_parser.hh" #include "bitvector.hh" #include "casting.hh" #include <cctype> #include <cstring> #include <istream> #include <fstream> #include <iostream> #include <string> class BlifParser : public LineParser { BitVector stobv(const std::string &s_); public: BlifParser(const std::string &f, std::istream &s_) : LineParser(f, s_) {} Design *parse(); }; BitVector BlifParser::stobv(const std::string &s_) { int n = s_.size(); BitVector bv(n); for (int i = 0; i < n; ++i) { char c = s_[(n - 1) - i]; if (c == '1') bv[i] = true; else if (c == '0' || c == 'x' || c == 'X') ; else fatal("invalid character in integer constant"); } return bv; } Design * BlifParser::parse() { Design *d = new Design; d->create_standard_models(); Model *io_model = d->find_model("SB_IO"); Model *top = nullptr; std::vector<std::pair<Net *, Net *>> unify; Instance *inst = nullptr; for (;;) { if (eof()) goto M; read_line(); if (line.empty()) continue; if (line[0] == '.') { L: std::string cmd = words[0]; if (cmd == ".model") { if (words.size() != 2) fatal("invalid .model directive"); assert(top == nullptr); top = new Model(d, words[1]); d->set_top(top); } else if (cmd == ".inputs") { for (unsigned i = 1; i < words.size(); i ++) { Port *port = top->find_port(words[i]); if (port) { if (port->direction() == Direction::OUT) port->set_direction(Direction::INOUT); } else port = top->add_port(words[i], Direction::IN); Net *net = top->find_or_add_net(words[i]); port->connect(net); } } else if (cmd == ".outputs") { for (unsigned i = 1; i < words.size(); i ++) { Port *port = top->find_port(words[i]); if (port) { if (port->direction() == Direction::IN) port->set_direction(Direction::INOUT); } else port = top->add_port(words[i], Direction::OUT); Net *net = top->find_or_add_net(words[i]); port->connect(net); } } else if (cmd == ".names") { LexicalPosition names_lp = lp; Net *names_net = nullptr; unsigned n = words.size(); if (n == 2) { names_net = top->find_or_add_net(words[1]); names_net->set_is_constant(true); names_net->set_constant(Value::ZERO); } else if (n == 3) { unify.push_back(std::make_pair(top->find_or_add_net(words[1]), top->find_or_add_net(words[2]))); } else fatal("invalid .names directive"); bool saw11 = false; for (;;) { if (eof()) { if (n == 3 && !saw11) names_lp.fatal("invalid .names directive"); goto M; } read_line(); if (line.empty()) continue; if (line[0] == '.') { if (n == 3 && !saw11) names_lp.fatal("invalid .names directive"); goto L; } if (words.size() != n - 1) fatal("invalid .names entry"); if (n == 2) { const std::string &output = words[0]; if (output == "1") names_net->set_constant(Value::ONE); else if (output != "0") fatal("invalid .names entry"); } else { assert(n == 3); if (words[0] != "1" || words[1] != "1") fatal("invalid .names entry"); saw11 = true; } } } else if (cmd == ".gate") { if (words.size() < 2) fatal("invalid .gate directive, missing name"); const std::string &n = words[1]; Model *inst_of = d->find_model(n); if (!inst_of) fatal(fmt("unknown model `" << n << "'")); inst = top->add_instance(inst_of); for (unsigned i = 2; i < words.size(); i ++) { const std::string &w = words[i]; std::size_t p = w.find('='); if (p == std::string::npos) fatal("invalid formal-actual"); std::string formal(w, 0, p), actual(w, p+1); if (actual.empty()) continue; Port *port = inst->find_port(formal); if (!port) fatal(fmt("unknown formal `" << formal << "'")); Net *net = top->find_or_add_net(actual); port->connect(net); } } else if (cmd == ".attr") { if (words.size() != 3) fatal("invalid .attr directive"); if (!inst) fatal("no gate for .attr directive"); if (words[2][0] == '"') { assert(words[2].back() == '"'); inst->set_attr(words[1], Const(lp, words[2].substr(1, words[2].size() - 2))); } else { inst->set_attr(words[1], Const(lp, stobv(words[2]))); } } else if (cmd == ".param") { if (words.size() != 3) fatal("invalid .param directive"); if (!inst) fatal("no gate for .param directive"); if (words[2][0] == '"') { assert(words[2].back() == '"'); inst->set_param(words[1], Const(lp, words[2].substr(1, words[2].size() - 2))); } else { inst->set_param(words[1], Const(lp, stobv(words[2]))); } } else if (cmd == ".end") goto M; else fatal("unknown directive"); } else fatal("expected directive"); } M: if (!top) fatal("no top model has been defined"); // unify std::map<Net *, Net *, IdLess> replacement; for (const auto &p : unify) { // n1 drives n2 Net *n1 = p.first, *n2 = p.second; Net *r = n1; while (Net *t = lookup_or_default(replacement, r, nullptr)) r = t; Net *x = n1; while (x != r) { auto i = replacement.find(x); assert(i != replacement.end()); x = i->second; i->second = r; } if (n2 == r) fatal(".names cycle\n"); n2->replace(r); extend(replacement, n2, r); } for (const auto &p : replacement) { Net *n = p.first; top->remove_net(n); delete n; } for (const auto &p : top->ports()) { if (p.second->is_bidir()) { Net *n = p.second->connection(); if (n) { Port *q = p.second->connection_other_port(); if (!q || !isa<Instance>(q->node()) || cast<Instance>(q->node())->instance_of() != io_model || q->name() != "PACKAGE_PIN") fatal(fmt("toplevel inout port '" << p.second->name () << "' not connected to SB_IO PACKAGE_PIN")); } } } std::set<Net *, IdLess> boundary_nets; for (Instance *inst2 : top->instances()) { if (inst2->instance_of() == io_model) { Port *p = inst2->find_port("PACKAGE_PIN"); Net *n = p->connection(); Port *q = p->connection_other_port(); if (!n || !q || !isa<Model>(q->node())) fatal("SB_IO PACKAGE_PIN not connected to toplevel port"); extend(boundary_nets, n); } } for (const auto &p : top->nets()) { Net *n = p.second; if (contains(boundary_nets, n)) continue; int n_drivers = 0; if (n->is_constant()) ++n_drivers; for (Port *p2 : n->connections()) { if (p2->is_output()) ++n_drivers; } if (n_drivers > 1) fatal(fmt("net `" << n->name() << "' has multiple drivers")); } return d; } Design * read_blif(const std::string &filename) { std::string expanded = expand_filename(filename); std::ifstream fs(expanded); if (fs.fail()) fatal(fmt("read_blif: failed to open `" << expanded << "': " << strerror(errno))); BlifParser parser(filename, fs); return parser.parse(); } Design * read_blif(const std::string &filename, std::istream &s) { BlifParser parser(filename, s); return parser.parse(); } <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <signaldata/FsReadWriteReq.hpp> bool printFSREADWRITEREQ(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo){ bool ret = true; const FsReadWriteReq * const sig = (FsReadWriteReq *) theData; fprintf(output, " UserPointer: %d\n", sig->userPointer); fprintf(output, " FilePointer: %d\n", sig->filePointer); fprintf(output, " UserReference: H\'%.8x", sig->userReference); fprintf(output, " Operation flag: H\'%.8x (", sig->operationFlag); if (sig->getSyncFlag(sig->operationFlag) == true) fprintf(output, "Sync,"); else fprintf(output, "No sync,"); fprintf(output, " Format="); switch(sig->getFormatFlag(sig->operationFlag)){ case FsReadWriteReq::fsFormatListOfPairs: fprintf(output, "List of pairs)\n"); break; case FsReadWriteReq::fsFormatArrayOfPages: fprintf(output, "Array of pages)\n"); break; case FsReadWriteReq::fsFormatListOfMemPages: fprintf(output, "List of mem pages)\n"); break; default: fprintf(output, "fsFormatMax not handled\n"); ret = false; break; } fprintf(output, " varIndex: %d\n", sig->varIndex); fprintf(output, " numberOfPages: %d\n", sig->numberOfPages); fprintf(output, " pageData: "); switch(sig->getFormatFlag(sig->operationFlag)){ case FsReadWriteReq::fsFormatListOfPairs: for (unsigned int i = 0; i < sig->numberOfPages*2; i += 2){ fprintf(output, " H\'%.8x, H\'%.8x\n", sig->data.pageData[i], sig->data.pageData[i + 1]); } break; case FsReadWriteReq::fsFormatArrayOfPages: fprintf(output, " H\'%.8x, H\'%.8x\n", sig->data.pageData[0], sig->data.pageData[1]); break; case FsReadWriteReq::fsFormatListOfMemPages: for (unsigned int i = 0; i < (sig->numberOfPages + 1); i++){ fprintf(output, " H\'%.8x, ", sig->data.pageData[i]); } break; default: fprintf(output, "Impossible event\n"); } fprintf(output, "\n"); return ret; } <commit_msg>FsReadWriteReq.cpp: compile error on hpux<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <signaldata/FsReadWriteReq.hpp> bool printFSREADWRITEREQ(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo){ bool ret = true; const FsReadWriteReq * const sig = (FsReadWriteReq *) theData; fprintf(output, " UserPointer: %d\n", sig->userPointer); fprintf(output, " FilePointer: %d\n", sig->filePointer); fprintf(output, " UserReference: H\'%.8x", sig->userReference); fprintf(output, " Operation flag: H\'%.8x (", sig->operationFlag); if (sig->getSyncFlag(sig->operationFlag) == true) fprintf(output, "Sync,"); else fprintf(output, "No sync,"); fprintf(output, " Format="); switch(sig->getFormatFlag(sig->operationFlag)){ case FsReadWriteReq::fsFormatListOfPairs: fprintf(output, "List of pairs)\n"); break; case FsReadWriteReq::fsFormatArrayOfPages: fprintf(output, "Array of pages)\n"); break; case FsReadWriteReq::fsFormatListOfMemPages: fprintf(output, "List of mem pages)\n"); break; default: fprintf(output, "fsFormatMax not handled\n"); ret = false; break; } fprintf(output, " varIndex: %d\n", sig->varIndex); fprintf(output, " numberOfPages: %d\n", sig->numberOfPages); fprintf(output, " pageData: "); unsigned int i; switch(sig->getFormatFlag(sig->operationFlag)){ case FsReadWriteReq::fsFormatListOfPairs: for (i= 0; i < sig->numberOfPages*2; i += 2){ fprintf(output, " H\'%.8x, H\'%.8x\n", sig->data.pageData[i], sig->data.pageData[i + 1]); } break; case FsReadWriteReq::fsFormatArrayOfPages: fprintf(output, " H\'%.8x, H\'%.8x\n", sig->data.pageData[0], sig->data.pageData[1]); break; case FsReadWriteReq::fsFormatListOfMemPages: for (i= 0; i < (sig->numberOfPages + 1); i++){ fprintf(output, " H\'%.8x, ", sig->data.pageData[i]); } break; default: fprintf(output, "Impossible event\n"); } fprintf(output, "\n"); return ret; } <|endoftext|>
<commit_before>#include <babylon/materials/textures/mirror_texture.h> #include <nlohmann/json.hpp> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/core/structs.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/misc/string_tools.h> #include <babylon/postprocesses/blur_post_process.h> namespace BABYLON { MirrorTexture::MirrorTexture(const std::string& iName, const std::variant<int, RenderTargetSize, float>& size, Scene* iScene, bool generateMipMaps, unsigned int type, unsigned int iSamplingMode, bool generateDepthBuffer) : RenderTargetTexture{iName, size, iScene, generateMipMaps, true, type, false, iSamplingMode, generateDepthBuffer} , mirrorPlane{Plane(0.f, 1.f, 0.f, 1.f)} , blurRatio{this, &MirrorTexture::get_blurRatio, &MirrorTexture::set_blurRatio} , adaptiveBlurKernel{this, &MirrorTexture::set_adaptiveBlurKernel} , blurKernel{this, &MirrorTexture::set_blurKernel} , blurKernelX{this, &MirrorTexture::get_blurKernelX, &MirrorTexture::set_blurKernelX} , blurKernelY{this, &MirrorTexture::get_blurKernelY, &MirrorTexture::set_blurKernelY} , scene{iScene} , _imageProcessingConfigChangeObserver{nullptr} , _transformMatrix{Matrix::Zero()} , _mirrorMatrix{Matrix::Zero()} , _blurX{nullptr} , _blurY{nullptr} , _adaptiveBlurKernel{0.f} , _blurKernelX{0.f} , _blurKernelY{0.f} , _blurRatio{1.f} , _saveClipPlane{std::nullopt} { ignoreCameraViewport = true; _updateGammaSpace(); _imageProcessingConfigChangeObserver = scene->imageProcessingConfiguration()->onUpdateParameters.add( [this](ImageProcessingConfiguration* /*ipc*/, EventState& /*es*/) -> void { _updateGammaSpace(); }); const auto engine = getScene()->getEngine(); onBeforeBindObservable.add( [engine, name = this->name](RenderTargetTexture*, EventState&) -> void { engine->_debugPushGroup(StringTools::printf("mirror generation for %s", name.c_str()), 1); }); onAfterUnbindObservable.add( [engine](RenderTargetTexture*, EventState&) -> void { engine->_debugPopGroup(1); }); onBeforeRenderObservable.add([this](int*, EventState&) -> void { const auto scene_ = getScene(); Matrix::ReflectionToRef(mirrorPlane, _mirrorMatrix); _mirrorMatrix.multiplyToRef(scene->getViewMatrix(), _transformMatrix); scene_->setTransformMatrix(_transformMatrix, scene_->getProjectionMatrix()); _saveClipPlane = scene->clipPlane; scene_->clipPlane = mirrorPlane; scene_->getEngine()->cullBackFaces = false; scene_->setMirroredCameraPosition( Vector3::TransformCoordinates(scene_->activeCamera()->globalPosition(), _mirrorMatrix)); }); onAfterRenderObservable.add([this](int*, EventState&) -> void { const auto scene_ = getScene(); scene_->updateTransformMatrix(); scene_->getEngine()->cullBackFaces = std::nullopt; scene_->_mirroredCameraPosition = nullptr; scene_->clipPlane = _saveClipPlane; }); } MirrorTexture::~MirrorTexture() = default; void MirrorTexture::set_blurRatio(float value) { if (stl_util::almost_equal(_blurRatio, value)) { return; } _blurRatio = value; _preparePostProcesses(); } float MirrorTexture::get_blurRatio() const { return _blurRatio; } void MirrorTexture::set_adaptiveBlurKernel(float value) { _adaptiveBlurKernel = value; _autoComputeBlurKernel(); } void MirrorTexture::set_blurKernel(float value) { blurKernelX = value; blurKernelY = value; } void MirrorTexture::set_blurKernelX(float value) { if (stl_util::almost_equal(_blurKernelX, value)) { return; } _blurKernelX = value; _preparePostProcesses(); } float MirrorTexture::get_blurKernelX() const { return _blurKernelX; } void MirrorTexture::set_blurKernelY(float value) { if (stl_util::almost_equal(_blurKernelY, value)) { return; } _blurKernelY = value; _preparePostProcesses(); } float MirrorTexture::get_blurKernelY() const { return _blurKernelY; } void MirrorTexture::_autoComputeBlurKernel() { const auto engine = getScene()->getEngine(); const auto dw = static_cast<float>(getRenderWidth()) / static_cast<float>(engine->getRenderWidth()); const auto dh = static_cast<float>(getRenderHeight()) / static_cast<float>(engine->getRenderHeight()); blurKernelX = _adaptiveBlurKernel * dw; blurKernelY = _adaptiveBlurKernel * dh; } void MirrorTexture::_onRatioRescale() { if (_sizeRatio != 0.f) { resize(_initialSizeParameter); if (_adaptiveBlurKernel == 0.f) { _preparePostProcesses(); } } if (_adaptiveBlurKernel != 0.f) { _autoComputeBlurKernel(); } } void MirrorTexture::_updateGammaSpace() { gammaSpace = !scene->imageProcessingConfiguration()->isEnabled() || !scene->imageProcessingConfiguration()->applyByPostProcess(); } void MirrorTexture::_preparePostProcesses() { clearPostProcesses(true); if (_blurKernelX != 0.f && _blurKernelY != 0.f) { const auto engine = getScene()->getEngine(); const auto iTextureType = engine->getCaps().textureFloatRender ? Constants::TEXTURETYPE_FLOAT : Constants::TEXTURETYPE_HALF_FLOAT; _blurX = BlurPostProcess::New("horizontal blur", Vector2(1.f, 0.f), _blurKernelX, _blurRatio, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, engine, false, iTextureType); _blurX->autoClear = false; if (_blurRatio == 1.f && samples() < 2 && _texture) { _blurX->inputTexture = _texture; } else { _blurX->alwaysForcePOT = true; } _blurY = BlurPostProcess::New("vertical blur", Vector2(0.f, 1.f), _blurKernelY, _blurRatio, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, engine, false, iTextureType); _blurY->autoClear = false; _blurY->alwaysForcePOT = _blurRatio != 1.f; addPostProcess(_blurX); addPostProcess(_blurY); } else { if (_blurY) { removePostProcess(_blurY); _blurY->dispose(); _blurY = nullptr; } if (_blurX) { removePostProcess(_blurX); _blurX->dispose(); _blurX = nullptr; } } } MirrorTexturePtr MirrorTexture::clone() { const auto iScene = getScene(); if (!iScene) { return nullptr; } const auto textureSize = getSize(); const auto newTexture = MirrorTexture::New(name, // RenderTargetSize{textureSize.width, textureSize.height}, // iScene, // _renderTargetOptions.generateMipMaps.value(), // _renderTargetOptions.type.value(), // _renderTargetOptions.samplingMode.value(), // _renderTargetOptions.generateDepthBuffer.value() // ); // Base texture newTexture->hasAlpha = hasAlpha(); newTexture->level = level; // Mirror Texture newTexture->mirrorPlane = mirrorPlane; if (!renderList().empty()) { newTexture->renderList = renderList(); } return newTexture; } json MirrorTexture::serialize() const { return nullptr; } void MirrorTexture::dispose() { RenderTargetTexture::dispose(); scene->imageProcessingConfiguration()->onUpdateParameters.remove( _imageProcessingConfigChangeObserver); } } // end of namespace BABYLON <commit_msg>Checking for textureFloatLinearFiltering setting<commit_after>#include <babylon/materials/textures/mirror_texture.h> #include <nlohmann/json.hpp> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/core/structs.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/misc/string_tools.h> #include <babylon/postprocesses/blur_post_process.h> namespace BABYLON { MirrorTexture::MirrorTexture(const std::string& iName, const std::variant<int, RenderTargetSize, float>& size, Scene* iScene, bool generateMipMaps, unsigned int type, unsigned int iSamplingMode, bool generateDepthBuffer) : RenderTargetTexture{iName, size, iScene, generateMipMaps, true, type, false, iSamplingMode, generateDepthBuffer} , mirrorPlane{Plane(0.f, 1.f, 0.f, 1.f)} , blurRatio{this, &MirrorTexture::get_blurRatio, &MirrorTexture::set_blurRatio} , adaptiveBlurKernel{this, &MirrorTexture::set_adaptiveBlurKernel} , blurKernel{this, &MirrorTexture::set_blurKernel} , blurKernelX{this, &MirrorTexture::get_blurKernelX, &MirrorTexture::set_blurKernelX} , blurKernelY{this, &MirrorTexture::get_blurKernelY, &MirrorTexture::set_blurKernelY} , scene{iScene} , _imageProcessingConfigChangeObserver{nullptr} , _transformMatrix{Matrix::Zero()} , _mirrorMatrix{Matrix::Zero()} , _blurX{nullptr} , _blurY{nullptr} , _adaptiveBlurKernel{0.f} , _blurKernelX{0.f} , _blurKernelY{0.f} , _blurRatio{1.f} , _saveClipPlane{std::nullopt} { ignoreCameraViewport = true; _updateGammaSpace(); _imageProcessingConfigChangeObserver = scene->imageProcessingConfiguration()->onUpdateParameters.add( [this](ImageProcessingConfiguration* /*ipc*/, EventState& /*es*/) -> void { _updateGammaSpace(); }); const auto engine = getScene()->getEngine(); onBeforeBindObservable.add( [engine, name = this->name](RenderTargetTexture*, EventState&) -> void { engine->_debugPushGroup(StringTools::printf("mirror generation for %s", name.c_str()), 1); }); onAfterUnbindObservable.add( [engine](RenderTargetTexture*, EventState&) -> void { engine->_debugPopGroup(1); }); onBeforeRenderObservable.add([this](int*, EventState&) -> void { const auto scene_ = getScene(); Matrix::ReflectionToRef(mirrorPlane, _mirrorMatrix); _mirrorMatrix.multiplyToRef(scene->getViewMatrix(), _transformMatrix); scene_->setTransformMatrix(_transformMatrix, scene_->getProjectionMatrix()); _saveClipPlane = scene->clipPlane; scene_->clipPlane = mirrorPlane; scene_->getEngine()->cullBackFaces = false; scene_->setMirroredCameraPosition( Vector3::TransformCoordinates(scene_->activeCamera()->globalPosition(), _mirrorMatrix)); }); onAfterRenderObservable.add([this](int*, EventState&) -> void { const auto scene_ = getScene(); scene_->updateTransformMatrix(); scene_->getEngine()->cullBackFaces = std::nullopt; scene_->_mirroredCameraPosition = nullptr; scene_->clipPlane = _saveClipPlane; }); } MirrorTexture::~MirrorTexture() = default; void MirrorTexture::set_blurRatio(float value) { if (stl_util::almost_equal(_blurRatio, value)) { return; } _blurRatio = value; _preparePostProcesses(); } float MirrorTexture::get_blurRatio() const { return _blurRatio; } void MirrorTexture::set_adaptiveBlurKernel(float value) { _adaptiveBlurKernel = value; _autoComputeBlurKernel(); } void MirrorTexture::set_blurKernel(float value) { blurKernelX = value; blurKernelY = value; } void MirrorTexture::set_blurKernelX(float value) { if (stl_util::almost_equal(_blurKernelX, value)) { return; } _blurKernelX = value; _preparePostProcesses(); } float MirrorTexture::get_blurKernelX() const { return _blurKernelX; } void MirrorTexture::set_blurKernelY(float value) { if (stl_util::almost_equal(_blurKernelY, value)) { return; } _blurKernelY = value; _preparePostProcesses(); } float MirrorTexture::get_blurKernelY() const { return _blurKernelY; } void MirrorTexture::_autoComputeBlurKernel() { const auto engine = getScene()->getEngine(); const auto dw = static_cast<float>(getRenderWidth()) / static_cast<float>(engine->getRenderWidth()); const auto dh = static_cast<float>(getRenderHeight()) / static_cast<float>(engine->getRenderHeight()); blurKernelX = _adaptiveBlurKernel * dw; blurKernelY = _adaptiveBlurKernel * dh; } void MirrorTexture::_onRatioRescale() { if (_sizeRatio != 0.f) { resize(_initialSizeParameter); if (_adaptiveBlurKernel == 0.f) { _preparePostProcesses(); } } if (_adaptiveBlurKernel != 0.f) { _autoComputeBlurKernel(); } } void MirrorTexture::_updateGammaSpace() { gammaSpace = !scene->imageProcessingConfiguration()->isEnabled() || !scene->imageProcessingConfiguration()->applyByPostProcess(); } void MirrorTexture::_preparePostProcesses() { clearPostProcesses(true); if (_blurKernelX != 0.f && _blurKernelY != 0.f) { const auto engine = getScene()->getEngine(); const auto iTextureType = engine->getCaps().textureFloatRender && engine->getCaps().textureFloatLinearFiltering ? Constants::TEXTURETYPE_FLOAT : Constants::TEXTURETYPE_HALF_FLOAT; _blurX = BlurPostProcess::New("horizontal blur", Vector2(1.f, 0.f), _blurKernelX, _blurRatio, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, engine, false, iTextureType); _blurX->autoClear = false; if (_blurRatio == 1.f && samples() < 2 && _texture) { _blurX->inputTexture = _texture; } else { _blurX->alwaysForcePOT = true; } _blurY = BlurPostProcess::New("vertical blur", Vector2(0.f, 1.f), _blurKernelY, _blurRatio, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, engine, false, iTextureType); _blurY->autoClear = false; _blurY->alwaysForcePOT = _blurRatio != 1.f; addPostProcess(_blurX); addPostProcess(_blurY); } else { if (_blurY) { removePostProcess(_blurY); _blurY->dispose(); _blurY = nullptr; } if (_blurX) { removePostProcess(_blurX); _blurX->dispose(); _blurX = nullptr; } } } MirrorTexturePtr MirrorTexture::clone() { const auto iScene = getScene(); if (!iScene) { return nullptr; } const auto textureSize = getSize(); const auto newTexture = MirrorTexture::New(name, // RenderTargetSize{textureSize.width, textureSize.height}, // iScene, // _renderTargetOptions.generateMipMaps.value(), // _renderTargetOptions.type.value(), // _renderTargetOptions.samplingMode.value(), // _renderTargetOptions.generateDepthBuffer.value() // ); // Base texture newTexture->hasAlpha = hasAlpha(); newTexture->level = level; // Mirror Texture newTexture->mirrorPlane = mirrorPlane; if (!renderList().empty()) { newTexture->renderList = renderList(); } return newTexture; } json MirrorTexture::serialize() const { return nullptr; } void MirrorTexture::dispose() { RenderTargetTexture::dispose(); scene->imageProcessingConfiguration()->onUpdateParameters.remove( _imageProcessingConfigChangeObserver); } } // end of namespace BABYLON <|endoftext|>
<commit_before>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 "cplusplus.h" class Cxx : public CPlusPlus { public: Cxx(FILE* file) : CPlusPlus(file) { } virtual void at(const StructType* node) { if (node->getJavadoc().size()) { write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str()); } write("struct %s", node->getName().c_str()); if (!node->isLeaf()) { write("\n%s{\n", indentString.c_str()); indent(); printChildren(node); unindent(); write("%s}", indentString.c_str()); } } virtual void at(const ExceptDcl* node) { if (node->getJavadoc().size()) { write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str()); } write("struct %s", node->getName().c_str()); write("\n%s{\n", indentString.c_str()); indent(); printChildren(node); unindent(); write("%s}", indentString.c_str()); } virtual void at(const Interface* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("class %s", node->getName().c_str()); if (node->getExtends()) { write(" : "); prefix = "public "; node->getExtends()->accept(this); prefix = ""; } if (!node->isLeaf()) { writeln(""); writeln("{"); writeln("public:"); indent(); // printChildren(node); int count = 0; for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { if (dynamic_cast<PragmaID*>(*i) || (*i)->isSequence(node) || (*i)->isNative(node)) { continue; } optionalStage = 0; do { callbackStage = 0; do { if (0 < count) { write(";\n"); } callbackCount = 0; optionalCount = 0; ++count; writetab(); (*i)->accept(this); ++callbackStage; } while (callbackStage < (1u << callbackCount)); ++optionalStage; } while (optionalStage <= optionalCount); } if (0 < count) { write(";\n"); } writeln("static const char* iid()"); writeln("{"); indent(); writeln("static const char* name = \"%s\";", node->getQualifiedName().c_str()); writeln("return name;"); unindent(); writeln("}"); if (Interface* constructor = node->getConstructor()) { // Process constructors. constructorMode = true; for (NodeList::iterator i = constructor->begin(); i != constructor->end(); ++i) { writetab(); (*i)->accept(this); } constructorMode = false; writeln("static Constructor* getConstructor()"); writeln("{"); indent(); writeln("return constructor;"); unindent(); writeln("}"); writeln("static void setConstructor(Constructor* ctor)"); writeln("{"); indent(); writeln("constructor = ctor;"); unindent(); writeln("}"); unindent(); writeln("private:"); indent(); writeln("static Constructor* constructor;"); } unindent(); writetab(); write("}"); } if (node->getConstructor()) { write(";\n\n"); writetab(); write("%s::Constructor* %s::constructor __attribute__((weak))", node->getName().c_str(), node->getName().c_str()); } } virtual void at(const NativeType* node) { if (node->getName() == "void_pointer") { write("void*"); } else { write("%s", node->getName().c_str()); } } virtual void at(const BinaryExpr* node) { node->getLeft()->accept(this); write(" %s ", node->getName().c_str()); node->getRight()->accept(this); } virtual void at(const UnaryExpr* node) { write("%s", node->getName().c_str()); NodeList::iterator elem = node->begin(); (*elem)->accept(this); } virtual void at(const GroupingExpression* node) { write("("); NodeList::iterator elem = node->begin(); (*elem)->accept(this); write(")"); } virtual void at(const Literal* node) { if (node->getName() == "TRUE") { write("true"); } else if (node->getName() == "FALSE") { write("false"); } else { write("%s", node->getName().c_str()); } } virtual void at(const PragmaID* node) { } virtual void at(const Member* node) { if (node->isTypedef()) { write("typedef "); } if (node->isInterface(node->getParent())) { node->getSpec()->accept(this); write(" %s", node->getName().c_str()); } else { node->getSpec()->accept(this); write(" %s", node->getName().c_str()); } } virtual void at(const ArrayDcl* node) { assert(!node->isLeaf()); at(static_cast<const Member*>(node)); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { write("["); (*i)->accept(this); write("]"); } } virtual void at(const ConstDcl* node) { if (node->getJavadoc().size()) { writeln("%s", node->getJavadoc().c_str()); writetab(); } write("static const "); at(static_cast<const Member*>(node)); write(" = "); node->getExp()->accept(this); } virtual void at(const Attribute* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } // getter CPlusPlus::getter(node); write(" = 0"); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { // setter write(";\n"); writetab(); CPlusPlus::setter(node); write(" = 0"); } } virtual void at(const OpDcl* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } CPlusPlus::at(node); if (!constructorMode) { write(" = 0"); } else { writeln(""); writeln("{"); indent(); writeln("if (constructor)"); indent(); writetab(); write("constructor->createInstance("); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { if (i != node->begin()) { write(", "); } write("%s", (*i)->getName().c_str()); } write(");"); writeln(""); unindent(); unindent(); writeln("}"); } } }; class Import : public Visitor { FILE* file; public: Import(FILE* file) : file(file) { } virtual void at(const Node* node) { if (1 < node->getRank()) { return; } visitChildren(node); } virtual void at(const Include* node) { if (1 < node->getRank()) { return; } if (node->isSystem()) { fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str()); } else { fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str()); } } }; void printCxx(const std::string& filename) { printf("# %s\n", filename.c_str()); FILE* file = fopen(filename.c_str(), "w"); if (!file) { return; } std::string included = getIncludedName(filename); fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "#ifndef %s\n", included.c_str()); fprintf(file, "#define %s\n\n", included.c_str()); Import import(file); getSpecification()->accept(&import); Cxx cxx(file); getSpecification()->accept(&cxx); fprintf(file, "#endif // %s\n", included.c_str()); fclose(file); } <commit_msg>(at(const Interface*)) : Clean up.<commit_after>/* * Copyright 2008, 2009 Google Inc. * Copyright 2007 Nintendo Co., Ltd. * * 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 "cplusplus.h" class Cxx : public CPlusPlus { public: Cxx(FILE* file) : CPlusPlus(file) { } virtual void at(const StructType* node) { if (node->getJavadoc().size()) { write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str()); } write("struct %s", node->getName().c_str()); if (!node->isLeaf()) { write("\n%s{\n", indentString.c_str()); indent(); printChildren(node); unindent(); write("%s}", indentString.c_str()); } } virtual void at(const ExceptDcl* node) { if (node->getJavadoc().size()) { write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str()); } write("struct %s", node->getName().c_str()); write("\n%s{\n", indentString.c_str()); indent(); printChildren(node); unindent(); write("%s}", indentString.c_str()); } virtual void at(const Interface* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } write("class %s", node->getName().c_str()); if (node->getExtends()) { write(" : "); prefix = "public "; node->getExtends()->accept(this); prefix = ""; } if (!node->isLeaf()) { writeln(""); writeln("{"); writeln("public:"); indent(); // printChildren(node); int count = 0; for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { if (dynamic_cast<PragmaID*>(*i) || (*i)->isSequence(node) || (*i)->isNative(node)) { continue; } optionalStage = 0; do { callbackStage = 0; do { if (0 < count) { write(";\n"); } optionalCount = 0; callbackCount = 0; ++count; writetab(); (*i)->accept(this); ++callbackStage; } while (callbackStage < (1u << callbackCount)); ++optionalStage; } while (optionalStage <= optionalCount); } if (0 < count) { write(";\n"); } writeln("static const char* iid()"); writeln("{"); indent(); writeln("static const char* name = \"%s\";", node->getQualifiedName().c_str()); writeln("return name;"); unindent(); writeln("}"); if (Interface* constructor = node->getConstructor()) { // Process constructors. constructorMode = true; for (NodeList::iterator i = constructor->begin(); i != constructor->end(); ++i) { writetab(); (*i)->accept(this); } constructorMode = false; writeln("static Constructor* getConstructor()"); writeln("{"); indent(); writeln("return constructor;"); unindent(); writeln("}"); writeln("static void setConstructor(Constructor* ctor)"); writeln("{"); indent(); writeln("constructor = ctor;"); unindent(); writeln("}"); unindent(); writeln("private:"); indent(); writeln("static Constructor* constructor;"); } unindent(); writetab(); write("}"); } if (node->getConstructor()) { write(";\n\n"); writetab(); write("%s::Constructor* %s::constructor __attribute__((weak))", node->getName().c_str(), node->getName().c_str()); } } virtual void at(const NativeType* node) { if (node->getName() == "void_pointer") { write("void*"); } else { write("%s", node->getName().c_str()); } } virtual void at(const BinaryExpr* node) { node->getLeft()->accept(this); write(" %s ", node->getName().c_str()); node->getRight()->accept(this); } virtual void at(const UnaryExpr* node) { write("%s", node->getName().c_str()); NodeList::iterator elem = node->begin(); (*elem)->accept(this); } virtual void at(const GroupingExpression* node) { write("("); NodeList::iterator elem = node->begin(); (*elem)->accept(this); write(")"); } virtual void at(const Literal* node) { if (node->getName() == "TRUE") { write("true"); } else if (node->getName() == "FALSE") { write("false"); } else { write("%s", node->getName().c_str()); } } virtual void at(const PragmaID* node) { } virtual void at(const Member* node) { if (node->isTypedef()) { write("typedef "); } if (node->isInterface(node->getParent())) { node->getSpec()->accept(this); write(" %s", node->getName().c_str()); } else { node->getSpec()->accept(this); write(" %s", node->getName().c_str()); } } virtual void at(const ArrayDcl* node) { assert(!node->isLeaf()); at(static_cast<const Member*>(node)); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { write("["); (*i)->accept(this); write("]"); } } virtual void at(const ConstDcl* node) { if (node->getJavadoc().size()) { writeln("%s", node->getJavadoc().c_str()); writetab(); } write("static const "); at(static_cast<const Member*>(node)); write(" = "); node->getExp()->accept(this); } virtual void at(const Attribute* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } // getter CPlusPlus::getter(node); write(" = 0"); if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable()) { // setter write(";\n"); writetab(); CPlusPlus::setter(node); write(" = 0"); } } virtual void at(const OpDcl* node) { if (node->getJavadoc().size()) { write("%s\n", node->getJavadoc().c_str()); writetab(); } CPlusPlus::at(node); if (!constructorMode) { write(" = 0"); } else { writeln(""); writeln("{"); indent(); writeln("if (constructor)"); indent(); writetab(); write("constructor->createInstance("); for (NodeList::iterator i = node->begin(); i != node->end(); ++i) { if (i != node->begin()) { write(", "); } write("%s", (*i)->getName().c_str()); } write(");"); writeln(""); unindent(); unindent(); writeln("}"); } } }; class Import : public Visitor { FILE* file; public: Import(FILE* file) : file(file) { } virtual void at(const Node* node) { if (1 < node->getRank()) { return; } visitChildren(node); } virtual void at(const Include* node) { if (1 < node->getRank()) { return; } if (node->isSystem()) { fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str()); } else { fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str()); } } }; void printCxx(const std::string& filename) { printf("# %s\n", filename.c_str()); FILE* file = fopen(filename.c_str(), "w"); if (!file) { return; } std::string included = getIncludedName(filename); fprintf(file, "// Generated by esidl %s.\n\n", VERSION); fprintf(file, "#ifndef %s\n", included.c_str()); fprintf(file, "#define %s\n\n", included.c_str()); Import import(file); getSpecification()->accept(&import); Cxx cxx(file); getSpecification()->accept(&cxx); fprintf(file, "#endif // %s\n", included.c_str()); fclose(file); } <|endoftext|>
<commit_before>#include <memory> #include <cassert> #include "eval.hh" #include "util.hh" #include "keyword.hh" #include "symbol.hh" #include "cons.hh" #include "function.hh" #include "printer.hh" using namespace std; enum class VM_op : int{ nop = 0, if_, set_ }; namespace { void funcall(const Function* fun, Lisp_ptr args){ const auto& argi = fun->arg_info(); const auto env = fun->closure(); const auto set_arg = [&](Symbol* sym, Lisp_ptr p){ if(env){ VM.local_set(sym, p); }else{ VM.stack().push(p); } }; Lisp_ptr arg_name = argi.head; VM.return_value() = {}; if(env){ VM.enter_frame(push_frame(env)); } // push args int argc = 0; if(!do_list(args, [&](Cons* cell) -> bool{ assert(argc <= argi.required_args); if(argc == argi.required_args) return false; VM.code().push(cell->car()); eval(); auto evaled = VM.return_value(); if(!evaled){ fprintf(stderr, "eval error: evaluating func's arg failed!!\n"); return false; } auto arg_name_cell = arg_name.get<Cons*>(); set_arg(arg_name_cell->car().get<Symbol*>(), evaled); arg_name = arg_name_cell->cdr(); ++argc; return true; }, [&](Lisp_ptr dot_cdr) -> bool{ assert(argc <= argi.required_args); if(argc < argi.required_args){ fprintf(stderr, "eval error: internal argument counter mismatched!! (read %d args)\n", argc); return false; } if(argi.variadic){ set_arg(arg_name.get<Symbol*>(), dot_cdr); ++argc; return true; }else{ if(!nullp(dot_cdr)){ fprintf(stderr, "funcall error: argcount mismatch! (more than required %d)\n", argi.required_args); return false; } return true; } })){ goto end; } // real call switch(fun->type()){ case Function::Type::interpreted: do_list(fun->get<Lisp_ptr>(), [&](Cons* cell) -> bool { VM.code().push(cell->car()); eval(); return true; }, [&](Lisp_ptr last_cdr){ if(!nullp(last_cdr)){ fprintf(stderr, "eval error: body has dot list!\n"); VM.return_value() = {}; } }); break; case Function::Type::native: fun->get<Function::NativeFunc>()(); if(!VM.return_value()) fprintf(stderr, "eval error: native func returned undef!\n"); break; default: UNEXP_DEFAULT(); } end: if(env){ VM.leave_frame(); }else{ // cleaned by native func } } void eval_lambda(const Cons* rest){ VM.return_value() = {}; auto args = rest->car(); if(rest->cdr().tag() != Ptr_tag::cons){ fprintf(stderr, "eval error: lambda has invalid body!\n"); return; } auto arg_info = parse_func_arg(args); if(!arg_info){ fprintf(stderr, "eval error: lambda has invalid args!\n"); return; } auto code = rest->cdr(); if(!code.get<Cons*>()){ fprintf(stderr, "eval error: lambda has no body!\n"); return; } auto fun = new Function(code, arg_info, VM.frame()); VM.return_value() = Lisp_ptr{fun}; return; } void eval_if(Cons* rest){ VM.return_value() = {}; // extracting Lisp_ptr test, conseq, alt; int len = bind_cons_list(Lisp_ptr(rest), [&](Cons* c){ test = c->car(); }, [&](Cons* c){ conseq = c->car(); }, [&](Cons* c){ alt = c->car(); }); switch(len){ case 1: fprintf(stderr, "eval error: informal if expr! (no test expr)\n"); return; case 2: case 3: // successed break; default: fprintf(stderr, "eval error: informal if expr! (more than %d exprs)\n", len); return; } // evaluating VM.code().push(Lisp_ptr(VM_op::if_)); VM.code().push(test); VM.stack().push(alt); VM.stack().push(conseq); } void vm_op_if(){ auto test_result = VM.return_value(); if(test_result.get<bool>()){ VM.code().push(VM.stack().top()); VM.stack().pop(); VM.stack().pop(); }else{ VM.stack().pop(); VM.code().push(VM.stack().top()); VM.stack().pop(); } } void eval_set(Cons* rest){ VM.return_value() = {}; // extracting Symbol* var = nullptr; Lisp_ptr val; int len = bind_cons_list(Lisp_ptr(rest), [&](Cons* c){ var = c->car().get<Symbol*>(); }, [&](Cons* c){ val = c->car(); }); if(!var){ fprintf(stderr, "eval error: set!'s first element is not symbol!\n"); return; } if(var->to_keyword() != Keyword::not_keyword){ fprintf(stderr, "eval error: set!'s first element is Keyword (%s)!\n", var->name().c_str()); return; } if(!val){ fprintf(stderr, "eval error: no value is supplied for set!\n"); return; } if(len > 2){ fprintf(stderr, "eval error: informal set! expr! (more than %d exprs)\n", len); return; } // evaluating VM.code().push(Lisp_ptr{VM_op::set_}); VM.code().push(val); VM.stack().push(Lisp_ptr{var}); } void vm_op_set(){ auto var = VM.stack().top().get<Symbol*>(); VM.stack().pop(); if(!var){ fprintf(stderr, "eval error: internal error occured (set!'s varname is dismissed)\n"); return; } VM.set(var, VM.return_value()); } void eval_define(const Cons* rest){ static constexpr auto test_varname = [](Symbol* var) -> bool{ if(!var){ fprintf(stderr, "eval error: defined variable name is not a symbol!\n"); return false; } if(var->to_keyword() != Keyword::not_keyword){ fprintf(stderr, "eval error: define's first element is Keyword (%s)!\n", var->name().c_str()); return false; } return true; }; Symbol* var = nullptr; Lisp_ptr value; unique_ptr<Function> func_value; VM.return_value() = {}; // extracting auto first = rest->car(); switch(first.tag()){ case Ptr_tag::symbol: { var = first.get<Symbol*>(); if(!test_varname(var)) return; auto val_l = rest->cdr().get<Cons*>(); if(!val_l){ fprintf(stderr, "eval error: definition has empty expr!\n"); return; } if(val_l->cdr().tag() != Ptr_tag::cons || val_l->cdr().get<Cons*>()){ fprintf(stderr, "eval error: definition has extra expr!\n"); return; } VM.code().push(val_l->car()); eval(); value = VM.return_value(); break; } case Ptr_tag::cons: { auto lis = first.get<Cons*>(); if(!lis){ fprintf(stderr, "eval error: defined variable is not found!\n"); return; } var = lis->car().get<Symbol*>(); if(!test_varname(var)) return; const auto& arg_info = parse_func_arg(lis->cdr()); if(!arg_info){ fprintf(stderr, "eval error: defined function argument is informal!\n"); return; } auto code = rest->cdr(); if(!code.get<Cons*>()){ fprintf(stderr, "eval error: definition has empty body!\n"); return; } func_value = unique_ptr<Function>(new Function(code, arg_info, VM.frame())); value = Lisp_ptr(func_value.get()); break; } default: fprintf(stderr, "eval error: informal define syntax!\n"); return; } // assignment VM.set(var, value); func_value.release(); VM.return_value() = value; return; } } // namespace void eval(){ while(!VM.code().empty()){ auto p = VM.code().top(); VM.code().pop(); switch(p.tag()){ case Ptr_tag::symbol: { auto sym = p.get<Symbol*>(); if(sym->to_keyword() != Keyword::not_keyword){ fprintf(stderr, "eval error: symbol '%s' is keyword!!\n", sym->name().c_str()); VM.return_value() = {}; break; } VM.return_value() = VM.find(sym); break; } case Ptr_tag::cons: { auto c = p.get<Cons*>(); auto first = c->car(); // special operator? if(first.tag() == Ptr_tag::symbol){ auto sym = first.get<Symbol*>(); auto k = sym->to_keyword(); if(k != Keyword::not_keyword){ Cons* r = c->cdr().get<Cons*>(); if(!r){ fprintf(stderr, "eval error: expresssion (<KEYWORD>%s) is informal!\n", (c->cdr().tag() == Ptr_tag::cons) ? "" : ". #"); VM.return_value() = {}; break; } switch(k){ case Keyword::quote: VM.return_value() = r->car(); break; case Keyword::lambda: eval_lambda(r); break; case Keyword::if_: eval_if(r); break; case Keyword::set_: eval_set(r); break; case Keyword::define: eval_define(r); break; case Keyword::cond: case Keyword::case_: case Keyword::and_: case Keyword::or_: case Keyword::let: case Keyword::let_star: case Keyword::letrec: case Keyword::begin: case Keyword::do_: case Keyword::delay: case Keyword::quasiquote: fprintf(stderr, "eval error: '%s' is under development...\n", sym->name().c_str()); VM.return_value() = {}; break; case Keyword::else_: case Keyword::r_arrow: case Keyword::unquote: case Keyword::unquote_splicing: fprintf(stderr, "eval error: '%s' cannot be used as operator!!\n", sym->name().c_str()); VM.return_value() = {}; break; default: UNEXP_DEFAULT(); } break; }else{ // macro call? // try to find macro-function from symbol // found -> macro expansion // not found -> goto function calling ; } } // procedure call? VM.code().push(first); eval(); auto proc = VM.return_value(); if(proc.tag() != Ptr_tag::function){ fprintf(stderr, "eval error: (# # ...)'s first element is not procedure (%s)\n", stringify(proc.tag())); VM.return_value() = {}; break; } funcall(proc.get<Function*>(), c->cdr()); break; } case Ptr_tag::vm_op: switch(p.get<VM_op>()){ case VM_op::nop: break; case VM_op::if_: vm_op_if(); break; case VM_op::set_: vm_op_set(); break; default: UNEXP_DEFAULT(); } break; default: // almost self-evaluating VM.return_value() = p; break; } } } <commit_msg>bitly cleanup<commit_after>#include <memory> #include <cassert> #include "eval.hh" #include "util.hh" #include "keyword.hh" #include "symbol.hh" #include "cons.hh" #include "function.hh" #include "printer.hh" using namespace std; enum class VM_op : int{ nop = 0, if_, set_ }; namespace { inline Symbol* to_varname(Lisp_ptr p){ Symbol* var = p.get<Symbol*>(); if(!var){ fprintf(stderr, "eval error: variable's name is not a symbol!\n"); return nullptr; } if(var->to_keyword() != Keyword::not_keyword){ fprintf(stderr, "eval error: variable's name is Keyword (%s)!\n", var->name().c_str()); return nullptr; } return var; }; void funcall(const Function* fun, Lisp_ptr args){ const auto& argi = fun->arg_info(); const auto env = fun->closure(); const auto set_arg = [&](Symbol* sym, Lisp_ptr p){ if(env){ VM.local_set(sym, p); }else{ VM.stack().push(p); } }; Lisp_ptr arg_name = argi.head; VM.return_value() = {}; if(env){ VM.enter_frame(push_frame(env)); } // push args int argc = 0; if(!do_list(args, [&](Cons* cell) -> bool{ assert(argc <= argi.required_args); if(argc == argi.required_args) return false; VM.code().push(cell->car()); eval(); auto evaled = VM.return_value(); if(!evaled){ fprintf(stderr, "eval error: evaluating func's arg failed!!\n"); return false; } auto arg_name_cell = arg_name.get<Cons*>(); set_arg(arg_name_cell->car().get<Symbol*>(), evaled); arg_name = arg_name_cell->cdr(); ++argc; return true; }, [&](Lisp_ptr dot_cdr) -> bool{ assert(argc <= argi.required_args); if(argc < argi.required_args){ fprintf(stderr, "eval error: internal argument counter mismatched!! (read %d args)\n", argc); return false; } if(argi.variadic){ set_arg(arg_name.get<Symbol*>(), dot_cdr); ++argc; return true; }else{ if(!nullp(dot_cdr)){ fprintf(stderr, "funcall error: argcount mismatch! (more than required %d)\n", argi.required_args); return false; } return true; } })){ goto end; } // real call switch(fun->type()){ case Function::Type::interpreted: do_list(fun->get<Lisp_ptr>(), [&](Cons* cell) -> bool { VM.code().push(cell->car()); eval(); return true; }, [&](Lisp_ptr last_cdr){ if(!nullp(last_cdr)){ fprintf(stderr, "eval error: body has dot list!\n"); VM.return_value() = {}; } }); break; case Function::Type::native: fun->get<Function::NativeFunc>()(); if(!VM.return_value()) fprintf(stderr, "eval error: native func returned undef!\n"); break; default: UNEXP_DEFAULT(); } end: if(env){ VM.leave_frame(); }else{ // cleaned by native func } } void eval_lambda(const Cons* rest){ VM.return_value() = {}; auto args = rest->car(); if(rest->cdr().tag() != Ptr_tag::cons){ fprintf(stderr, "eval error: lambda has invalid body!\n"); return; } auto arg_info = parse_func_arg(args); if(!arg_info){ fprintf(stderr, "eval error: lambda has invalid args!\n"); return; } auto code = rest->cdr(); if(!code.get<Cons*>()){ fprintf(stderr, "eval error: lambda has no body!\n"); return; } auto fun = new Function(code, arg_info, VM.frame()); VM.return_value() = Lisp_ptr{fun}; return; } void eval_if(Cons* rest){ VM.return_value() = {}; // extracting Lisp_ptr test, conseq, alt; int len = bind_cons_list(Lisp_ptr(rest), [&](Cons* c){ test = c->car(); }, [&](Cons* c){ conseq = c->car(); }, [&](Cons* c){ alt = c->car(); }); switch(len){ case 1: fprintf(stderr, "eval error: informal if expr! (no test expr)\n"); return; case 2: case 3: // successed break; default: fprintf(stderr, "eval error: informal if expr! (more than %d exprs)\n", len); return; } // evaluating VM.code().push(Lisp_ptr(VM_op::if_)); VM.code().push(test); VM.stack().push(alt); VM.stack().push(conseq); } void vm_op_if(){ auto test_result = VM.return_value(); if(test_result.get<bool>()){ VM.code().push(VM.stack().top()); VM.stack().pop(); VM.stack().pop(); }else{ VM.stack().pop(); VM.code().push(VM.stack().top()); VM.stack().pop(); } } void eval_set(Cons* rest){ VM.return_value() = {}; // extracting Symbol* var = nullptr; Lisp_ptr val; int len = bind_cons_list(Lisp_ptr(rest), [&](Cons* c){ var = to_varname(c->car()); }, [&](Cons* c){ val = c->car(); }); if(!var) return; if(!val){ fprintf(stderr, "eval error: no value is supplied for set!\n"); return; } if(len > 2){ fprintf(stderr, "eval error: informal set! expr! (more than %d exprs)\n", len); return; } // evaluating VM.code().push(Lisp_ptr{VM_op::set_}); VM.code().push(val); VM.stack().push(Lisp_ptr{var}); } void vm_op_set(){ auto var = VM.stack().top().get<Symbol*>(); VM.stack().pop(); if(!var){ fprintf(stderr, "eval error: internal error occured (set!'s varname is dismissed)\n"); return; } VM.set(var, VM.return_value()); } void eval_define(const Cons* rest){ VM.return_value() = {}; // extracting auto first = rest->car(); switch(first.tag()){ case Ptr_tag::symbol: { auto var = to_varname(first); if(!var) return; auto val_l = rest->cdr().get<Cons*>(); if(!val_l){ fprintf(stderr, "eval error: definition has empty expr!\n"); return; } if(val_l->cdr().tag() != Ptr_tag::cons || val_l->cdr().get<Cons*>()){ fprintf(stderr, "eval error: definition has extra expr!\n"); return; } VM.code().push(val_l->car()); eval(); auto value = VM.return_value(); VM.set(var, value); VM.return_value() = value; return; } case Ptr_tag::cons: { auto lis = first.get<Cons*>(); if(!lis){ fprintf(stderr, "eval error: defined variable is not found!\n"); return; } auto var = to_varname(lis->car()); if(!var) return; const auto& arg_info = parse_func_arg(lis->cdr()); if(!arg_info){ fprintf(stderr, "eval error: defined function argument is informal!\n"); return; } auto code = rest->cdr(); if(!code.get<Cons*>()){ fprintf(stderr, "eval error: definition has empty body!\n"); return; } auto value = Lisp_ptr(new Function(code, arg_info, VM.frame())); VM.set(var, value); VM.return_value() = value; return; } default: fprintf(stderr, "eval error: informal define syntax!\n"); return; } } } // namespace void eval(){ while(!VM.code().empty()){ auto p = VM.code().top(); VM.code().pop(); switch(p.tag()){ case Ptr_tag::symbol: { auto sym = to_varname(p); if(!sym){ VM.return_value() = {}; break; } VM.return_value() = VM.find(sym); break; } case Ptr_tag::cons: { auto c = p.get<Cons*>(); auto first = c->car(); // special operator? if(first.tag() == Ptr_tag::symbol){ auto sym = first.get<Symbol*>(); auto k = sym->to_keyword(); if(k != Keyword::not_keyword){ Cons* r = c->cdr().get<Cons*>(); if(!r){ fprintf(stderr, "eval error: expresssion (<KEYWORD>%s) is informal!\n", (c->cdr().tag() == Ptr_tag::cons) ? "" : ". #"); VM.return_value() = {}; break; } switch(k){ case Keyword::quote: VM.return_value() = r->car(); break; case Keyword::lambda: eval_lambda(r); break; case Keyword::if_: eval_if(r); break; case Keyword::set_: eval_set(r); break; case Keyword::define: eval_define(r); break; case Keyword::cond: case Keyword::case_: case Keyword::and_: case Keyword::or_: case Keyword::let: case Keyword::let_star: case Keyword::letrec: case Keyword::begin: case Keyword::do_: case Keyword::delay: case Keyword::quasiquote: fprintf(stderr, "eval error: '%s' is under development...\n", sym->name().c_str()); VM.return_value() = {}; break; case Keyword::else_: case Keyword::r_arrow: case Keyword::unquote: case Keyword::unquote_splicing: fprintf(stderr, "eval error: '%s' cannot be used as operator!!\n", sym->name().c_str()); VM.return_value() = {}; break; default: UNEXP_DEFAULT(); } break; }else{ // macro call? // try to find macro-function from symbol // found -> macro expansion // not found -> goto function calling ; } } // procedure call? VM.code().push(first); eval(); auto proc = VM.return_value(); if(proc.tag() != Ptr_tag::function){ fprintf(stderr, "eval error: (# # ...)'s first element is not procedure (%s)\n", stringify(proc.tag())); VM.return_value() = {}; break; } funcall(proc.get<Function*>(), c->cdr()); break; } case Ptr_tag::vm_op: switch(p.get<VM_op>()){ case VM_op::nop: break; case VM_op::if_: vm_op_if(); break; case VM_op::set_: vm_op_set(); break; default: UNEXP_DEFAULT(); } break; default: // almost self-evaluating VM.return_value() = p; break; } } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "ed.h" #include "glob.h" int file_masks::match (const char *name) const { if (empty_p ()) return 0; int not = 0, match = 0; for (char **p = fm_masks; *p; p++) if (**p == GLOB_NOT) { match |= pathname_match_p (*p + 1, name); not = 1; } else if (pathname_match_p (*p, name)) return 1; return not ? !match : 0; } char ** file_masks::build_masks (lisp lmasks) { int nfiles = 0; int nbytes = 0; for (lisp p = lmasks; consp (p); p = xcdr (p)) { lisp x = xcar (p); check_string (x); if (xstring_length (x)) { nbytes += w2sl (x) + 1; nfiles++; } } if (!nfiles) return 0; nfiles++; char **b0 = (char **)xmalloc (sizeof (char *) * nfiles + nbytes); char **b = b0; char *s = (char *)b0 + sizeof (char *) * nfiles; for (lisp p = lmasks; consp (p); p = xcdr (p)) { lisp x = xcar (p); if (xstring_length (x)) { *b++ = s; s = w2s (s, x) + 1; } } *b = 0; return b0; } void file_masks::set_text (HWND hwnd) const { if (empty_p ()) SetWindowText (hwnd, ""); else { int nbytes = 16; for (char **p = fm_masks; *p; p++) nbytes += strlen (*p) + 1; char *b0 = (char *)alloca (nbytes); char *b = stpcpy (b0, "Mask:"); for (char **p = fm_masks; *p; p++) { *b++ = ' '; b = stpcpy (b, *p); } SetWindowText (hwnd, b0); } } static const u_char * find_matched_bracket (const u_char *s) { if (*s == '^') s++; if (*s == ']') s++; while (1) { int c = *s++; switch (c) { case 0: return 0; case ']': return s - 1; default: if (SJISP (c) && *s) s++; break; } } } int wild_pathname_p (const char *filename) { const u_char *p = (const u_char *)filename; int unmatched_bracket = xsymbol_value (Vbrackets_is_wildcard_character) == Qnil; if (*p == GLOB_NOT) return 1; while (1) { int c = *p++; switch (c) { case 0: return 0; case '[': if (!unmatched_bracket && find_matched_bracket (p)) return 1; unmatched_bracket = 1; break; case '*': case '?': return 1; default: if (SJISP (c) && *p) p++; break; } } } int pathname_match_p1 (const char *pat, const char *str, int nodot) { const u_char *p = (const u_char *)pat; const u_char *s = (const u_char *)str; int unmatched_bracket = xsymbol_value (Vbrackets_is_wildcard_character) == Qnil; while (1) { int c = *p++; switch (c) { case 0: return !*s; case '[': { if (unmatched_bracket) goto normal; const u_char *pe = find_matched_bracket (p); if (!pe) { unmatched_bracket = 1; goto normal; } if (!*s) return 0; int not = 0; if (*p == '^') { not = 1; p++; } while (p < pe) { c = *p++; if (SJISP (c) && *p) { if (p[1] == '-' && p + 3 < pe && SJISP (p[2])) { u_int x = (*s << 8) + s[1]; if (x >= u_int ((c << 8) + *p) && x <= u_int ((p[2] << 8) + p[3])) { not ^= 1; break; } p += 4; } else { if (u_int (c) == *s && *p == s[1]) { not ^= 1; break; } p++; } } else { if (*p == '-' && p + 1 < pe && !SJISP (p[1])) { int x = char_upcase (*s); if (x >= char_upcase (c) && x <= char_upcase (p[1])) { not ^= 1; break; } p += 2; } else if (char_upcase (c) == char_upcase (*s)) { not ^= 1; break; } } } if (!not) return 0; p = pe + 1; s += (SJISP (*s) && s[1]) ? 2 : 1; break; } case '?': if (!*s) return 0; if (nodot && *s == '.') return 0; if (SJISP (*s) && s[1]) s++; s++; break; case '*': while (*p == '*') p++; if (!*p) return 1; while (1) { if (pathname_match_p1 ((const char *)p, (const char *)s, nodot)) return 1; if (!*s) return 0; if (nodot && *s == '.') return 0; if (SJISP (*s) && s[1]) s++; s++; } /* NOTREACHED */ case '.': if (*s == '.') s++; else return !*p && !*s; break; default: normal: if (SJISP (c) && *p) { if (u_int (c) != *s++) return 0; if (*p++ != *s++) return 0; } else { if (char_upcase (c) != char_upcase (*s)) return 0; s++; } } } } int pathname_match_p (const char *pat, const char *str) { int nodot = 0; int l = strlen (pat); if (l > 1 && pat[l - 1] == '.' && !check_kanji2 (pat, l - 1)) nodot = 1; return pathname_match_p1 (pat, str, nodot); } #define DF_ABSOLUTE 1 #define DF_RECURSIVE 2 #define DF_FILE_ONLY 4 #define DF_SHOW_DOTS 8 #define DF_COUNT 16 #define DF_DIR_ONLY 32 #define DF_FILE_INFO 64 static lisp directory (char *path, const char *pat, char *name, file_masks &masks, int flags, int depth, int max_depth, long &count, lisp callback, lisp result) { QUIT; if (max_depth && depth >= max_depth) return result; int l = strlen (path); if (l >= PATH_MAX) return result; char *pe = path + l; *pe = '*'; pe[1] = 0; char *ne = name + strlen (name); WIN32_FIND_DATA fd; HANDLE h = WINFS::FindFirstFile (path, &fd); if (h != INVALID_HANDLE_VALUE) { find_handle fh (h); do { #ifndef PATHNAME_ESCAPE_TILDE if (*fd.cFileName == '~' && !fd.cFileName[1]) continue; #endif if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (*fd.cFileName == '.' && (!fd.cFileName[1] || (fd.cFileName[1] == '.' && !fd.cFileName[2]))) { if (!(flags & DF_SHOW_DOTS)) continue; } else if (*pat == GLOB_NOT ? pathname_match_p (pat + 1, fd.cFileName) : (*pat && !pathname_match_p (pat, fd.cFileName))) continue; else if (flags & DF_RECURSIVE) { if (!(flags & DF_ABSOLUTE)) strcpy (stpcpy (ne, fd.cFileName), "/"); strcpy (stpcpy (pe, fd.cFileName), "/"); result = directory (path, "", name, masks, flags, depth + 1, max_depth, count, callback, result); if (flags & DF_COUNT && count <= 0) break; } if (flags & DF_FILE_ONLY) continue; if (!masks.empty_p () && !masks.match (fd.cFileName)) continue; if (flags & DF_ABSOLUTE) strcpy (stpcpy (pe, fd.cFileName), "/"); else strcpy (stpcpy (ne, fd.cFileName), "/"); } else { if (flags & DF_DIR_ONLY) continue; if (*pat) { if (*pat == GLOB_NOT ? pathname_match_p (pat + 1, fd.cFileName) : !pathname_match_p (pat, fd.cFileName)) continue; } else { if (!masks.empty_p () && !masks.match (fd.cFileName)) continue; } if (flags & DF_ABSOLUTE) strcpy (pe, fd.cFileName); else strcpy (ne, fd.cFileName); } lisp lpath = make_string ((flags & DF_ABSOLUTE) ? path : name); if (flags & DF_FILE_INFO) lpath = xcons (lpath, make_file_info (fd)); if (callback != Qnil) { lisp arg = xcons (lpath, Qnil); protect_gc gcpro (arg); Ffuncall (callback, arg); } else result = xcons (lpath, result); if (flags & DF_COUNT && --count <= 0) break; } while (WINFS::FindNextFile (h, &fd)); } return result; } lisp Fdirectory (lisp dirname, lisp keys) { char path[PATH_MAX * 2]; char pat[PATH_MAX + 1]; pathname2cstr (dirname, path); char *p = jrindex (path, '/'); int f = WINFS::GetFileAttributes (path); if (f != -1 && f & FILE_ATTRIBUTE_DIRECTORY) { if (p && p[1]) strcat (path, "/"); *pat = 0; } else { if (p) { strcpy (pat, p + 1); p[1] = 0; } else { strcpy (pat, path); *path = 0; } } lisp wild = find_keyword (Kwild, keys, Qnil); file_masks masks (stringp (wild) ? xcons (wild, Qnil) : wild); char name[PATH_MAX * 2]; *name = 0; int flags = 0; int max_depth = 0; long count = 0; if (find_keyword (Kabsolute, keys, Qnil) != Qnil) flags |= DF_ABSOLUTE; if (find_keyword (Krecursive, keys, Qnil) != Qnil) { flags |= DF_RECURSIVE; lisp x = find_keyword (Kdepth, keys, Qnil); if (x != Qnil) max_depth = fixnum_value (x); } if (find_keyword (Kfile_only, keys, Qnil) != Qnil) flags |= DF_FILE_ONLY; if (find_keyword (Kshow_dots, keys, Qnil) != Qnil) flags |= DF_SHOW_DOTS; lisp lcount = find_keyword (Kcount, keys, Qnil); if (lcount != Qnil) { flags |= DF_COUNT; count = fixnum_value (lcount); if (count <= 0) return Qnil; } else if (find_keyword (Kany_one, keys, Qnil) != Qnil) // for compatibility { flags |= DF_COUNT; count = 1; } if (find_keyword (Kdirectory_only, keys, Qnil) != Qnil) flags |= DF_DIR_ONLY; if (find_keyword (Kfile_info, keys, Qnil) != Qnil) flags |= DF_FILE_INFO; lisp callback = find_keyword (Kcallback, keys, Qnil); return Fnreverse (directory (path, pat, name, masks, flags, 0, max_depth, count, callback, Qnil)); } lisp Fpathname_match_p (lisp pathname, lisp wildname) { check_string (pathname); check_string (wildname); char *path = (char *)alloca (xstring_length (pathname) * 2 + 1); w2s (path, pathname); char *wild = (char *)alloca (xstring_length (wildname) * 2 + 1); w2s (wild, wildname); return boole (*wild == GLOB_NOT ? !pathname_match_p (wild + 1, path) : pathname_match_p (wild, path)); } lisp Fwild_pathname_p (lisp pathname) { char path[PATH_MAX + 1]; pathname2cstr (pathname, path); return boole (wild_pathname_p (path)); } <commit_msg>directory 関数に :test 引数を追加 (#198)<commit_after>#include "stdafx.h" #include "ed.h" #include "glob.h" int file_masks::match (const char *name) const { if (empty_p ()) return 0; int not = 0, match = 0; for (char **p = fm_masks; *p; p++) if (**p == GLOB_NOT) { match |= pathname_match_p (*p + 1, name); not = 1; } else if (pathname_match_p (*p, name)) return 1; return not ? !match : 0; } char ** file_masks::build_masks (lisp lmasks) { int nfiles = 0; int nbytes = 0; for (lisp p = lmasks; consp (p); p = xcdr (p)) { lisp x = xcar (p); check_string (x); if (xstring_length (x)) { nbytes += w2sl (x) + 1; nfiles++; } } if (!nfiles) return 0; nfiles++; char **b0 = (char **)xmalloc (sizeof (char *) * nfiles + nbytes); char **b = b0; char *s = (char *)b0 + sizeof (char *) * nfiles; for (lisp p = lmasks; consp (p); p = xcdr (p)) { lisp x = xcar (p); if (xstring_length (x)) { *b++ = s; s = w2s (s, x) + 1; } } *b = 0; return b0; } void file_masks::set_text (HWND hwnd) const { if (empty_p ()) SetWindowText (hwnd, ""); else { int nbytes = 16; for (char **p = fm_masks; *p; p++) nbytes += strlen (*p) + 1; char *b0 = (char *)alloca (nbytes); char *b = stpcpy (b0, "Mask:"); for (char **p = fm_masks; *p; p++) { *b++ = ' '; b = stpcpy (b, *p); } SetWindowText (hwnd, b0); } } static const u_char * find_matched_bracket (const u_char *s) { if (*s == '^') s++; if (*s == ']') s++; while (1) { int c = *s++; switch (c) { case 0: return 0; case ']': return s - 1; default: if (SJISP (c) && *s) s++; break; } } } int wild_pathname_p (const char *filename) { const u_char *p = (const u_char *)filename; int unmatched_bracket = xsymbol_value (Vbrackets_is_wildcard_character) == Qnil; if (*p == GLOB_NOT) return 1; while (1) { int c = *p++; switch (c) { case 0: return 0; case '[': if (!unmatched_bracket && find_matched_bracket (p)) return 1; unmatched_bracket = 1; break; case '*': case '?': return 1; default: if (SJISP (c) && *p) p++; break; } } } int pathname_match_p1 (const char *pat, const char *str, int nodot) { const u_char *p = (const u_char *)pat; const u_char *s = (const u_char *)str; int unmatched_bracket = xsymbol_value (Vbrackets_is_wildcard_character) == Qnil; while (1) { int c = *p++; switch (c) { case 0: return !*s; case '[': { if (unmatched_bracket) goto normal; const u_char *pe = find_matched_bracket (p); if (!pe) { unmatched_bracket = 1; goto normal; } if (!*s) return 0; int not = 0; if (*p == '^') { not = 1; p++; } while (p < pe) { c = *p++; if (SJISP (c) && *p) { if (p[1] == '-' && p + 3 < pe && SJISP (p[2])) { u_int x = (*s << 8) + s[1]; if (x >= u_int ((c << 8) + *p) && x <= u_int ((p[2] << 8) + p[3])) { not ^= 1; break; } p += 4; } else { if (u_int (c) == *s && *p == s[1]) { not ^= 1; break; } p++; } } else { if (*p == '-' && p + 1 < pe && !SJISP (p[1])) { int x = char_upcase (*s); if (x >= char_upcase (c) && x <= char_upcase (p[1])) { not ^= 1; break; } p += 2; } else if (char_upcase (c) == char_upcase (*s)) { not ^= 1; break; } } } if (!not) return 0; p = pe + 1; s += (SJISP (*s) && s[1]) ? 2 : 1; break; } case '?': if (!*s) return 0; if (nodot && *s == '.') return 0; if (SJISP (*s) && s[1]) s++; s++; break; case '*': while (*p == '*') p++; if (!*p) return 1; while (1) { if (pathname_match_p1 ((const char *)p, (const char *)s, nodot)) return 1; if (!*s) return 0; if (nodot && *s == '.') return 0; if (SJISP (*s) && s[1]) s++; s++; } /* NOTREACHED */ case '.': if (*s == '.') s++; else return !*p && !*s; break; default: normal: if (SJISP (c) && *p) { if (u_int (c) != *s++) return 0; if (*p++ != *s++) return 0; } else { if (char_upcase (c) != char_upcase (*s)) return 0; s++; } } } } int pathname_match_p (const char *pat, const char *str) { int nodot = 0; int l = strlen (pat); if (l > 1 && pat[l - 1] == '.' && !check_kanji2 (pat, l - 1)) nodot = 1; return pathname_match_p1 (pat, str, nodot); } #define DF_ABSOLUTE 1 #define DF_RECURSIVE 2 #define DF_FILE_ONLY 4 #define DF_SHOW_DOTS 8 #define DF_COUNT 16 #define DF_DIR_ONLY 32 #define DF_FILE_INFO 64 static lisp directory (char *path, const char *pat, char *name, file_masks &masks, int flags, int depth, int max_depth, long &count, lisp callback, lisp test, lisp result) { QUIT; if (max_depth && depth >= max_depth) return result; int l = strlen (path); if (l >= PATH_MAX) return result; char *pe = path + l; *pe = '*'; pe[1] = 0; char *ne = name + strlen (name); WIN32_FIND_DATA fd; HANDLE h = WINFS::FindFirstFile (path, &fd); if (h != INVALID_HANDLE_VALUE) { find_handle fh (h); do { #ifndef PATHNAME_ESCAPE_TILDE if (*fd.cFileName == '~' && !fd.cFileName[1]) continue; #endif bool test_called = false; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (*fd.cFileName == '.' && (!fd.cFileName[1] || (fd.cFileName[1] == '.' && !fd.cFileName[2]))) { if (!(flags & DF_SHOW_DOTS)) continue; } else if (*pat == GLOB_NOT ? pathname_match_p (pat + 1, fd.cFileName) : (*pat && !pathname_match_p (pat, fd.cFileName))) continue; else if (flags & DF_RECURSIVE) { if (!(flags & DF_ABSOLUTE)) strcpy (stpcpy (ne, fd.cFileName), "/"); strcpy (stpcpy (pe, fd.cFileName), "/"); if (test != Qnil) { lisp lpath = make_string ((flags & DF_ABSOLUTE) ? path : name); if (flags & DF_FILE_INFO) lpath = xcons (lpath, make_file_info (fd)); test_called = true; if (funcall_1 (test, lpath) == Qnil) continue; } result = directory (path, "", name, masks, flags, depth + 1, max_depth, count, callback, test, result); if (flags & DF_COUNT && count <= 0) break; } if (flags & DF_FILE_ONLY) continue; if (!masks.empty_p () && !masks.match (fd.cFileName)) continue; if (flags & DF_ABSOLUTE) strcpy (stpcpy (pe, fd.cFileName), "/"); else strcpy (stpcpy (ne, fd.cFileName), "/"); } else { if (flags & DF_DIR_ONLY) continue; if (*pat) { if (*pat == GLOB_NOT ? pathname_match_p (pat + 1, fd.cFileName) : !pathname_match_p (pat, fd.cFileName)) continue; } else { if (!masks.empty_p () && !masks.match (fd.cFileName)) continue; } if (flags & DF_ABSOLUTE) strcpy (pe, fd.cFileName); else strcpy (ne, fd.cFileName); } lisp lpath = make_string ((flags & DF_ABSOLUTE) ? path : name); if (flags & DF_FILE_INFO) lpath = xcons (lpath, make_file_info (fd)); if (test != Qnil && !test_called) { if (funcall_1 (test, lpath) == Qnil) continue; } if (callback != Qnil) { lisp arg = xcons (lpath, Qnil); protect_gc gcpro (arg); Ffuncall (callback, arg); } else result = xcons (lpath, result); if (flags & DF_COUNT && --count <= 0) break; } while (WINFS::FindNextFile (h, &fd)); } return result; } lisp Fdirectory (lisp dirname, lisp keys) { char path[PATH_MAX * 2]; char pat[PATH_MAX + 1]; pathname2cstr (dirname, path); char *p = jrindex (path, '/'); int f = WINFS::GetFileAttributes (path); if (f != -1 && f & FILE_ATTRIBUTE_DIRECTORY) { if (p && p[1]) strcat (path, "/"); *pat = 0; } else { if (p) { strcpy (pat, p + 1); p[1] = 0; } else { strcpy (pat, path); *path = 0; } } lisp wild = find_keyword (Kwild, keys, Qnil); file_masks masks (stringp (wild) ? xcons (wild, Qnil) : wild); char name[PATH_MAX * 2]; *name = 0; int flags = 0; int max_depth = 0; long count = 0; if (find_keyword (Kabsolute, keys, Qnil) != Qnil) flags |= DF_ABSOLUTE; if (find_keyword (Krecursive, keys, Qnil) != Qnil) { flags |= DF_RECURSIVE; lisp x = find_keyword (Kdepth, keys, Qnil); if (x != Qnil) max_depth = fixnum_value (x); } if (find_keyword (Kfile_only, keys, Qnil) != Qnil) flags |= DF_FILE_ONLY; if (find_keyword (Kshow_dots, keys, Qnil) != Qnil) flags |= DF_SHOW_DOTS; lisp lcount = find_keyword (Kcount, keys, Qnil); if (lcount != Qnil) { flags |= DF_COUNT; count = fixnum_value (lcount); if (count <= 0) return Qnil; } else if (find_keyword (Kany_one, keys, Qnil) != Qnil) // for compatibility { flags |= DF_COUNT; count = 1; } if (find_keyword (Kdirectory_only, keys, Qnil) != Qnil) flags |= DF_DIR_ONLY; if (find_keyword (Kfile_info, keys, Qnil) != Qnil) flags |= DF_FILE_INFO; lisp callback = find_keyword (Kcallback, keys, Qnil); lisp test = find_keyword (Ktest, keys, Qnil); return Fnreverse (directory (path, pat, name, masks, flags, 0, max_depth, count, callback, test, Qnil)); } lisp Fpathname_match_p (lisp pathname, lisp wildname) { check_string (pathname); check_string (wildname); char *path = (char *)alloca (xstring_length (pathname) * 2 + 1); w2s (path, pathname); char *wild = (char *)alloca (xstring_length (wildname) * 2 + 1); w2s (wild, wildname); return boole (*wild == GLOB_NOT ? !pathname_match_p (wild + 1, path) : pathname_match_p (wild, path)); } lisp Fwild_pathname_p (lisp pathname) { char path[PATH_MAX + 1]; pathname2cstr (pathname, path); return boole (wild_pathname_p (path)); } <|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <ctype.h> #include <cstring> #include <vector> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <sys/wait.h> using namespace std; //parses the entered command putting each string seperated //by spaces into a vector passed in by reference //the function utilizes strtok to do this void parse(char x[], vector<string> &v){ char* tmp; //separates the string by spaces tmp = strtok(x, " "); while(tmp != NULL){ //stores in the vector v.push_back(tmp); //searches for the next " " character tmp = strtok(NULL, " "); } } //the function returns false if the command passed in //is "exit" or any spaced variation of it. //returnd false otherwise bool isExit(char x[]){ //sets up vars necessary for comparison string tmp = x; string hold = "exit"; char spc = ' '; unsigned int k = 0; //if the size of the passed in char[] is less than that //necessary for it to be exit return false if(tmp.size() < hold.size()){ return false; } //check each non-space character if within the first //four characters any of the characters dont align with "exit" return false //otherwise count how many more characters there are in the passed in string //if there are more than 4 return false otherwise return true //if a space appears when k is > 0 but < 4 return false, this prevents //bugs like "exi t" from working for(unsigned int i = 0; i < tmp.size(); i++){ if(tmp.at(i) != spc){ if(k < hold.size() && tmp.at(i) != hold.at(k)){ return false; } k++; } else if(k > 0 && k < hold.size()){ return false; } } if(k != hold.size()){ return false; } else{ return true; } } //traverses the entered list of commands //and checks to see how many different kinds of //connectors there are, if there are more than one //it returns true else returns false bool multiConn(string x){ int amp = 0; int ln = 0; int semi = 0; int total = 0; //if any part of the string does not //align with "exit" returns false, otherwise counts //all characters after the passed in command for(unsigned int i = 0; i < x.size(); i++){ if(x.at(i) == '&' && i != x.size()-1){ if(x.at(i+1) == '&'){ amp++; } } if(x.at(i) == '|' && i != x.size()-1){ if(x.at(i+1) == '|'){ ln++; } } if(x.at(i) == ';'){ semi++; } } //calculates the total amount of different connectors if(amp > 0){ total++; } if(semi > 0){ total++; } if(ln > 0){ total++; } //if more than one return true if(total > 1){ cerr << "Multiple connector types forbidden" << endl; return true; } //else false else{ return false; } } //the function searches for the '#' and //removes anything after that character string commentRemoval(string x){ int comm = x.find('#'); //if no '#' is found return the entire string if(comm == -1){ return x; } //if the '#' is the first character return nothing else if(comm == 0){ return ""; } //otherwise return every thing up to the '#' else{ return x.substr(0, comm); } } bool isls(char x[]){ string tmp = x; if(tmp.size() < 2){ return false; } if(tmp.at(0) == 'l' && tmp.at(1) == 's'){ return true; } return false; } bool multiCheck(string x, bool flags[]){ string chk = "alR"; for(unsigned int i = 1; i < x.size(); i++){ if(chk.find(x.at(i)) < x.size() || chk.find(x.at(i)) >= x.size()){ return false; } else if(x.at(i) == 'a'){ flags[0] = true; } else if(x.at(i) == 'l'){ flags[1] = true; } else if(x.at(i) == 'R'){ flags[2] = true; } } return true; } bool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){ if(cmd.size() < 0){ return false; } if(cmd.at(0) != "ls"){ return false; } for(unsigned int i = 1; i < cmd.size(); i++){ if(cmd.at(i) == "-a"){ flags[0] = true; } else if(cmd.at(i) == "-l"){ flags[1] = true; } else if(cmd.at(i) == "-R"){ flags[2] = true; } else if(cmd.at(i).at(0) == '-'){ cout << "RUNS" << endl; if(!multiCheck(cmd.at(i), flags)){ cout << "RETURNS FALSE" << endl; return false; } } else{ files.push_back(cmd.at(i)); } } return true; } //this function runs the command using fork and execvp //and returns once all commands from the entered char[] //have been executed void run(char str[]){ //needed to parse with strtok char* pch; //holds the bool of if a command executed properly bool sucs = true; //holds the return status of a fork/execvp int status = 0; //holds the connector used for the current list of comamnds string connector; //holds a string version of the passed in char[] for later //comparing string strz = str; //the vector that holds the commands to be converted and executed vector<string> cmd; //cbegins breaking the entered commands up by connector pch = strtok(str, ";"); //if the command is empty return if(pch==NULL){ return; } //if using strtok with ";" changed the strz //set the connector to be ";" else if(pch != strz){ connector = ";"; } //else if strz was unchanged use strtok with "&&" //if this changes the string is NULL return //of if strtok changed from the original value of strz set the connector if(pch == strz){ pch = strtok(str, "&&"); if(pch == NULL){ return; } if(pch != strz){ connector = "&&"; } } //repeat the above process but with "||" instead of "&&" if(pch == strz){ pch = strtok(str, "||"); if(pch == NULL){ return; } if(pch != strz){ connector = "||"; } } //if the pch is not NULL and is the exit command exit the programm if(pch != NULL && isExit(pch)){ exit(0); } //this while loop is where fork and execvp execute commands while(pch != NULL){ if(isls(pch)){ bool flags[3]; flags[0] = false; flags[1] = false; flags[2] = false; bool valid = false; vector<string> files; parse(pch, cmd); valid = ls_parse(cmd, flags, files); if(!valid){ cerr << "Invalid flag" << endl; } else{ cout << flags[0] << " " << flags[1] << " " << flags[2] << endl; for(unsigned int i = 0; i < files.size(); i++){ cout << files.at(i) << endl; } } exit(0); } else{ //fork the programm int pid = fork(); //if pid is -1 the fork failed so exit if(pid == -1){ perror("fork"); exit(1); } //if the pid is 0 the current id the current process is the child else if(pid == 0){ //call the parsing function on the command and the cmd vector //to break it up into command and params parse(pch, cmd); //set the size of the dynamic char** that will be passed into execvp int cmd_size = cmd.size() + 1; char** argc = new char*[cmd_size]; //for each string in cmd copy it into argc, which will be passed //into execvp for(unsigned int i = 0 ; i < cmd.size(); i++ ){ argc[i] = new char[cmd.at(i).size()]; strcpy(argc[i], cmd.at(i).c_str()); } //set the last value of argc to be NULL so that execvp will work properly argc[cmd.size()] = NULL; //call execvp on the first element of argc and the entirety of it //if it returns -1 it has failed fo print an error and delete //the dynamically allocated memory if(-1 == execvp(argc[0], argc)){ perror("execvp"); delete[] argc; exit(1); } } //otherwise it is the parrent process else{ //wait for any process to exit, in this case I only created on, //and store its exit code in status if(-1 == waitpid(-1, &status, 0)){ perror("waitpid"); exit(1); } //if the value of status is larger than 0 //it failed if(status > 0){ sucs = false; } //otherwise if succeeded else{ sucs = true; } //clear the vector holding the command to execute cmd.clear(); //run the next command if the connector logic and value of sucs allow it if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){ pch = strtok(NULL, connector.c_str()); } //otherwise return else{ return; } //if the next command is not NULL and is exit exit the program if(pch != NULL && isExit(pch)){ exit(0); } } } } //if there are no more commands to execute/parse return return; } //main takes in commands and passes them to run to execute int main(){ //continue until terminated by a conditional branch within run while(true){ //retrieves the login name //and checks to make sure there was no error char* login = getlogin(); if(login == NULL){ perror("getlogin"); } //sets up the host name variable, maximum of 128 chars char host[128]; //holds return value of gethostname int hostFlag; //sets up input var string input; //retrieves the host name and checks for errors if((hostFlag = gethostname(host, sizeof(host))) == -1){ perror("gethostname"); } //if both login and gethostname rerurned without error //cout the login@host if(login != NULL && hostFlag != -1){ cout << login << "@" << host << "$ "; } //otherwise cout vanilla prompt else{ cout << "$ "; } //retrieve user input including spaces getline(cin, input); //remove anything that is a comment from the users input input = commentRemoval(input); //check for multiple connectors if(!multiConn(input)){ //determines the size of the input int input_size = input.size()+1; //dynamically allocates a char*[] of the size of the input + 1 char* str = new char[input_size]; //copies the input into the char* str[] strcpy(str, input.c_str()); //calls run on the users entered commands run(str); //after running the dynamically allocated memory is deleted delete[] str; } //if there are more than one connector do not run commands //and cerr error } return 0; } <commit_msg>can now run ls with other commands or alone<commit_after>#include <iostream> #include <stdio.h> #include <ctype.h> #include <cstring> #include <vector> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <sys/wait.h> using namespace std; //parses the entered command putting each string seperated //by spaces into a vector passed in by reference //the function utilizes strtok to do this void parse(char x[], vector<string> &v){ char* tmp; //separates the string by spaces tmp = strtok(x, " "); while(tmp != NULL){ //stores in the vector v.push_back(tmp); //searches for the next " " character tmp = strtok(NULL, " "); } } //the function returns false if the command passed in //is "exit" or any spaced variation of it. //returnd false otherwise bool isExit(char x[]){ //sets up vars necessary for comparison string tmp = x; string hold = "exit"; char spc = ' '; unsigned int k = 0; //if the size of the passed in char[] is less than that //necessary for it to be exit return false if(tmp.size() < hold.size()){ return false; } //check each non-space character if within the first //four characters any of the characters dont align with "exit" return false //otherwise count how many more characters there are in the passed in string //if there are more than 4 return false otherwise return true //if a space appears when k is > 0 but < 4 return false, this prevents //bugs like "exi t" from working for(unsigned int i = 0; i < tmp.size(); i++){ if(tmp.at(i) != spc){ if(k < hold.size() && tmp.at(i) != hold.at(k)){ return false; } k++; } else if(k > 0 && k < hold.size()){ return false; } } if(k != hold.size()){ return false; } else{ return true; } } //traverses the entered list of commands //and checks to see how many different kinds of //connectors there are, if there are more than one //it returns true else returns false bool multiConn(string x){ int amp = 0; int ln = 0; int semi = 0; int total = 0; //if any part of the string does not //align with "exit" returns false, otherwise counts //all characters after the passed in command for(unsigned int i = 0; i < x.size(); i++){ if(x.at(i) == '&' && i != x.size()-1){ if(x.at(i+1) == '&'){ amp++; } } if(x.at(i) == '|' && i != x.size()-1){ if(x.at(i+1) == '|'){ ln++; } } if(x.at(i) == ';'){ semi++; } } //calculates the total amount of different connectors if(amp > 0){ total++; } if(semi > 0){ total++; } if(ln > 0){ total++; } //if more than one return true if(total > 1){ cerr << "Multiple connector types forbidden" << endl; return true; } //else false else{ return false; } } //the function searches for the '#' and //removes anything after that character string commentRemoval(string x){ int comm = x.find('#'); //if no '#' is found return the entire string if(comm == -1){ return x; } //if the '#' is the first character return nothing else if(comm == 0){ return ""; } //otherwise return every thing up to the '#' else{ return x.substr(0, comm); } } bool isls(char x[]){ string tmp = x; if(tmp.size() < 2){ return false; } if(tmp.at(0) == 'l' && tmp.at(1) == 's'){ return true; } return false; } bool multiCheck(string x, bool flags[]){ string chk = "alR"; for(unsigned int i = 1; i < x.size(); i++){ if(chk.find(x.at(i)) < 0 || chk.find(x.at(i)) >= x.size()){ return false; } else if(x.at(i) == 'a'){ flags[0] = true; } else if(x.at(i) == 'l'){ flags[1] = true; } else if(x.at(i) == 'R'){ flags[2] = true; } } return true; } bool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){ if(cmd.size() < 0){ return false; } if(cmd.at(0) != "ls"){ return false; } for(unsigned int i = 1; i < cmd.size(); i++){ if(cmd.at(i) == "-a"){ flags[0] = true; } else if(cmd.at(i) == "-l"){ flags[1] = true; } else if(cmd.at(i) == "-R"){ flags[2] = true; } else if(cmd.at(i).at(0) == '-'){ if(!multiCheck(cmd.at(i), flags)){ return false; } } else{ files.push_back(cmd.at(i)); } } return true; } //this function runs the command using fork and execvp //and returns once all commands from the entered char[] //have been executed void run(char str[]){ //needed to parse with strtok char* pch; //holds the bool of if a command executed properly bool sucs = true; //holds the return status of a fork/execvp int status = 0; //holds the connector used for the current list of comamnds string connector; //holds a string version of the passed in char[] for later //comparing string strz = str; //the vector that holds the commands to be converted and executed vector<string> cmd; //cbegins breaking the entered commands up by connector pch = strtok(str, ";"); //if the command is empty return if(pch==NULL){ return; } //if using strtok with ";" changed the strz //set the connector to be ";" else if(pch != strz){ connector = ";"; } //else if strz was unchanged use strtok with "&&" //if this changes the string is NULL return //of if strtok changed from the original value of strz set the connector if(pch == strz){ pch = strtok(str, "&&"); if(pch == NULL){ return; } if(pch != strz){ connector = "&&"; } } //repeat the above process but with "||" instead of "&&" if(pch == strz){ pch = strtok(str, "||"); if(pch == NULL){ return; } if(pch != strz){ connector = "||"; } } //if the pch is not NULL and is the exit command exit the programm if(pch != NULL && isExit(pch)){ exit(0); } //this while loop is where fork and execvp execute commands while(pch != NULL){ if(isls(pch)){ int pid = fork(); if(pid == 0){ bool flags[3]; flags[0] = false; flags[1] = false; flags[2] = false; bool valid = false; vector<string> files; parse(pch, cmd); valid = ls_parse(cmd, flags, files); if(!valid){ cerr << "Invalid flag" << endl; exit(1); } else{ cout << flags[0] << " " << flags[1] << " " << flags[2] << endl; for(unsigned int i = 0; i < files.size(); i++){ cout << files.at(i) << endl; } status = 0; } cmd.clear(); files.clear(); flags[0] = false; flags[1] = false; flags[2] = false; exit(0); } else{ waitpid(-1, &status, 0); } } else{ //fork the programm int pid = fork(); //if pid is -1 the fork failed so exit if(pid == -1){ perror("fork"); exit(1); } //if the pid is 0 the current id the current process is the child else if(pid == 0){ //call the parsing function on the command and the cmd vector //to break it up into command and params parse(pch, cmd); //set the size of the dynamic char** that will be passed into execvp int cmd_size = cmd.size() + 1; char** argc = new char*[cmd_size]; //for each string in cmd copy it into argc, which will be passed //into execvp for(unsigned int i = 0 ; i < cmd.size(); i++ ){ argc[i] = new char[cmd.at(i).size()]; strcpy(argc[i], cmd.at(i).c_str()); } //set the last value of argc to be NULL so that execvp will work properly argc[cmd.size()] = NULL; //call execvp on the first element of argc and the entirety of it //if it returns -1 it has failed fo print an error and delete //the dynamically allocated memory if(-1 == execvp(argc[0], argc)){ perror("execvp"); delete[] argc; exit(1); } } //otherwise it is the parrent process else{ //wait for any process to exit, in this case I only created on, //and store its exit code in status if(-1 == waitpid(-1, &status, 0)){ perror("waitpid"); exit(1); } } } //if the value of status is larger than 0 //it failed if(status > 0){ sucs = false; } //otherwise if succeeded else{ sucs = true; } //clear the vector holding the command to execute cmd.clear(); //run the next command if the connector logic and value of sucs allow it if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){ pch = strtok(NULL, connector.c_str()); } //otherwise return else{ return; } //if the next command is not NULL and is exit exit the program if(pch != NULL && isExit(pch)){ exit(0); } } //if there are no more commands to execute/parse return return; } //main takes in commands and passes them to run to execute int main(){ //continue until terminated by a conditional branch within run while(true){ //retrieves the login name //and checks to make sure there was no error char* login = getlogin(); if(login == NULL){ perror("getlogin"); } //sets up the host name variable, maximum of 128 chars char host[128]; //holds return value of gethostname int hostFlag; //sets up input var string input; //retrieves the host name and checks for errors if((hostFlag = gethostname(host, sizeof(host))) == -1){ perror("gethostname"); } //if both login and gethostname rerurned without error //cout the login@host if(login != NULL && hostFlag != -1){ cout << login << "@" << host << "$ "; } //otherwise cout vanilla prompt else{ cout << "$ "; } //retrieve user input including spaces getline(cin, input); //remove anything that is a comment from the users input input = commentRemoval(input); //check for multiple connectors if(!multiConn(input)){ //determines the size of the input int input_size = input.size()+1; //dynamically allocates a char*[] of the size of the input + 1 char* str = new char[input_size]; //copies the input into the char* str[] strcpy(str, input.c_str()); //calls run on the users entered commands run(str); //after running the dynamically allocated memory is deleted delete[] str; } //if there are more than one connector do not run commands //and cerr error } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2020-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <compat.h> #include <compat/endian.h> #include <crypto/sha256.h> #include <fs.h> #include <i2p.h> #include <logging.h> #include <netaddress.h> #include <netbase.h> #include <random.h> #include <util/strencodings.h> #include <tinyformat.h> #include <util/readwritefile.h> #include <util/sock.h> #include <util/spanparsing.h> #include <util/system.h> #include <chrono> #include <memory> #include <stdexcept> #include <string> namespace i2p { /** * Swap Standard Base64 <-> I2P Base64. * Standard Base64 uses `+` and `/` as last two characters of its alphabet. * I2P Base64 uses `-` and `~` respectively. * So it is easy to detect in which one is the input and convert to the other. * @param[in] from Input to convert. * @return converted `from` */ static std::string SwapBase64(const std::string& from) { std::string to; to.resize(from.size()); for (size_t i = 0; i < from.size(); ++i) { switch (from[i]) { case '-': to[i] = '+'; break; case '~': to[i] = '/'; break; case '+': to[i] = '-'; break; case '/': to[i] = '~'; break; default: to[i] = from[i]; break; } } return to; } /** * Decode an I2P-style Base64 string. * @param[in] i2p_b64 I2P-style Base64 string. * @return decoded `i2p_b64` * @throw std::runtime_error if decoding fails */ static Binary DecodeI2PBase64(const std::string& i2p_b64) { const std::string& std_b64 = SwapBase64(i2p_b64); bool invalid; Binary decoded = DecodeBase64(std_b64.c_str(), &invalid); if (invalid) { throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64)); } return decoded; } /** * Derive the .b32.i2p address of an I2P destination (binary). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestBinToAddr(const Binary& dest) { CSHA256 hasher; hasher.Write(dest.data(), dest.size()); unsigned char hash[CSHA256::OUTPUT_SIZE]; hasher.Finalize(hash); CNetAddr addr; const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p"; if (!addr.SetSpecial(addr_str)) { throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str)); } return addr; } /** * Derive the .b32.i2p address of an I2P destination (I2P-style Base64). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestB64ToAddr(const std::string& dest) { const Binary& decoded = DecodeI2PBase64(dest); return DestBinToAddr(decoded); } namespace sam { Session::Session(const fs::path& private_key_file, const CService& control_host, CThreadInterrupt* interrupt) : m_private_key_file(private_key_file), m_control_host(control_host), m_interrupt(interrupt), m_control_sock(std::make_unique<Sock>(INVALID_SOCKET)) { } Session::~Session() { LOCK(m_mutex); Disconnect(); } bool Session::Listen(Connection& conn) { try { LOCK(m_mutex); CreateIfNotCreatedAlready(); conn.me = m_my_addr; conn.sock = StreamAccept(); return true; } catch (const std::runtime_error& e) { Log("Error listening: %s", e.what()); CheckControlSock(); } return false; } bool Session::Accept(Connection& conn) { try { while (!*m_interrupt) { Sock::Event occurred; conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred); if ((occurred & Sock::RECV) == 0) { // Timeout, no incoming connections within MAX_WAIT_FOR_IO. continue; } const std::string& peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE); conn.peer = CService(DestB64ToAddr(peer_dest), Params().GetDefaultPort()); return true; } } catch (const std::runtime_error& e) { Log("Error accepting: %s", e.what()); CheckControlSock(); } return false; } bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error) { proxy_error = true; std::string session_id; std::unique_ptr<Sock> sock; conn.peer = to; try { { LOCK(m_mutex); CreateIfNotCreatedAlready(); session_id = m_session_id; conn.me = m_my_addr; sock = Hello(); } const Reply& lookup_reply = SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringIP())); const std::string& dest = lookup_reply.Get("VALUE"); const Reply& connect_reply = SendRequestAndGetReply( *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest), false); const std::string& result = connect_reply.Get("RESULT"); if (result == "OK") { conn.sock = std::move(sock); return true; } if (result == "INVALID_ID") { LOCK(m_mutex); Disconnect(); throw std::runtime_error("Invalid session id"); } if (result == "CANT_REACH_PEER" || result == "TIMEOUT") { proxy_error = false; } throw std::runtime_error(strprintf("\"%s\"", connect_reply.full)); } catch (const std::runtime_error& e) { Log("Error connecting to %s: %s", to.ToString(), e.what()); CheckControlSock(); return false; } } // Private methods std::string Session::Reply::Get(const std::string& key) const { const auto& pos = keys.find(key); if (pos == keys.end() || !pos->second.has_value()) { throw std::runtime_error( strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full)); } return pos->second.value(); } template <typename... Args> void Session::Log(const std::string& fmt, const Args&... args) const { LogPrint(BCLog::I2P, "I2P: %s\n", tfm::format(fmt, args...)); } Session::Reply Session::SendRequestAndGetReply(const Sock& sock, const std::string& request, bool check_result_ok) const { sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt); Reply reply; // Don't log the full "SESSION CREATE ..." because it contains our private key. reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request; // It could take a few minutes for the I2P router to reply as it is querying the I2P network // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is // signaled. static constexpr auto recv_timeout = 3min; reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE); for (const auto& kv : spanparsing::Split(reply.full, ' ')) { const auto& pos = std::find(kv.begin(), kv.end(), '='); if (pos != kv.end()) { reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()}); } else { reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt); } } if (check_result_ok && reply.Get("RESULT") != "OK") { throw std::runtime_error( strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full)); } return reply; } std::unique_ptr<Sock> Session::Hello() const { auto sock = CreateSock(m_control_host); if (!sock) { throw std::runtime_error("Cannot create socket"); } if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) { throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToString())); } SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1"); return sock; } void Session::CheckControlSock() { LOCK(m_mutex); std::string errmsg; if (!m_control_sock->IsConnected(errmsg)) { Log("Control socket error: %s", errmsg); Disconnect(); } } void Session::DestGenerate(const Sock& sock) { // https://geti2p.net/spec/common-structures#key-certificates // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations". // Use "7" because i2pd <2.24.0 does not recognize the textual form. const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false); m_private_key = DecodeI2PBase64(reply.Get("PRIV")); } void Session::GenerateAndSavePrivateKey(const Sock& sock) { DestGenerate(sock); // umask is set to 077 in init.cpp, which is ok (unless -sysperms is given) if (!WriteBinaryFile(m_private_key_file, std::string(m_private_key.begin(), m_private_key.end()))) { throw std::runtime_error( strprintf("Cannot save I2P private key to %s", m_private_key_file)); } } Binary Session::MyDestination() const { // From https://geti2p.net/spec/common-structures#destination: // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be // non-zero" static constexpr size_t DEST_LEN_BASE = 387; static constexpr size_t CERT_LEN_POS = 385; uint16_t cert_len; memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len)); cert_len = be16toh(cert_len); const size_t dest_len = DEST_LEN_BASE + cert_len; return Binary{m_private_key.begin(), m_private_key.begin() + dest_len}; } void Session::CreateIfNotCreatedAlready() { std::string errmsg; if (m_control_sock->IsConnected(errmsg)) { return; } Log("Creating SAM session with %s", m_control_host.ToString()); auto sock = Hello(); const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file); if (read_ok) { m_private_key.assign(data.begin(), data.end()); } else { GenerateAndSavePrivateKey(*sock); } const std::string& session_id = GetRandHash().GetHex().substr(0, 10); // full is an overkill, too verbose in the logs const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key)); SendRequestAndGetReply(*sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s", session_id, private_key_b64)); m_my_addr = CService(DestBinToAddr(MyDestination()), Params().GetDefaultPort()); m_session_id = session_id; m_control_sock = std::move(sock); LogPrintf("I2P: SAM session created: session id=%s, my address=%s\n", m_session_id, m_my_addr.ToString()); } std::unique_ptr<Sock> Session::StreamAccept() { auto sock = Hello(); const Reply& reply = SendRequestAndGetReply( *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false); const std::string& result = reply.Get("RESULT"); if (result == "OK") { return sock; } if (result == "INVALID_ID") { // If our session id is invalid, then force session re-creation on next usage. Disconnect(); } throw std::runtime_error(strprintf("\"%s\"", reply.full)); } void Session::Disconnect() { if (m_control_sock->Get() != INVALID_SOCKET) { if (m_session_id.empty()) { Log("Destroying incomplete session"); } else { Log("Destroying session %s", m_session_id); } } m_control_sock->Reset(); m_session_id.clear(); } } // namespace sam } // namespace i2p <commit_msg>i2p: cancel the Accept() method if waiting on the socket errors<commit_after>// Copyright (c) 2020-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <compat.h> #include <compat/endian.h> #include <crypto/sha256.h> #include <fs.h> #include <i2p.h> #include <logging.h> #include <netaddress.h> #include <netbase.h> #include <random.h> #include <util/strencodings.h> #include <tinyformat.h> #include <util/readwritefile.h> #include <util/sock.h> #include <util/spanparsing.h> #include <util/system.h> #include <chrono> #include <memory> #include <stdexcept> #include <string> namespace i2p { /** * Swap Standard Base64 <-> I2P Base64. * Standard Base64 uses `+` and `/` as last two characters of its alphabet. * I2P Base64 uses `-` and `~` respectively. * So it is easy to detect in which one is the input and convert to the other. * @param[in] from Input to convert. * @return converted `from` */ static std::string SwapBase64(const std::string& from) { std::string to; to.resize(from.size()); for (size_t i = 0; i < from.size(); ++i) { switch (from[i]) { case '-': to[i] = '+'; break; case '~': to[i] = '/'; break; case '+': to[i] = '-'; break; case '/': to[i] = '~'; break; default: to[i] = from[i]; break; } } return to; } /** * Decode an I2P-style Base64 string. * @param[in] i2p_b64 I2P-style Base64 string. * @return decoded `i2p_b64` * @throw std::runtime_error if decoding fails */ static Binary DecodeI2PBase64(const std::string& i2p_b64) { const std::string& std_b64 = SwapBase64(i2p_b64); bool invalid; Binary decoded = DecodeBase64(std_b64.c_str(), &invalid); if (invalid) { throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64)); } return decoded; } /** * Derive the .b32.i2p address of an I2P destination (binary). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestBinToAddr(const Binary& dest) { CSHA256 hasher; hasher.Write(dest.data(), dest.size()); unsigned char hash[CSHA256::OUTPUT_SIZE]; hasher.Finalize(hash); CNetAddr addr; const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p"; if (!addr.SetSpecial(addr_str)) { throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str)); } return addr; } /** * Derive the .b32.i2p address of an I2P destination (I2P-style Base64). * @param[in] dest I2P destination. * @return the address that corresponds to `dest` * @throw std::runtime_error if conversion fails */ static CNetAddr DestB64ToAddr(const std::string& dest) { const Binary& decoded = DecodeI2PBase64(dest); return DestBinToAddr(decoded); } namespace sam { Session::Session(const fs::path& private_key_file, const CService& control_host, CThreadInterrupt* interrupt) : m_private_key_file(private_key_file), m_control_host(control_host), m_interrupt(interrupt), m_control_sock(std::make_unique<Sock>(INVALID_SOCKET)) { } Session::~Session() { LOCK(m_mutex); Disconnect(); } bool Session::Listen(Connection& conn) { try { LOCK(m_mutex); CreateIfNotCreatedAlready(); conn.me = m_my_addr; conn.sock = StreamAccept(); return true; } catch (const std::runtime_error& e) { Log("Error listening: %s", e.what()); CheckControlSock(); } return false; } bool Session::Accept(Connection& conn) { try { while (!*m_interrupt) { Sock::Event occurred; if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) { throw std::runtime_error("wait on socket failed"); } if ((occurred & Sock::RECV) == 0) { // Timeout, no incoming connections within MAX_WAIT_FOR_IO. continue; } const std::string& peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE); conn.peer = CService(DestB64ToAddr(peer_dest), Params().GetDefaultPort()); return true; } } catch (const std::runtime_error& e) { Log("Error accepting: %s", e.what()); CheckControlSock(); } return false; } bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error) { proxy_error = true; std::string session_id; std::unique_ptr<Sock> sock; conn.peer = to; try { { LOCK(m_mutex); CreateIfNotCreatedAlready(); session_id = m_session_id; conn.me = m_my_addr; sock = Hello(); } const Reply& lookup_reply = SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringIP())); const std::string& dest = lookup_reply.Get("VALUE"); const Reply& connect_reply = SendRequestAndGetReply( *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest), false); const std::string& result = connect_reply.Get("RESULT"); if (result == "OK") { conn.sock = std::move(sock); return true; } if (result == "INVALID_ID") { LOCK(m_mutex); Disconnect(); throw std::runtime_error("Invalid session id"); } if (result == "CANT_REACH_PEER" || result == "TIMEOUT") { proxy_error = false; } throw std::runtime_error(strprintf("\"%s\"", connect_reply.full)); } catch (const std::runtime_error& e) { Log("Error connecting to %s: %s", to.ToString(), e.what()); CheckControlSock(); return false; } } // Private methods std::string Session::Reply::Get(const std::string& key) const { const auto& pos = keys.find(key); if (pos == keys.end() || !pos->second.has_value()) { throw std::runtime_error( strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full)); } return pos->second.value(); } template <typename... Args> void Session::Log(const std::string& fmt, const Args&... args) const { LogPrint(BCLog::I2P, "I2P: %s\n", tfm::format(fmt, args...)); } Session::Reply Session::SendRequestAndGetReply(const Sock& sock, const std::string& request, bool check_result_ok) const { sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt); Reply reply; // Don't log the full "SESSION CREATE ..." because it contains our private key. reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request; // It could take a few minutes for the I2P router to reply as it is querying the I2P network // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is // signaled. static constexpr auto recv_timeout = 3min; reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE); for (const auto& kv : spanparsing::Split(reply.full, ' ')) { const auto& pos = std::find(kv.begin(), kv.end(), '='); if (pos != kv.end()) { reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()}); } else { reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt); } } if (check_result_ok && reply.Get("RESULT") != "OK") { throw std::runtime_error( strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full)); } return reply; } std::unique_ptr<Sock> Session::Hello() const { auto sock = CreateSock(m_control_host); if (!sock) { throw std::runtime_error("Cannot create socket"); } if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) { throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToString())); } SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1"); return sock; } void Session::CheckControlSock() { LOCK(m_mutex); std::string errmsg; if (!m_control_sock->IsConnected(errmsg)) { Log("Control socket error: %s", errmsg); Disconnect(); } } void Session::DestGenerate(const Sock& sock) { // https://geti2p.net/spec/common-structures#key-certificates // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations". // Use "7" because i2pd <2.24.0 does not recognize the textual form. const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false); m_private_key = DecodeI2PBase64(reply.Get("PRIV")); } void Session::GenerateAndSavePrivateKey(const Sock& sock) { DestGenerate(sock); // umask is set to 077 in init.cpp, which is ok (unless -sysperms is given) if (!WriteBinaryFile(m_private_key_file, std::string(m_private_key.begin(), m_private_key.end()))) { throw std::runtime_error( strprintf("Cannot save I2P private key to %s", m_private_key_file)); } } Binary Session::MyDestination() const { // From https://geti2p.net/spec/common-structures#destination: // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be // non-zero" static constexpr size_t DEST_LEN_BASE = 387; static constexpr size_t CERT_LEN_POS = 385; uint16_t cert_len; memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len)); cert_len = be16toh(cert_len); const size_t dest_len = DEST_LEN_BASE + cert_len; return Binary{m_private_key.begin(), m_private_key.begin() + dest_len}; } void Session::CreateIfNotCreatedAlready() { std::string errmsg; if (m_control_sock->IsConnected(errmsg)) { return; } Log("Creating SAM session with %s", m_control_host.ToString()); auto sock = Hello(); const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file); if (read_ok) { m_private_key.assign(data.begin(), data.end()); } else { GenerateAndSavePrivateKey(*sock); } const std::string& session_id = GetRandHash().GetHex().substr(0, 10); // full is an overkill, too verbose in the logs const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key)); SendRequestAndGetReply(*sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s", session_id, private_key_b64)); m_my_addr = CService(DestBinToAddr(MyDestination()), Params().GetDefaultPort()); m_session_id = session_id; m_control_sock = std::move(sock); LogPrintf("I2P: SAM session created: session id=%s, my address=%s\n", m_session_id, m_my_addr.ToString()); } std::unique_ptr<Sock> Session::StreamAccept() { auto sock = Hello(); const Reply& reply = SendRequestAndGetReply( *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false); const std::string& result = reply.Get("RESULT"); if (result == "OK") { return sock; } if (result == "INVALID_ID") { // If our session id is invalid, then force session re-creation on next usage. Disconnect(); } throw std::runtime_error(strprintf("\"%s\"", reply.full)); } void Session::Disconnect() { if (m_control_sock->Get() != INVALID_SOCKET) { if (m_session_id.empty()) { Log("Destroying incomplete session"); } else { Log("Destroying session %s", m_session_id); } } m_control_sock->Reset(); m_session_id.clear(); } } // namespace sam } // namespace i2p <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); if (fUseProxy) return false; CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exiting\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrConnect)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); else strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (!fUseProxy && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST\r"); Send(hSocket, "WHO #bitcoinTEST\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :[email protected] JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <commit_msg>Only encode IPv4 addresses in IRC nicks<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); if (fUseProxy) return false; CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exiting\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (!fUseProxy && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #bitcoinTEST\r"); Send(hSocket, "WHO #bitcoinTEST\r"); } else { // randomly join #bitcoin00-#bitcoin99 int channel_number = GetRandInt(100); Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :[email protected] JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <|endoftext|>
<commit_before>#include <glib.h> #include <uv.h> #include <nan.h> #include <v8.h> #include "debug.h" #include "gi.h" #include "loop.h" #include "macros.h" #include "util.h" /* Integration for the GLib main loop and uv's main loop */ /* The way that this works is that we take uv's loop and nest it inside GLib's * mainloop, since nesting GLib inside uv seems to be fairly impossible until * either uv allows external sources to drive prepare/check, or until GLib * exposes an epoll fd to wait on... */ using namespace v8; namespace GNodeJS { static void CallNextTickCallback (); static Nan::Persistent<Array> loopStack(Nan::New<Array> ()); struct uv_loop_source { GSource source; uv_loop_t *loop; }; static gboolean loop_source_prepare (GSource *base, int *timeout) { struct uv_loop_source *source = (struct uv_loop_source *) base; uv_update_time (source->loop); bool loop_alive = uv_loop_alive (source->loop); /* If the loop is dead, we can simply sleep forever until a GTK+ source * (presumably) wakes us back up again. */ if (!loop_alive) return FALSE; /* Otherwise, check the timeout. If the timeout is 0, that means we're * ready to go. Otherwise, keep sleeping until the timeout happens again. */ int t = uv_backend_timeout (source->loop); *timeout = t; if (t == 0) return TRUE; else return FALSE; } static gboolean loop_source_dispatch (GSource *base, GSourceFunc callback, gpointer user_data) { struct uv_loop_source *source = (struct uv_loop_source *) base; uv_run (source->loop, UV_RUN_ONCE); CallMicrotaskHandlers (); return G_SOURCE_CONTINUE; } static GSourceFuncs uv_loop_source_funcs = { /* prepare */ loop_source_prepare, /* check */ NULL, /* dispatch */ loop_source_dispatch, /* finalize */ NULL, NULL, NULL, }; static GSource *loop_source_new (uv_loop_t *loop) { struct uv_loop_source *source = (struct uv_loop_source *) g_source_new (&uv_loop_source_funcs, sizeof (*source)); source->loop = loop; g_source_add_unix_fd (&source->source, uv_backend_fd (loop), (GIOCondition) (G_IO_IN | G_IO_OUT | G_IO_ERR)); return &source->source; } /** * This function is used to call "process._tickCallback()" inside NodeJS. * We want to do this after we run the libuv eventloop because there might * be pending micro-tasks from Promises or calls to 'process.nextTick()'. */ static void CallNextTickCallback() { static Nan::Persistent<Object> process; static Nan::Persistent<Object> tickCallback; if (tickCallback.IsEmpty()) { auto global = Nan::GetCurrentContext()->Global(); auto processObject = Nan::To<Object> (global->Get(UTF8("process"))); if (processObject.IsEmpty()) { return; } Local<Object> processObjectChecked = processObject.ToLocalChecked(); Local<Value> tickCallbackValue = processObjectChecked->Get(UTF8("_tickCallback")); if (!tickCallbackValue->IsFunction()) { return; } process.Reset(processObjectChecked); tickCallback.Reset(TO_OBJECT (tickCallbackValue)); } if (!tickCallback.IsEmpty()) { Nan::CallAsFunction(Nan::New<Object> (tickCallback), Nan::New<Object> (process), 0, nullptr); } } void CallMicrotaskHandlers () { CallNextTickCallback(); Isolate::GetCurrent()->RunMicrotasks(); } void StartLoop() { GSource *source = loop_source_new (uv_default_loop ()); g_source_attach (source, NULL); } Local<Array> GetLoopStack() { return Nan::New<Array>(loopStack); } void QuitLoopStack() { Local<Array> stack = GetLoopStack(); for (uint32_t i = 0; i < stack->Length(); i++) { Local<Object> fn = TO_OBJECT (Nan::Get(stack, i).ToLocalChecked()); Local<Object> self = fn; #ifndef NDEBUG auto name = Nan::Get(fn, UTF8("name")); if (name.IsEmpty() || TO_STRING (name.ToLocalChecked())->Length() == 0) log("calling (anonymous)"); else log("calling %s", *Nan::Utf8String(name.ToLocalChecked())); #endif Nan::CallAsFunction(fn, self, 0, nullptr); } loopStack.Reset(Nan::New<Array>()); } }; <commit_msg>loop: remove forward declaration<commit_after>#include <glib.h> #include <uv.h> #include <nan.h> #include <v8.h> #include "debug.h" #include "gi.h" #include "loop.h" #include "macros.h" #include "util.h" /* Integration for the GLib main loop and uv's main loop */ /* The way that this works is that we take uv's loop and nest it inside GLib's * mainloop, since nesting GLib inside uv seems to be fairly impossible until * either uv allows external sources to drive prepare/check, or until GLib * exposes an epoll fd to wait on... */ using namespace v8; namespace GNodeJS { static Nan::Persistent<Array> loopStack(Nan::New<Array> ()); struct uv_loop_source { GSource source; uv_loop_t *loop; }; static gboolean loop_source_prepare (GSource *base, int *timeout) { struct uv_loop_source *source = (struct uv_loop_source *) base; uv_update_time (source->loop); bool loop_alive = uv_loop_alive (source->loop); /* If the loop is dead, we can simply sleep forever until a GTK+ source * (presumably) wakes us back up again. */ if (!loop_alive) return FALSE; /* Otherwise, check the timeout. If the timeout is 0, that means we're * ready to go. Otherwise, keep sleeping until the timeout happens again. */ int t = uv_backend_timeout (source->loop); *timeout = t; if (t == 0) return TRUE; else return FALSE; } static gboolean loop_source_dispatch (GSource *base, GSourceFunc callback, gpointer user_data) { struct uv_loop_source *source = (struct uv_loop_source *) base; uv_run (source->loop, UV_RUN_ONCE); CallMicrotaskHandlers (); return G_SOURCE_CONTINUE; } static GSourceFuncs uv_loop_source_funcs = { /* prepare */ loop_source_prepare, /* check */ NULL, /* dispatch */ loop_source_dispatch, /* finalize */ NULL, NULL, NULL, }; static GSource *loop_source_new (uv_loop_t *loop) { struct uv_loop_source *source = (struct uv_loop_source *) g_source_new (&uv_loop_source_funcs, sizeof (*source)); source->loop = loop; g_source_add_unix_fd (&source->source, uv_backend_fd (loop), (GIOCondition) (G_IO_IN | G_IO_OUT | G_IO_ERR)); return &source->source; } /** * This function is used to call "process._tickCallback()" inside NodeJS. * We want to do this after we run the libuv eventloop because there might * be pending micro-tasks from Promises or calls to 'process.nextTick()'. */ static void CallNextTickCallback() { static Nan::Persistent<Object> process; static Nan::Persistent<Object> tickCallback; if (tickCallback.IsEmpty()) { auto global = Nan::GetCurrentContext()->Global(); auto processObject = Nan::To<Object> (global->Get(UTF8("process"))); if (processObject.IsEmpty()) { return; } Local<Object> processObjectChecked = processObject.ToLocalChecked(); Local<Value> tickCallbackValue = processObjectChecked->Get(UTF8("_tickCallback")); if (!tickCallbackValue->IsFunction()) { return; } process.Reset(processObjectChecked); tickCallback.Reset(TO_OBJECT (tickCallbackValue)); } if (!tickCallback.IsEmpty()) { Nan::CallAsFunction(Nan::New<Object> (tickCallback), Nan::New<Object> (process), 0, nullptr); } } void CallMicrotaskHandlers () { CallNextTickCallback(); Isolate::GetCurrent()->RunMicrotasks(); } void StartLoop() { GSource *source = loop_source_new (uv_default_loop ()); g_source_attach (source, NULL); } Local<Array> GetLoopStack() { return Nan::New<Array>(loopStack); } void QuitLoopStack() { Local<Array> stack = GetLoopStack(); for (uint32_t i = 0; i < stack->Length(); i++) { Local<Object> fn = TO_OBJECT (Nan::Get(stack, i).ToLocalChecked()); Local<Object> self = fn; #ifndef NDEBUG auto name = Nan::Get(fn, UTF8("name")); if (name.IsEmpty() || TO_STRING (name.ToLocalChecked())->Length() == 0) log("calling (anonymous)"); else log("calling %s", *Nan::Utf8String(name.ToLocalChecked())); #endif Nan::CallAsFunction(fn, self, 0, nullptr); } loopStack.Reset(Nan::New<Array>()); } }; <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/http_parser.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #else #include <boost/asio/ip/host_name.hpp> #include <boost/asio/ip/multicast.hpp> #endif #include <boost/thread/mutex.hpp> #include <cstdlib> #include <boost/config.hpp> using boost::bind; using namespace libtorrent; namespace libtorrent { // defined in broadcast_socket.cpp address guess_local_address(io_service&); } static error_code ec; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(1) , m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771) , bind(&lsd::on_announce, self(), _1, _2, _3)) , m_broadcast_timer(ios) , m_disabled(false) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif } lsd::~lsd() {} void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; std::stringstream btsearch; btsearch << "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: " << listen_port << "\r\n" "Infohash: " << ih << "\r\n" "\r\n\r\n"; std::string const& msg = btsearch.str(); m_retry_count = 1; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> announce: ih: " << ih << " port: " << listen_port << std::endl; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::resend_announce(error_code const& e, std::string msg) { if (e) return; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::on_announce(udp::endpoint const& from, char* buffer , std::size_t bytes_transferred) { using namespace libtorrent::detail; http_parser p; bool error = false; p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred) , error); if (!p.header_finished() || error) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: incomplete HTTP message\n"; #endif return; } if (p.method() != "bt-search") { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid HTTP method: " << p.method() << std::endl; #endif return; } std::string const& port_str = p.header("port"); if (port_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing port" << std::endl; #endif return; } std::string const& ih_str = p.header("infohash"); if (ih_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing infohash" << std::endl; #endif return; } sha1_hash ih(0); std::istringstream ih_sstr(ih_str); ih_sstr >> ih; int port = std::atoi(port_str.c_str()); if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " *** incoming local announce " << from.address() << ":" << port << " ih: " << ih << std::endl; #endif // we got an announce, pass it on through the callback #ifndef BOOST_NO_EXCEPTIONS try { #endif m_callback(tcp::endpoint(from.address(), port), ih); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif } } void lsd::close() { m_socket.close(); error_code ec; m_broadcast_timer.cancel(ec); m_disabled = true; m_callback.clear(); } <commit_msg>fixed locale dependence in lsd.cpp<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/http_parser.hpp" #include "libtorrent/escape_string.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #else #include <boost/asio/ip/host_name.hpp> #include <boost/asio/ip/multicast.hpp> #endif #include <boost/thread/mutex.hpp> #include <cstdlib> #include <boost/config.hpp> using boost::bind; using namespace libtorrent; namespace libtorrent { // defined in broadcast_socket.cpp address guess_local_address(io_service&); } static error_code ec; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(1) , m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771) , bind(&lsd::on_announce, self(), _1, _2, _3)) , m_broadcast_timer(ios) , m_disabled(false) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif } lsd::~lsd() {} void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; std::stringstream btsearch; btsearch << "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: " << to_string(listen_port).elems << "\r\n" "Infohash: " << ih << "\r\n" "\r\n\r\n"; std::string const& msg = btsearch.str(); m_retry_count = 1; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> announce: ih: " << ih << " port: " << to_string(listen_port).elems << std::endl; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::resend_announce(error_code const& e, std::string msg) { if (e) return; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::on_announce(udp::endpoint const& from, char* buffer , std::size_t bytes_transferred) { using namespace libtorrent::detail; http_parser p; bool error = false; p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred) , error); if (!p.header_finished() || error) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: incomplete HTTP message\n"; #endif return; } if (p.method() != "bt-search") { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid HTTP method: " << p.method() << std::endl; #endif return; } std::string const& port_str = p.header("port"); if (port_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing port" << std::endl; #endif return; } std::string const& ih_str = p.header("infohash"); if (ih_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing infohash" << std::endl; #endif return; } sha1_hash ih(0); std::istringstream ih_sstr(ih_str); ih_sstr >> ih; int port = std::atoi(port_str.c_str()); if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " *** incoming local announce " << from.address() << ":" << to_string(port).elems << " ih: " << ih << std::endl; #endif // we got an announce, pass it on through the callback #ifndef BOOST_NO_EXCEPTIONS try { #endif m_callback(tcp::endpoint(from.address(), port), ih); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif } } void lsd::close() { m_socket.close(); error_code ec; m_broadcast_timer.cancel(ec); m_disabled = true; m_callback.clear(); } <|endoftext|>
<commit_before>#if _WIN32 #include <Windows.h> #endif // _WIN32 #include <GL/gl.h> #include <GL/glut.h> #include <cstdio> #include <cstdlib> #include <cmath> #include <omp.h> #include <map> #include <vector> #include <chrono> #include <thread> #include <mutex> #include <iostream> #include "spvis.hpp" static std::mutex thread_mutex; static TrainData points; static TrainVector pvector; static Classifier *classifier = NULL; Classifiers &getClassifiers() { static Classifiers c; return c; } void registerClassifier(const std::string &name, Classifier *c) { auto &cs = getClassifiers(); cs[name] = c; } static int window_w; static int window_h; void screen_prop(int &w, int &h) { w = window_w; h = window_h; } struct PointColor { Point point; float rgb[3]; }; static bool run_step = true; static void display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); thread_mutex.lock(); glPointSize(1); for (int i = 0; i < window_h; ++i) { for (int j = 0; j < window_w; ++j) { const Point p = {j, i}; Likelihood l; classifier->classify(p, l); l.normalize(); float d = std::abs(l.class1 - l.class2); float c = 1 - d; float r = l.class1 + (1 - l.class1) * c; float g = c; float b = l.class2 + (1 - l.class2) * c; glColor3f(r, g, b); glBegin(GL_POINTS); glVertex2i(j, i); glEnd(); } } thread_mutex.unlock(); glPointSize(7); glColor3f(0.0f, 0.0f, 0.0f); glBegin(GL_POINTS); for (const auto &v : points) { glVertex2i(v.first.x, v.first.y); } glEnd(); glPointSize(3); for (const auto &v : points) { glColor3f(v.second.class1, 0.0f, v.second.class2); glBegin(GL_POINTS); glVertex2i(v.first.x, v.first.y); glEnd(); } glutSwapBuffers(); } static void reshape(int w, int h) { window_w = w; window_h = h; printf("%d %d\n", w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, h, 0); glViewport(0, 0, w, h); } static void keyboard(unsigned char key, int x, int y) { if (key == 27 || key == 'q') { exit(0); } if (key == 'r') { points.clear(); pvector.clear(); thread_mutex.lock(); classifier->initialize(points, pvector); thread_mutex.unlock(); } if (key == 't') { thread_mutex.lock(); run_step = !run_step; printf("run_step = %d\n", run_step); thread_mutex.unlock(); } } static void special(int key, int x, int y) { } static void mouse(int button, int state, int x, int y) { if (state == GLUT_UP) return; Point p = {x, y}; points[p] = {(button == GLUT_LEFT_BUTTON ? 1.0f : 0.0f), (button == GLUT_RIGHT_BUTTON ? 1.0f : 0.0f)}; pvector.push_back(*points.find(p)); thread_mutex.lock(); classifier->initialize(points, pvector); thread_mutex.unlock(); } int main(int argc, char **argv) { using namespace std; const auto &classifiers = getClassifiers(); if (classifiers.size() == 0) { cerr << "No Classifier compiled" << endl; return 1; } int idx = -1; std::vector<Classifier *> cvec; cout << "Supported Classifiers:" << endl; for (const auto &c : classifiers) { cout << cvec.size() << "\t: " << c.first << endl; cvec.push_back(c.second); } cout << "Select Classfier: "; while (idx < 0 || idx > classifiers.size()) { cin >> idx; } classifier = cvec[idx]; std::thread step_thread([]() { int cnt = 0; while (true) { if (++cnt > 5000) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); cnt = 0; } thread_mutex.lock(); if (!run_step) { thread_mutex.unlock(); continue; } classifier->step(); thread_mutex.unlock(); } }); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutCreateWindow("spvis"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutSpecialFunc(special); glutMouseFunc(mouse); glutIdleFunc(display); glClearColor(0.0, 0.0, 0.0, 1.0); glutMainLoop(); return 0; } <commit_msg>Some updates<commit_after>#if _WIN32 #include <Windows.h> #endif // _WIN32 #include <GL/gl.h> #include <GL/glut.h> #include <cstdio> #include <cstdlib> #include <cmath> #include <omp.h> #include <map> #include <vector> #include <chrono> #include <thread> #include <mutex> #include <iostream> #include "spvis.hpp" static std::mutex thread_mutex; static TrainData points; static TrainVector pvector; static Classifier *classifier = NULL; Classifiers &getClassifiers() { static Classifiers c; return c; } void registerClassifier(const std::string &name, Classifier *c) { auto &cs = getClassifiers(); cs[name] = c; } static int window_w; static int window_h; void screen_prop(int &w, int &h) { w = window_w; h = window_h; } struct PointColor { Point point; float rgb[3]; }; static bool run_step = true; static void display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); thread_mutex.lock(); glPointSize(1); for (int i = 0; i < window_h; ++i) { for (int j = 0; j < window_w; ++j) { const Point p = {j, i}; Likelihood l; classifier->classify(p, l); l.normalize(); float d = std::abs(l.class1 - l.class2); float c = 1 - d; float r = l.class1 + (1 - l.class1) * c; float g = c; float b = l.class2 + (1 - l.class2) * c; glColor3f(r, g, b); glBegin(GL_POINTS); glVertex2i(j, i); glEnd(); } } thread_mutex.unlock(); glPointSize(7); glColor3f(0.0f, 0.0f, 0.0f); glBegin(GL_POINTS); for (const auto &v : points) { glVertex2i(v.first.x, v.first.y); } glEnd(); glPointSize(3); for (const auto &v : points) { glColor3f(v.second.class1, 0.0f, v.second.class2); glBegin(GL_POINTS); glVertex2i(v.first.x, v.first.y); glEnd(); } glutSwapBuffers(); } static void reshape(int w, int h) { window_w = w; window_h = h; printf("%d %d\n", w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, h, 0); glViewport(0, 0, w, h); } static void keyboard(unsigned char key, int x, int y) { if (key == 27 || key == 'q') { exit(0); } if (key == 'r') { points.clear(); pvector.clear(); thread_mutex.lock(); classifier->initialize(points, pvector); thread_mutex.unlock(); } if (key == 't') { thread_mutex.lock(); run_step = !run_step; printf("run_step = %d\n", run_step); thread_mutex.unlock(); } } static void special(int key, int x, int y) { } static void mouse(int button, int state, int x, int y) { if (state == GLUT_UP) return; Point p = {x, y}; points[p] = {(button == GLUT_LEFT_BUTTON ? 1.0f : 0.0f), (button == GLUT_RIGHT_BUTTON ? 1.0f : 0.0f)}; pvector.push_back(*points.find(p)); thread_mutex.lock(); classifier->initialize(points, pvector); thread_mutex.unlock(); } int main(int argc, char **argv) { using namespace std; const auto &classifiers = getClassifiers(); if (classifiers.size() == 0) { cerr << "No Classifier compiled" << endl; return 1; } int idx = -1; std::vector<Classifier *> cvec; cout << "Supported Classifiers:" << endl; for (const auto &c : classifiers) { cout << cvec.size() << "\t: " << c.first << endl; cvec.push_back(c.second); } cout << "Select Classfier: "; while (idx < 0 || idx > classifiers.size()) { cin >> idx; } classifier = cvec[idx]; std::thread step_thread([]() { int cnt = 0; using std::this_thread::sleep_for; using std::chrono::milliseconds; while (true) { if (++cnt > 5000) { sleep_for(milliseconds(100)); cnt = 0; } thread_mutex.lock(); if (!run_step) { thread_mutex.unlock(); continue; } classifier->step(); thread_mutex.unlock(); } }); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutCreateWindow("spvis"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutSpecialFunc(special); glutMouseFunc(mouse); glutIdleFunc(display); glClearColor(0.0, 0.0, 0.0, 1.0); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "Pythia8/Pythia.h" using Pythia8::Pythia; using Pythia8::Hist; int main() { Pythia pythia; pythia.readString("Beams:eCM = 13000."); pythia.readString("SoftQCD:all = on"); pythia.readString("PhaseSpace:pTHatMin = 200."); pythia.init(); Hist mult("charged multiplicity", 100, -0.5, 799.5); for (int iEvent = 0; iEvent < 1; ++iEvent) { if (!pythia.next()) continue; int nCharged = 0; for (int i = 0; i < pythia.event.size(); ++i) { if (pythia.event[i].isFinal() && pythia.event[i].isHadron()) { std::cout << pythia.event[i].pT() << std::endl; } } } pythia.stat(); return 0; } <commit_msg>write pt/pz<commit_after>#include <iostream> #include "Pythia8/Pythia.h" using Pythia8::Pythia; int main() { Pythia pythia; pythia.readString("Beams:eCM = 14000."); pythia.readString("SoftQCD:all = on"); pythia.init(); for (int iEvent = 0; iEvent < 1; ++iEvent) { if (!pythia.next()) continue; std::cerr << pythia.event.size() << std::endl; for (int i = 0; i < pythia.event.size(); i++) { if (pythia.event[i].isFinal() && pythia.event[i].isHadron()) { // Maybe we should reject too High pz, otherwise it would be the end-cap region std::cerr << pythia.event[i].pT() << "," << pythia.event[i].pz() << std::endl; } } // We need information for the number of the jets in one vertex, maybe std::cerr << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "./problems/problem1.h" #include "time.h" using namespace std; int main () { clock_t start, end; printf("\nPROJECT EULER SOLUTIONS\n"); printf("===========================\n\n"); start = clock(); problem1BruteForce(); end = clock(); printf(" [duration = %i ticks]\n\n", end - start); start = clock(); problem1Multiples(); end = clock(); printf(" [duration = %i ticks]\n\n", end - start); printf("===========================\n\n"); return 0; } <commit_msg>- remove warnings<commit_after>#include <iostream> #include "./problems/problem1.h" #include "time.h" using namespace std; int main () { clock_t start, end; printf("\nPROJECT EULER SOLUTIONS\n"); printf("===========================\n\n"); start = clock(); problem1BruteForce(); end = clock(); printf(" [duration = %lu ticks]\n\n", end - start); start = clock(); problem1Multiples(); end = clock(); printf(" [duration = %lu ticks]\n\n", end - start); printf("===========================\n\n"); return 0; } <|endoftext|>
<commit_before>/** * Path manipulation utilities */ #include "path.h" #include <string> #include <sys/stat.h> #include <sys/types.h> #include <limits.h> #include <stdlib.h> #ifdef windows # include <io.h> # define realpath(in, out) _fullpath(out, in, PATH_MAX) #endif /** * Normalize path by removing "./", "../" and resolving symlinks */ std::string path_normalize(std::string path) { char * p = new char[PATH_MAX]; realpath(path.c_str(), p); std::string result(p); delete[] p; return result; /* std::string result = path; size_t pos = 0; int state = 1; // 0 bad, 1 just after dirname, 2 dot while (pos != result.length()) { char ch = result.at(pos); switch (ch) { case '/': case '\\': if (state == 0) { state = 1; } if (state == 2) { pos -= 1; result.erase(pos, 2); } break; case '.': if (state == 1) { state = 2; } else { state = 0; } break; default: state = 0; break; } pos++; } return result; */ } /** * Return file name component of path */ std::string path_filename(std::string path) { size_t pos = path_lastslash(path); if (pos != std::string::npos) { path.erase(0, pos+1); } return path; } /** * Return directory name component of path */ std::string path_dirname(std::string path) { size_t pos = path_lastslash(path); if (pos != std::string::npos) { path.erase(pos, path.length()-pos); } return path; } /** * Return index of last slash (normal or backslash) in a path */ size_t path_lastslash(std::string path) { size_t pos = path.find_last_of('/'); if (pos == std::string::npos) { pos = path.find_last_of('\\'); } return pos; } /** * Is this path absolute? */ bool path_isabsolute(std::string path) { #ifdef windows size_t pos = path.find(':'); return (pos != std::string::npos); #else if (path.length() == 0) { return false; } return (path.at(0) == '/'); #endif } /** * Does a file exist at this path? */ bool path_file_exists(std::string path) { struct stat st; if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */ if (st.st_mode & S_IFDIR) { return false; } /* is directory */ return true; } /** * Does a directory exist at this path? */ bool path_dir_exists(std::string path) { struct stat st; if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */ if (st.st_mode & S_IFDIR) { return true; } /* is directory */ return false; } /** * Get current working directory */ std::string path_getcwd() { return getcwd(NULL, 0); } /** * Change current directory */ void path_chdir(std::string dir) { #ifdef VERBOSE printf("[path_chdir] chdir to '%s'\n", dir.c_str()); #endif chdir(dir.c_str()); } <commit_msg>memory leak fix<commit_after>/** * Path manipulation utilities */ #include "path.h" #include <string> #include <sys/stat.h> #include <sys/types.h> #include <limits.h> #include <stdlib.h> #ifdef windows # include <io.h> # define realpath(in, out) _fullpath(out, in, PATH_MAX) #endif /** * Normalize path by removing "./", "../" and resolving symlinks */ std::string path_normalize(std::string path) { char * p = new char[PATH_MAX]; realpath(path.c_str(), p); std::string result(p); delete[] p; return result; /* std::string result = path; size_t pos = 0; int state = 1; // 0 bad, 1 just after dirname, 2 dot while (pos != result.length()) { char ch = result.at(pos); switch (ch) { case '/': case '\\': if (state == 0) { state = 1; } if (state == 2) { pos -= 1; result.erase(pos, 2); } break; case '.': if (state == 1) { state = 2; } else { state = 0; } break; default: state = 0; break; } pos++; } return result; */ } /** * Return file name component of path */ std::string path_filename(std::string path) { size_t pos = path_lastslash(path); if (pos != std::string::npos) { path.erase(0, pos+1); } return path; } /** * Return directory name component of path */ std::string path_dirname(std::string path) { size_t pos = path_lastslash(path); if (pos != std::string::npos) { path.erase(pos, path.length()-pos); } return path; } /** * Return index of last slash (normal or backslash) in a path */ size_t path_lastslash(std::string path) { size_t pos = path.find_last_of('/'); if (pos == std::string::npos) { pos = path.find_last_of('\\'); } return pos; } /** * Is this path absolute? */ bool path_isabsolute(std::string path) { #ifdef windows size_t pos = path.find(':'); return (pos != std::string::npos); #else if (path.length() == 0) { return false; } return (path.at(0) == '/'); #endif } /** * Does a file exist at this path? */ bool path_file_exists(std::string path) { struct stat st; if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */ if (st.st_mode & S_IFDIR) { return false; } /* is directory */ return true; } /** * Does a directory exist at this path? */ bool path_dir_exists(std::string path) { struct stat st; if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */ if (st.st_mode & S_IFDIR) { return true; } /* is directory */ return false; } /** * Get current working directory */ std::string path_getcwd() { char * buf = getcwd(NULL, 0); std::string result(buf); free(buf); return result; } /** * Change current directory */ void path_chdir(std::string dir) { #ifdef VERBOSE printf("[path_chdir] chdir to '%s'\n", dir.c_str()); #endif chdir(dir.c_str()); } <|endoftext|>
<commit_before>/// /// @file phi.cpp /// /// Copyright (C) 2013 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "pi_bsearch.h" #include "imath.h" #include <primesieve/soe/PrimeSieve.h> #include <stdint.h> #include <vector> #include <limits> #include <cstddef> #ifdef _OPENMP #include <omp.h> #include "to_omp_threads.h" #endif /// Keep the cache size below CACHE_BYTES_LIMIT per thread #define CACHE_BYTES_LIMIT (16 << 20) /// Cache phi(x, a) results if a <= CACHE_A_LIMIT #define CACHE_A_LIMIT 500 /// Avoid slow 64-bit division if possible #define FAST_DIV(x, y) ((x <= std::numeric_limits<uint32_t>::max()) \ ? static_cast<uint32_t>(x) / (y) : (x) / (y)) namespace primecount { /// This class is used to calculate phi(x, a) using the recursive /// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1). /// This implementation is based on an algorithm from Tomas Oliveira e /// Silva [1]. I have added a cache to my implementation in which /// results of phi(x, a) are stored if x < 2^16 and a <= 500. /// The cache speeds up the calculations by at least 3 orders of /// magnitude near 10^15. /// /// [1] Tomas Oliveira e Silva, "Computing pi(x): the combinatorial method", /// Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006 /// class PhiCache { public: PhiCache(const std::vector<int32_t>& primes) : primes_(primes), bytes_(0) { std::size_t max_size = CACHE_A_LIMIT + 1; cache_.resize(std::min(primes.size(), max_size)); } int64_t phi_bsearch(int64_t x, int64_t a) { int64_t pi = pi_bsearch(primes_.begin(), primes_.end(), x); return pi - a + 1; } template<int64_t SIGN> int64_t phi(int64_t x, int64_t a) { int64_t sum = x * SIGN; if (a > 0) { int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x)); sum += (a - iters) * -SIGN; for (int64_t a2 = 0; a2 < iters; a2++) { // x2 = x / primes_[a2] int64_t x2 = FAST_DIV(x, primes_[a2]); int64_t phi_result; if (validate(a2, x2) && cache_[a2][x2] != 0) phi_result = cache_[a2][x2] * -SIGN; else { if (x2 <= primes_.back() && x2 < isquare(primes_[a2])) phi_result = phi_bsearch(x2, a2) * -SIGN; else phi_result = phi<-SIGN>(x2, a2); if (validate(a2, x2)) cache_[a2][x2] = static_cast<uint16_t>(phi_result * -SIGN); } sum += phi_result; } } return sum; } private: /// Cache for phi(x, a) results std::vector<std::vector<uint16_t> > cache_; const std::vector<int32_t>& primes_; int64_t bytes_; bool validate(int64_t a2, int64_t x2) { if (a2 > CACHE_A_LIMIT || x2 > std::numeric_limits<uint16_t>::max()) return false; // resize and initialize cache if necessary if (x2 >= static_cast<int64_t>(cache_[a2].size())) { if (bytes_ > CACHE_BYTES_LIMIT) return false; bytes_ += (x2 + 1 - cache_[a2].size()) * 2; cache_[a2].resize(x2 + 1, 0); } return true; } }; /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a, int threads) { if (x < 1) return 0; if (a > x) return 1; if (a < 1) return x; std::vector<int32_t> primes; PrimeSieve ps; ps.generate_N_Primes(a, &primes); if (primes.back() >= x) return 1; int iters = pi_bsearch(primes.begin(), primes.end(), isqrt(x)); PhiCache cache(primes); int64_t sum = x - a + iters; #ifdef _OPENMP threads = to_omp_threads(threads); #pragma omp parallel for firstprivate(cache) reduction(+: sum) \ num_threads(threads) schedule(dynamic, 16) #endif for (int64_t a2 = 0; a2 < iters; a2++) sum += cache.phi<-1>(x / primes[a2], a2); return sum; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file phi.cpp /// /// Copyright (C) 2013 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "pi_bsearch.h" #include "imath.h" #include <primesieve/soe/PrimeSieve.h> #include <stdint.h> #include <vector> #include <limits> #include <cstddef> #ifdef _OPENMP #include <omp.h> #include "to_omp_threads.h" #endif /// Keep the cache size below CACHE_BYTES_LIMIT per thread #define CACHE_BYTES_LIMIT (16 << 20) /// Cache phi(x, a) results if a <= CACHE_A_LIMIT #define CACHE_A_LIMIT 500 /// Avoid slow 64-bit division if possible #define FAST_DIV(x, y) ((x <= std::numeric_limits<uint32_t>::max()) \ ? static_cast<uint32_t>(x) / (y) : (x) / (y)) namespace primecount { /// This class is used to calculate phi(x, a) using the recursive /// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1). /// This implementation is based on an algorithm from Tomas Oliveira e /// Silva [1]. I have added a cache to my implementation in which /// results of phi(x, a) are stored if x < 2^16 and a <= 500. /// The cache speeds up the calculations by at least 3 orders of /// magnitude near 10^15. /// /// [1] Tomas Oliveira e Silva, "Computing pi(x): the combinatorial method", /// Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006 /// class PhiCache { public: PhiCache(const std::vector<int32_t>& primes) : primes_(primes), bytes_(0) { std::size_t max_size = CACHE_A_LIMIT + 1; cache_.resize(std::min(primes.size(), max_size)); } int64_t phi_bsearch(int64_t x, int64_t a) { int64_t pix = pi_bsearch(primes_.begin(), primes_.end(), x); return pix - a + 1; } template<int64_t SIGN> int64_t phi(int64_t x, int64_t a) { int64_t sum = x * SIGN; if (a > 0) { int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x)); sum += (a - iters) * -SIGN; for (int64_t a2 = 0; a2 < iters; a2++) { // x2 = x / primes_[a2] int64_t x2 = FAST_DIV(x, primes_[a2]); int64_t phi_result; if (validate(a2, x2) && cache_[a2][x2] != 0) phi_result = cache_[a2][x2] * -SIGN; else { if (x2 <= primes_.back() && x2 < isquare(primes_[a2])) phi_result = phi_bsearch(x2, a2) * -SIGN; else phi_result = phi<-SIGN>(x2, a2); if (validate(a2, x2)) cache_[a2][x2] = static_cast<uint16_t>(phi_result * -SIGN); } sum += phi_result; } } return sum; } private: /// Cache for phi(x, a) results std::vector<std::vector<uint16_t> > cache_; const std::vector<int32_t>& primes_; int64_t bytes_; bool validate(int64_t a2, int64_t x2) { if (a2 > CACHE_A_LIMIT || x2 > std::numeric_limits<uint16_t>::max()) return false; // resize and initialize cache if necessary if (x2 >= static_cast<int64_t>(cache_[a2].size())) { if (bytes_ > CACHE_BYTES_LIMIT) return false; bytes_ += (x2 + 1 - cache_[a2].size()) * 2; cache_[a2].resize(x2 + 1, 0); } return true; } }; /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a, int threads) { if (x < 1) return 0; if (a > x) return 1; if (a < 1) return x; std::vector<int32_t> primes; PrimeSieve ps; ps.generate_N_Primes(a, &primes); if (primes.back() >= x) return 1; int iters = pi_bsearch(primes.begin(), primes.end(), isqrt(x)); PhiCache cache(primes); int64_t sum = x - a + iters; #ifdef _OPENMP threads = to_omp_threads(threads); #pragma omp parallel for firstprivate(cache) reduction(+: sum) \ num_threads(threads) schedule(dynamic, 16) #endif for (int64_t a2 = 0; a2 < iters; a2++) sum += cache.phi<-1>(x / primes[a2], a2); return sum; } } // namespace primecount <|endoftext|>