text
stringlengths
500
20k
source
stringclasses
27 values
lang
stringclasses
3 values
char_count
int64
500
20k
word_count
int64
4
19.8k
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bibecoin-config.h" #endif #include "bitcoingui.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "net.h" #include "networkstyle.h" #include "optionsmodel.h" #include "splashscreen.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "init.h" #include "main.h" #include "rpcserver.h" #include "scheduler.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <stdint.h> #include <boost/filesystem/operations.hpp> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif #if QT_VERSION < 0x050000 #include <QTextCodec> #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bibecoin-core", psz).toStdString(); } static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if (!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator& qtTranslatorBase, QTranslator& qtTranslator, QTranslator& translatorBase, QTranslator& translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bibecoin.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bibecoin.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char* msg) { const char* category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context); const char* category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif /** Class encapsulating BibeCoin Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore : public QObject { Q_OBJECT public: explicit BitcoinCore(); public slots: void initialize(); void shutdown(); void restart(QStringList args); signals: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString& message); private: boost::thread_group threadGroup; CScheduler scheduler; /// Flag indicating a restart bool execute_restart; /// Pass fatal exception message to UI thread void handleRunawayException(std::exception* e); }; /** Main BibeCoin application object */ class BitcoinApplication : public QApplication { Q_OBJECT public: explicit BitcoinApplication(int& argc, char** argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// Create options model void createOptionsModel(); /// Create main window void createWindow(const NetworkStyle* networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle* networkStyle); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (BitcoinGUI) WId getMainWinId() const; public slots: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString& message); signals: void requestedInitialize(); void requestedRestart(QStringList args); void requestedShutdown(); void stopThread(); void splashFinished(QWidget* window); private: QThread* coreThread; OptionsModel* optionsModel; ClientModel* clientModel; BitcoinGUI* window; QTimer* pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel* walletModel; #endif int returnValue; void startThread(); }; #include "bibecoin.moc" BitcoinCore::BitcoinCore() : QObject() { } void BitcoinCore::handleRunawayException(std::exception* e) { PrintExceptionContinue(e, "Runaway exception"); emit runawayException(QString::fromStdString(strMiscWarning)); } void BitcoinCore::initialize() { execute_restart = true; try { qDebug() << __func__ << ": Running AppInit2 in thread"; int rv = AppInit2(threadGroup, scheduler); emit initializeResult(rv); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::restart(QStringList args) { if (execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button execute_restart = false; try { qDebug() << __func__ << ": Running Restart in thread"; Interrupt(threadGroup); threadGroup.join_all(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; emit shutdownResult(1); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; QApplication::quit(); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; Interrupt(threadGroup); threadGroup.join_all(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; emit shutdownResult(1); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int& argc, char** argv) : QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); } BitcoinApplication::~BitcoinApplication() { if (coreThread) { qDebug() << __func__ << ": Stopping thread"; emit stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif // Delete Qt-settings if user clicked on "Reset Options" QSettings settings; if (optionsModel && optionsModel->resetSettings) { settings.clear(); settings.sync(); } delete optionsModel; optionsModel = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel() { optionsModel = new OptionsModel(); } void BitcoinApplication::createWindow(const NetworkStyle* networkStyle) { window = new BitcoinGUI(networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown())); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle* networkStyle) { SplashScreen* splash = new SplashScreen(0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*))); } void BitcoinApplication::startThread() { if (coreThread) return; coreThread = new QThread(this); BitcoinCore* executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int))); connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int))); connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString))); connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize())); connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown())); connect(window, SIGNAL(requestedRestart(QStringList)), executor, SLOT(restart(QStringList))); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit())); coreThread->start(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); emit requestedInitialize(); } void BitcoinApplication::requestShutdown() { qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; // Show a simple window indicating shutdown status ShutdownWindow::showShutdownWindow(window); // Request shutdown from core thread emit requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if (retval) { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if (pwalletMain) { walletModel = new WalletModel(pwalletMain, optionsModel); window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET); connect(walletModel, SIGNAL(coinsSent(CWallet*, SendCoinsRecipient, QByteArray)), paymentServer, SLOT(fetchPaymentACK(CWallet*, const SendCoinsRecipient&, QByteArray))); } #endif // If -min option passed, start window minimized. if (GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } emit splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // BibeCoin: URIs or payment requests: connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), window, SLOT(handlePaymentRequest(SendCoinsRecipient))); connect(window, SIGNAL(receivedURI(QString)), paymentServer, SLOT(handleURIOrFile(QString))); connect(paymentServer, SIGNAL(message(QString, QString, unsigned int)), window, SLOT(message(QString, QString, unsigned int))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString& message) { QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. BibeCoin can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(1); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char* argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bibecoin_locale); Q_INIT_RESOURCE(bibecoin); BitcoinApplication app(argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType<bool*>(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType<CAmount>("CAmount"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { HelpMessageDialog help(NULL, mapArgs.count("-version")); help.showOrPrint(); return 1; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory()) return 0; /// 6. Determine availability of data directory and parse bibecoin.conf /// - Do not call GetDataDir(true) before this step finishes if (!boost::filesystem::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("BibeCoin Core"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (std::exception& e) { QMessageBox::critical(0, QObject::tr("BibeCoin Core"), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return 0; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { QMessageBox::critical(0, QObject::tr("BibeCoin Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); return 1; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing applicati
c++
code
20,000
3,893
// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #include "decoder.h" #include "../TestDevVideoPlayTestData.h" _LIT(KDevVideoDecoderPanicCategory, "DevVideoDecoder"); void DevVideoDecoderPanic(TInt aReason) { User::Panic(KDevVideoDecoderPanicCategory, aReason); } CMMFVideoDecodeHwDevice* CMMFTestVideoDecodeHwDevice::NewL(TAny* /*aInitParams*/) { CMMFTestVideoDecodeHwDevice* s = new(ELeave) CMMFTestVideoDecodeHwDevice; return (STATIC_CAST(CMMFVideoDecodeHwDevice*, s)); } CMMFTestVideoDecodeHwDevice::CMMFTestVideoDecodeHwDevice() :iExtensionUid(KUidDevVideoPlayHwDeviceExtensionScanCopy) { } CMMFTestVideoDecodeHwDevice::~CMMFTestVideoDecodeHwDevice() { // destroy objects in RArray for (TInt i = 0; i < iVidFormats.Count(); i++) { delete iVidFormats[i]; } iVidFormats.Reset(); iVidFormats.Close(); iPictureRates.Reset(); iPictureRates.Close(); iCombinations.Reset(); iCombinations.Close(); iPostProcVidFormats.Reset(); iPostProcVidFormats.Close(); iScaleFactors.Reset(); iScaleFactors.Close(); delete iBufferDataArea; } TAny* CMMFTestVideoDecodeHwDevice::CustomInterface(TUid aInterface) { if (aInterface == KUidCustomInterfaceOne) { return this;//just want to return something non-null! } else if (aInterface == iExtensionUid) { return static_cast<MMMFVideoPlayHwDeviceExtensionScanCopy*>(this); } else { return NULL; } } // post processor info may be obtained from this plugin or the post processor plugin CPostProcessorInfo* CMMFTestVideoDecodeHwDevice::PostProcessorInfoLC() { // construct array of test types for (TUint i = 0; i < KTestPostProcInfoCount; i++) { // append the video formats TUncompressedVideoFormat vid = KTestPostProcInfoFormatArray[i]; User::LeaveIfError(iPostProcVidFormats.Append(vid)); // append the combinations TUint32 comb = KTestPostProcInfoCombsArray[i]; User::LeaveIfError(iCombinations.Append(comb)); // append the scale factors TScaleFactor scale = KTestPostProcInfoScaleFactorsArray[i]; User::LeaveIfError(iScaleFactors.Append(scale)); } // construct the video decoder info object CPostProcessorInfo* info = CPostProcessorInfo::NewL( KUidDevVideoTestDecodeHwDevice, KTestPostProcInfoManufacturer, KTestPostProcInfoIdentifier, TVersion(KTestPostProcInfoVersionMaj, KTestPostProcInfoVersionMin, KTestPostProcInfoVersionBuild), iPostProcVidFormats.Array(), iCombinations.Array(), ETrue, // accelerated ETrue, // direct display support KTestPostProcInfoYuvToRgbCaps, KTestPostProcInfoRotations, ETrue, // scaling iScaleFactors.Array(), ETrue, // anti-aliasing KTestDecoderInfoISInfo ); CleanupStack::PushL(info); return info; } void CMMFTestVideoDecodeHwDevice::GetOutputFormatListL(RArray<TUncompressedVideoFormat>& aFormats) { // append in order 1, 2, 3 User::LeaveIfError(aFormats.Append(KTestVidFormat1)); User::LeaveIfError(aFormats.Append(KTestVidFormat2)); User::LeaveIfError(aFormats.Append(KTestVidFormat3)); } void CMMFTestVideoDecodeHwDevice::SetOutputFormatL(const TUncompressedVideoFormat &aFormat) { if (!(aFormat == KTestVidFormat1)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetPostProcessTypesL(TUint32 aPostProcCombination) { if (!(aPostProcCombination == KTestProcessType1)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetInputCropOptionsL(const TRect& aRect) { TRect testRect(KTestInputCropRectA, KTestInputCropRectB, KTestInputCropRectC, KTestInputCropRectD); if (!(aRect == testRect)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetYuvToRgbOptionsL(const TYuvToRgbOptions& aOptions, const TYuvFormat& aYuvFormat, TRgbFormat aRgbFormat) { // check options first if (!CompareYuvRgbOptions(aOptions, KTestYuvToRgb1)) User::Leave(KErrCorrupt); // now check formats if ( !(CompareYuvFormats(aYuvFormat, KTestYuvFormat1)) || !(aRgbFormat == KTestRgbFormat1) ) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetYuvToRgbOptionsL(const TYuvToRgbOptions& aOptions) { if (!CompareYuvRgbOptions(aOptions, KTestYuvToRgb1)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetRotateOptionsL(TRotationType aRotationType) { if (!(aRotationType == KTestRotate1)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetScaleOptionsL(const TSize& aTargetSize, TBool aAntiAliasFiltering) { TSize testScale(KTestScaleX, KTestScaleY); if (!(aTargetSize == testScale) || !aAntiAliasFiltering) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetOutputCropOptionsL(const TRect& aRect) { TRect testRect(KTestOutputCropRectA, KTestOutputCropRectB, KTestOutputCropRectC, KTestOutputCropRectD); if (!(aRect == testRect)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetPostProcSpecificOptionsL(const TDesC8& aOptions) { if (!(aOptions == KTestPostProcOptions1)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::SetClockSource(MMMFClockSource* aClock) { __ASSERT_ALWAYS(aClock, DevVideoDecoderPanic(EDecoderPanicClockSource)); // call Time() to check that clock can be used TTimeIntervalMicroSeconds currTime(0); // done this way to remove compiler warning currTime = aClock->Time(); } void CMMFTestVideoDecodeHwDevice::SetVideoDestScreenL(TBool /*aScreen*/) { } void CMMFTestVideoDecodeHwDevice::Initialize() { iProxy->MdvppInitializeComplete(this, KErrNone); } void CMMFTestVideoDecodeHwDevice::StartDirectScreenAccessL(const TRect& aVideoRect, CFbsScreenDevice& /*aScreenDevice*/, const TRegion& aClipRegion) { TRect dsaRect(KTestDSARectA, KTestDSARectB, KTestDSARectC, KTestDSARectD); TRegionFix<1> dsaReg(dsaRect); // probably no need to check aScreenDevice if ( /*!(&aScreenDevice) || */!(dsaRect == aVideoRect) || !(dsaReg.BoundingRect() == aClipRegion.BoundingRect()) ) User::Leave(KErrNotSupported); } void CMMFTestVideoDecodeHwDevice::SetScreenClipRegion(const TRegion& aRegion) { TRect dsaRect(KTestDSARectA, KTestDSARectB, KTestDSARectC, KTestDSARectD); TRegionFix<1> dsaReg(dsaRect); __ASSERT_ALWAYS(dsaReg.BoundingRect() == aRegion.BoundingRect(), DevVideoDecoderPanic(EDecoderPanicScreenClipRegion)); } void CMMFTestVideoDecodeHwDevice::SetPauseOnClipFail(TBool aPause) { __ASSERT_ALWAYS(aPause, DevVideoDecoderPanic(EDecoderPanicPauseClipFail)); } void CMMFTestVideoDecodeHwDevice::AbortDirectScreenAccess() { // do something here? } TBool CMMFTestVideoDecodeHwDevice::IsPlaying() { return iIsPlaying; } void CMMFTestVideoDecodeHwDevice::Redraw() { // do something here? } void CMMFTestVideoDecodeHwDevice::Start() { iIsPlaying = ETrue; } void CMMFTestVideoDecodeHwDevice::Stop() { iIsPlaying = EFalse; } void CMMFTestVideoDecodeHwDevice::Pause() { iIsPlaying = EFalse; } void CMMFTestVideoDecodeHwDevice::Resume() { iIsPlaying = ETrue; } void CMMFTestVideoDecodeHwDevice::SetPosition(const TTimeIntervalMicroSeconds& aPlaybackPosition) { if (aPlaybackPosition == TTimeIntervalMicroSeconds(KTestPositionFatal)) { iProxy->MdvppFatalError(this, KErrDied); } else { __ASSERT_ALWAYS(aPlaybackPosition == TTimeIntervalMicroSeconds(KTestPosition), DevVideoDecoderPanic(EDecoderPanicSetPosition)); } } void CMMFTestVideoDecodeHwDevice::FreezePicture(const TTimeIntervalMicroSeconds& aTimestamp) { __ASSERT_ALWAYS(aTimestamp == TTimeIntervalMicroSeconds(KTestPosition), DevVideoDecoderPanic(EDecoderPanicFreezePicture)); } void CMMFTestVideoDecodeHwDevice::ReleaseFreeze(const TTimeIntervalMicroSeconds& aTimestamp) { __ASSERT_ALWAYS(aTimestamp == TTimeIntervalMicroSeconds(KTestPosition), DevVideoDecoderPanic(EDecoderPanicReleaseFreeze)); } TTimeIntervalMicroSeconds CMMFTestVideoDecodeHwDevice::PlaybackPosition() { return TTimeIntervalMicroSeconds(KTestPlayPosition); } TUint CMMFTestVideoDecodeHwDevice::PictureBufferBytes() { return KTestPictureBytes; } void CMMFTestVideoDecodeHwDevice::GetPictureCounters(CMMFDevVideoPlay::TPictureCounters& aCounters) { aCounters = GetTestPictureCounters(); } void CMMFTestVideoDecodeHwDevice::SetComplexityLevel(TUint aLevel) { __ASSERT_ALWAYS(aLevel == KTestComplexityLevel1, DevVideoDecoderPanic(EDecoderPanicComplexityLevel)); } TUint CMMFTestVideoDecodeHwDevice::NumComplexityLevels() { return KTestNumComplexityLevels1; } void CMMFTestVideoDecodeHwDevice::GetComplexityLevelInfo(TUint aLevel, CMMFDevVideoPlay::TComplexityLevelInfo& aInfo) { __ASSERT_ALWAYS(aLevel == KTestComplexityLevel1, DevVideoDecoderPanic(EDecoderPanicComplexityLevelInfo)); aInfo = GetTestLevelInfo(aLevel); } void CMMFTestVideoDecodeHwDevice::ReturnPicture(TVideoPicture* /*aPicture*/) { } TBool CMMFTestVideoDecodeHwDevice::GetSnapshotL(TPictureData& /*aPictureData*/, const TUncompressedVideoFormat& /*aFormat*/) { return EFalse; } // this method should be called on the post processor not on the decoder // ending up here is a programming error and hence a PANIC condition void CMMFTestVideoDecodeHwDevice::GetTimedSnapshotL(TPictureData* /*aPictureData*/, const TUncompressedVideoFormat& /*aFormat*/, const TTimeIntervalMicroSeconds& /*aPresentationTimestamp*/) { DevVideoDecoderPanic(EDecoderPanicTimedSnapshot); } // this method should be called on the post processor not on the decoder // ending up here is a programming error and hence a PANIC condition void CMMFTestVideoDecodeHwDevice::GetTimedSnapshotL(TPictureData* /*aPictureData*/, const TUncompressedVideoFormat& /*aFormat*/, const TPictureId& /*aPictureId*/) { DevVideoDecoderPanic(EDecoderPanicTimedSnapshotId); } // this method should be called on the post processor not on the decoder // ending up here is a programming error and hence a PANIC condition void CMMFTestVideoDecodeHwDevice::CancelTimedSnapshot() { DevVideoDecoderPanic(EDecoderPanicCancelTimedSnapshot); } // this method should be called on the post processor not on the decoder // ending up here is a programming error and hence a PANIC condition void CMMFTestVideoDecodeHwDevice::GetSupportedSnapshotFormatsL(RArray<TUncompressedVideoFormat>& /*aFormats*/) { DevVideoDecoderPanic(EDecoderPanicSupportedSnapshotFormats); } void CMMFTestVideoDecodeHwDevice::InputEnd() { iProxy->MdvppStreamEnd(); } CVideoDecoderInfo* CMMFTestVideoDecodeHwDevice::VideoDecoderInfoLC() { // construct array of test types for (TUint i = 0; i < KTestDecoderInfoCount; i++) { // construct the video types for iVidTypes CCompressedVideoFormat* vid = NULL; TPtrC8 mimeType = KTestDecoderInfoMimeArray[i]; vid = GetTestCVFormatL(mimeType); CleanupStack::PushL(vid); User::LeaveIfError(iVidFormats.Append(vid)); CleanupStack::Pop(vid); // CCompressedVideo object is destroyed in destructor // append the max picture rates TPictureRateAndSize rate; GetTestEncoderInfoRate(i, rate); User::LeaveIfError(iPictureRates.Append(rate)); } // construct the video decoder info object CVideoDecoderInfo* vInfo = CVideoDecoderInfo::NewL( KUidDevVideoTestDecodeHwDevice, KTestDecoderInfoManufacturer, KTestDecoderInfoIdentifier, TVersion(KTestDecoderInfoVersionMaj, KTestDecoderInfoVersionMin, KTestDecoderInfoVersionBuild), iVidFormats.Array(), ETrue, // accelerated ETrue, // supports direct display TSize(KTestDecoderInfoMaxSizeX,KTestDecoderInfoMaxSizeY), KMaxTUint, //aMaxBitrate iPictureRates.Array(), ETrue, // aSupportsPictureLoss EFalse, // aSupportsSliceLoss KTestDecoderInfoCSInfo, KTestDecoderInfoISInfo ); CleanupStack::PushL(vInfo); #ifdef SYMBIAN_ENABLE_MMF_MULTISCREEN_SUPPORT vInfo->AddSupportedScreenL(KDecoderDefaultScreenNumber); vInfo->AddSupportedScreenL(KDecoderSecondaryScreenNumber); #endif vInfo->SetSupportsContentProtected(ETrue); return vInfo; } TVideoPictureHeader* CMMFTestVideoDecodeHwDevice::GetHeaderInformationL(TVideoDataUnitType aDataUnitType, TVideoDataUnitEncapsulation aEncapsulation, TVideoInputBuffer* aDataUnit) { // check KTestDataUnitType, KTestDataUnitEncap if ((aDataUnitType != KTestDataUnitType) || (aEncapsulation != KTestDataUnitEncap) || (aDataUnit->iOptions != KTestInputBufferOptions) ) { User::Leave(KErrCorrupt); } // repackage picture header iPictureHeader.iOptions = KTestPictureHeaderOptions; iPictureHeader.iPresentationTimestamp = aDataUnit->iPresentationTimestamp; iPictureHeader.iOptional = &(aDataUnit->iData); return &iPictureHeader; } void CMMFTestVideoDecodeHwDevice::ConfigureDecoderL(const TVideoPictureHeader& aVideoPictureHeader) { TTimeIntervalMicroSeconds testTime(KTestInputBufferTimestamp); // check the picture header if ( (aVideoPictureHeader.iOptions != KTestPictureHeaderOptions) ||(!(aVideoPictureHeader.iPresentationTimestamp == testTime)) ||(!(*(aVideoPictureHeader.iOptional) == KTestInputBufferData()))) { User::Leave(KErrCorrupt); } iPictureHeader = aVideoPictureHeader; } void CMMFTestVideoDecodeHwDevice::ReturnHeader(TVideoPictureHeader* aHeader) { __ASSERT_ALWAYS(aHeader, DevVideoDecoderPanic(EDecoderPanicPictureHeader)); __ASSERT_ALWAYS(aHeader->iOptions == KTestPictureHeaderOptions, DevVideoDecoderPanic(EDecoderPanicPictureHeaderOptions)); __ASSERT_ALWAYS(aHeader->iPresentationTimestamp == TTimeIntervalMicroSeconds(KTestPictureHeaderTimestamp), DevVideoDecoderPanic(EDecoderPanicPictureHeaderTimestamp)); } void CMMFTestVideoDecodeHwDevice::SetInputFormatL(const CCompressedVideoFormat& aFormat, TVideoDataUnitType aDataUnitType, TVideoDataUnitEncapsulation aEncapsulation, TBool aDataInOrder) { // check expected parameters - TClasses first if (!((aDataUnitType == KTestUnitType1) && (aEncapsulation == KTestEncapType1) && (aDataInOrder))) User::Leave(KErrCorrupt); // construct a temporary compressed video class [will leave on error] CCompressedVideoFormat *compVideo = GetTestCVFormatL(KTestMimeType1); CleanupStack::PushL(compVideo); // compare to received class if (!(aFormat == *compVideo)) User::Leave(KErrCorrupt); // destroy temporary class CleanupStack::PopAndDestroy(compVideo); } void CMMFTestVideoDecodeHwDevice::SynchronizeDecoding(TBool aSynchronize) { __ASSERT_ALWAYS(aSynchronize, DevVideoDecoderPanic(EDecoderPanicSynchronizeDecoding)); } void CMMFTestVideoDecodeHwDevice::SetBufferOptionsL(const CMMFDevVideoPlay::TBufferOptions& aOptions) { CMMFDevVideoPlay::TBufferOptions buffOptions = GetTestBufferOptions(); if (!CompareBufferOptions(aOptions, buffOptions)) User::Leave(KErrCorrupt); } void CMMFTestVideoDecodeHwDevice::GetBufferOptions(CMMFDevVideoPlay::TBufferOptions& aOptions) { aOptions = GetTestBufferOptions(); } void CMMFTestVideoDecodeHwDevice::SetHrdVbvSpec(THrdVbvSpecification aHrdVbvSpec, const TDesC8& aHrdVbvParams) { __ASSERT_ALWAYS(aHrdVbvSpec == KTestHrdVbvSpec, DevVideoDecoderPanic(EDecoderPanicHrdVbvSpec)); __ASSERT_ALWAYS(aHrdVbvParams == KTestHrdVbvParams, DevVideoDecoderPanic(EDecoderPanicHrdVbvParams)); } void CMMFTestVideoDecodeHwDevice::SetOutputDevice(CMMFVideoPostProcHwDevice* /*aDevice*/) { } TTimeIntervalMicroSeconds CMMFTestVideoDecodeHwDevice::DecodingPosition() { return TTimeIntervalMicroSeconds(KTestDecodePosition); } TUint CMMFTestVideoDecodeHwDevice::PreDecoderBufferBytes() { return KTestPreDecoderBytes; } void CMMFTestVideoDecodeHwDevice::GetBitstreamCounters(CMMFDevVideoPlay::TBitstreamCounters& aCounters) { aCounters = GetTestBitstreamCounters(); } TUint CMMFTestVideoDecodeHwDevice::NumFreeBuffers() { return KTestNumFreeBuffers; } TVideoInputBuffer* CMMFTestVideoDecodeHwDevice::GetBufferL(TUint aBufferSize) { if (!iBufferDataArea) { TPtrC8 testBufferString(KTestBufferString); iBufferDataArea = testBufferString.AllocL(); } TPtr8 dataAreaPtr = iBufferDataArea->Des(); TInt reqBufferSize = aBufferSize; if (reqBufferSize > dataAreaPtr.MaxLength()) User::Leave(KErrTooBig); // initialize iInputBuffer with test data iInputBuffer.iOptions = KTestBufferOptions; iInputBuffer.iDecodingTimestamp = aBufferSize; iInputBuffer.iData.Set(dataAreaPtr); // call new buffer callback iProxy->MdvppNewBuffers(); return &iInputBuffer; } void CMMFTestVideoDecodeHwDevice::WriteCodedDataL(TVideoInputBuffer* aBuffer) { TTimeIntervalMicroSeconds testTime(KTestBufferSize); // check received buffer against test data if (!(aBuffer->iOptions == KTestBufferOptions) || !(aBuffer->iDecodingTimestamp == testTime) || !(aBuffer->iData == KTestBufferString)) { User::Leave(KErrCorrupt); } } void CMMFTestVideoDecodeHwDevice::WriteCodedDataL(TVideoInputBuffer* aBuffer, TFramePortion aPortion) { TTimeIntervalMicroSeconds testTime(KTestBufferSize); // check received buffer against test data if ((aPortion != EFramePortionEndFragment) || !(aBuffer->iOptions == KTestBufferOptions) || !(aBuffer->iDecodingTimestamp == testTime) || !(aBuffer->iData == KTestBufferString)) { User::Leave(KErrCorrupt); } } void CMMFTestVideoDecodeHwDevice::ScanAndCopyCodedDataL(TPtr8 aCodedData, TVideoInputBuffer* aBuffer, TInt& aConsumed, TFramePortion aPortion) { //compare ptr data to test data if ((aPortion != EFramePortionEndFragment) || (aCodedData != KTestBufferString)) { User::Leave(KErrCorrupt); } //copy data into buffer aBuffer->iData.Set(aCodedData); aConsumed = aBuffer->iData.Length(); } void CMMFTestVideoDecodeHwDevice::CommitL() { } void CMMFTestVideoDecodeHwDevice::Revert() { } void CMMFTestVideoDecodeHwDevice::SetProxy(MMMFDevVideoPlayProxy& aProxy) { ASSERT(iProxy == NULL); iProxy = &aProxy; }
c++
code
18,193
3,031
/* * fft.cpp * * Created on: 13.12.2012 * Author: stephaniebayer */ #include "fft.h" #include<vector> #include "Cipher_elg.h" #include "G_q.h" #include "Mod_p.h" #include "Functions.h" #include "multi_expo.h" #include <NTL/ZZ.h> #include <NTL/mat_ZZ.h> NTL_CLIENT fft::fft() { // TODO Auto-generated constructor stub } fft::~fft() { // TODO Auto-generated destructor stub } ZZ fft::r_o_u(ZZ gen, long m, ZZ ord){ // ZZ ord = H.get_ord(); ZZ rou; ZZ pow; ZZ temp; long t = 2*m; if ((ord-1) % t == 0) { temp = (ord-1)/t; PowerMod(rou,gen,temp , ord); if(GCD(rou,ord)==to_ZZ(1)) { if (t&1) { PowerMod(pow,rou,t, ord); if(pow==1){ //cout<<"rou: "<<ord<<" "<<rou; return rou; } } else { PowerMod(pow,rou,t/2,ord); if(pow == (ord-1)) { //cout<<"rou "<<ord<<" "<<rou; return rou; } } } } else { cout << "There is no" << 2*m <<"-th root of unity"<< endl; return to_ZZ(1); } return to_ZZ(1); } long fft::to_long(vector<int>* bit_r){ long t, length; double two,i; two = 2; length =bit_r->size(); t=0; for(i = 0; i<length; i++ ){ t =t +bit_r->at(i)*pow(two,i); } return t; } void fft::bitreverse(long& z, long x, long d){ long i; vector<int>* temp=0; temp = new vector<int>(d); for(i = 0; i<d; i++){ if(bit(x,i)==1){ temp->at(d-i-1)=1; } else{ temp->at(d-i-1)=0; } } z = to_long(temp); delete temp; } void fft::brevorder(vector<ZZ>* ret, vector<ZZ>* v){ long i,k,d,l, lv; ZZ temp; lv = v->size(); l=ret->size(); d = NumBits(l)-1; for(i = 0; i<lv; i++){ ret->at(i)=v->at(i); } for(i = 0; i<l; i++){ bitreverse(k,i,d); if(i<k){ temp = ret->at(i); ret->at(i) = ret->at(k); ret->at(k)= temp; } } } void fft::FFT(vector<ZZ>* fft, vector<ZZ>* v , long N, ZZ rootofunity, ZZ ord){ int n, m, m2, i, i0, i1, k, l; ZZ rho, rr, z; double two = 2; l= v->size(); //cout<<fft->size()<< " "<<N; brevorder(fft,v); n = NumBits(N)-1; //(* N = 2**n *) for(k= 0; k<n; k++){ //cout<<k<<" "; m = pow(two,k); m2 = 2*m; rr = 1; PowerMod(rho,rootofunity,pow(two, n-k-1),ord); // cout<<m2<<" rho "<<rho<<" "<<m<<" "; for (i = 0; i<m; i++){ i0=i; //cout<<" rr "<<rr; while( i0 < N){ i1=i0+m; //cout<<" : "<<i0<<" "<<i1<<" "; MulMod(z, fft->at(i1), rr, ord); //(* rr = rho**i *) //cout<<" z "<<z<<" "; SubMod(fft->at(i1),fft->at(i0), z, ord); //cout<<fft->at(i0)<<" "<<fft->at(i1)<<" "; AddMod(fft->at(i0), fft->at(i0), z, ord); //cout<<fft->at(i0)<<" "<<fft->at(i1)<<" "; i0 = i0 + m2; } MulMod(rr ,rr,rho, ord) ; } // cout<<endl; } } void fft::FFTinv(vector<ZZ>* ret, vector<ZZ>* points, long N, ZZ rootofunity, ZZ ord){ long i; ZZ s, omega; InvMod(omega, rootofunity, ord); InvMod(s,to_ZZ(N),ord); FFT(ret, points,N,omega,ord); for (i = 0; i< N; i++){ MulMod(ret->at(i), s , ret->at(i), ord); } } void fft::fft_in(vector<ZZ>* ret, vector<ZZ>* v, ZZ rootofunity, ZZ ord, ZZ mod){ int nb,t,t2,i,i0,i1,k,l; ZZ rho, rr, z; double two = 2; l = v->size(); brevorder(ret, v); nb = NumBits(l)-1; for(k = 0 ; k<nb; k++){ t = pow(two,k); t2 = 2*t; rr = 1; PowerMod(rho,rootofunity,pow(two, nb-k-1),ord); for(i = 0; i<t; i ++){ i0 = i; if(rr != 1){ while (i0 < l){ i1=i0+t; PowerMod(z,ret->at(i1), rr, mod); MulMod(ret->at(i1),ret->at(i0), InvMod(z,mod),mod); MulMod(ret->at(i0),ret->at(i0), z, mod); i0 = i0 + t2; } } else{ while (i0 < l){ i1=i0+t; z = ret->at(i1); MulMod(ret->at(i1),ret->at(i0), InvMod(z,mod),mod); MulMod(ret->at(i0),ret->at(i0), z, mod); i0 = i0 + t2; } } MulMod(rr, rr,rho,ord); } } } void fft::fft_sum_in(vector<ZZ>* ret, vector<ZZ>* v, ZZ rootofunity, ZZ ord){ int nb,t,t2,i,i0,i1,k,l; ZZ rho, rr, z; double two = 2; l = v->size(); brevorder(ret, v); nb = NumBits(l)-1; for(k = 0 ; k<nb; k++){ t = pow(two,k); t2 = 2*t; rr = 1; PowerMod(rho,rootofunity,pow(two, nb-k-1),ord); for(i = 0; i<t; i ++){ i0 = i; while (i0 < l){ i1=i0+t; MulMod(z,ret->at(i1), rr, ord); SubMod(ret->at(i1),ret->at(i0), z, ord); AddMod(ret->at(i0),ret->at(i0), z, ord); i0 = i0 + t2; } MulMod(rr,rr,rho,ord); } } } void fft::fft_mult_cipher(vector<vector<vector<ZZ>* >*>* ret, vector<vector<Cipher_elg>* >* v, ZZ rootofunity, ZZ ord, ZZ mod){ vector<vector<ZZ>* >* fft = 0; vector<ZZ>* temp_u = 0; vector<ZZ>* temp_v = 0; long i,j, m, n,l; n= v->at(0)->size(); m = v->size(); l=2*m; for(i = 0; i<n; i++){ fft =new vector<vector<ZZ>* >(2); temp_u = new vector<ZZ>(l); temp_v = new vector<ZZ>(l); temp_u ->at(0) = to_ZZ(1); temp_v ->at(0) = to_ZZ(1); for(j = 1; j <=m; j++){ temp_u->at(j)=v->at(j-1)->at(i).get_u(); temp_v->at(j)=v->at(j-1)->at(i).get_v(); } for(j = m+1; j<l; j++){ temp_u->at(j) = to_ZZ(1); temp_v->at(j) = to_ZZ(1); } fft->at(0)=new vector<ZZ>(l); fft->at(1)=new vector<ZZ>(l); fft_in(fft->at(0), temp_u, rootofunity, ord, mod); fft_in(fft->at(1), temp_v,rootofunity, ord, mod); ret->at(i)=fft; delete temp_u; delete temp_v; } } void fft::fft_matrix(vector<vector<ZZ>* >* ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){ vector<ZZ>* fft = 0; vector<ZZ>* temp = 0; long i,j, m, n,l; double two = 2; int e; // cout<<"in sumT "<< T->size(); n= T->at(0)->size(); m = T->size(); //In the case of the Ciphertexts m is a power of 2, in the normal setting m is odd in our case if(m%2==0){ e = NumBits(2*m+1)- 1; } else{ e = NumBits(2*m+1); } l = pow(two, e); for(i = 0; i<n; i++){ temp = new vector<ZZ>(m); for(j = 0; j <m; j++){ temp->at(j)=T->at(j)->at(i); } fft=new vector<ZZ>(l); FFT(fft, temp, l, rootofunity, ord ); //fft_sum_in(fft, temp, rootofunity, ord); ret->at(i)=fft; delete temp; } // cout<<endl; } void fft::fft_matrix_inv(vector<vector<ZZ>* >* ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){ vector<ZZ>* fft = 0; vector<ZZ>* temp = 0; long i,j, m, n,l; double two = 2; int e; //cout<<"in sumT "<< ret->size(); //In the case of the Ciphertexts m is a power of 2, in the normal setting m is odd in our case n= T->at(0)->size(); m = T->size(); if(m%2==0){ e = NumBits(2*m+1)- 1; } else{ e = NumBits(2*m+1); } l = pow(two, e); // cout<<" l ist "<<l<<endl; for(i = 0; i<n; i++){ temp = new vector<ZZ>(m); for(j = 0; j <m; j++){ temp->at(j)=T->at(m-j-1)->at(i); } fft=new vector<ZZ>(l); FFT(fft, temp, l, rootofunity, ord ); //fft_sum_in(fft, temp, rootofunity, ord); ret->at(i)=fft; delete temp; } //cout<<endl; } void fft::sum_t(vector<vector<ZZ>*>* ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){ vector<ZZ>* tem = 0; ZZ temp, t; long m,n,k,i,j,te,l; m = T->size(); n = T->at(0)->size(); l=2*m; for(k= 0; k<l; k++){ tem = new vector<ZZ>(n); for(j = 0; j<n;j++){ temp = 0; for (i = m-1; i>= 0; i--){ PowerMod(t,rootofunity, i*(k+1),ord); te =fabs(i-m+1); MulMod(t,t,T->at(te)->at(j),ord); AddMod(temp, temp, t,ord); } tem->at(j) = temp; } ret->at(k) = tem; } } void fft::calc_Pk(vector<vector<ZZ>*>* ret, vector<vector<Cipher_elg>* >* v, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord, ZZ mod, int omega_sw){ long j,m,n,l; vector<vector<vector<ZZ>* >*>* fft_t=0; vector<vector<ZZ>* >* sumT=0; ZZ temp_u, te_u, temp_v, te_v,temp ; m = T->size(); n= T->at(0)->size(); vector<ZZ>* ret_u = new vector<ZZ>(2*m); vector<ZZ>* ret_v = new vector<ZZ>(2*m); fft_t = new vector<vector<vector<ZZ>* >*>(n); fft::fft_mult_cipher(fft_t, v,rootofunity, ord, mod); sumT = new vector<vector<ZZ>* >(n); fft::fft_matrix_inv(sumT, T, rootofunity, ord); l=2*m-1; for (j = 0; j<l; j++){ multi_expo::multi_expo_LL(temp_u,fft_t, sumT, omega_sw ,j+1,0); multi_expo::multi_expo_LL(temp_v,fft_t, sumT, omega_sw ,j+1,1); ret_u->at(j) = temp_u; ret_v->at(j) = temp_v; } multi_expo::multi_expo_LL(temp_u ,fft_t, sumT, omega_sw ,0,0); multi_expo::multi_expo_LL(temp_v ,fft_t, sumT, omega_sw ,0,1); ret_u->at(l) = temp_u; ret_v->at(l) = temp_v; ret->at(0) = ret_u; ret->at(1) = ret_v; Functions::delete_vector(fft_t); Functions::delete_vector(sumT); } void fft::calc_m( vector<vector<ZZ>*>* M , long m, ZZ rootofunity, ZZ ord){ vector<ZZ>* Rootofunity; vector<ZZ>* div; ZZ prod,temp,temp_1; long i,j,l; l=2*m; vector<ZZ>* Rootofun = new vector<ZZ>(l); div =new vector<ZZ>(l); Rootofun->at(0) = rootofunity; for(i = 1; i<l; i++){ MulMod(Rootofun->at(i), Rootofun->at(i-1), rootofunity,ord); } for(i = 0 ; i<l; i++){ prod = 1; for(j = 0; j<l; j++){ if (i!=j){ MulMod(prod,prod, SubMod(Rootofun->at(i),Rootofun->at(j),ord),ord); } } div->at(i)= prod; } for(i = 0; i<l; i++){ Rootofunity = new vector<ZZ>(l); Rootofunity->at(2*m-1) = to_ZZ(1); PowerMod(temp,rootofunity, i+1,ord); for(j = l-2; j>=0; j--){ MulMod(Rootofunity->at(j),Rootofunity->at(j+1),temp,ord); } for(j = l-1; j>=0; j--){ MulMod(Rootofunity->at(j),Rootofunity->at(j), InvMod(div->at(i),ord),ord); } M->at(i) = Rootofunity; } delete Rootofun; delete div; }
c++
code
9,336
3,858
//---------------------------------------------------------------------- // File: rrtNode.cpp // Programmer: Lening Li // Last modified: 9/23/15 // Description: RRT Node code //---------------------------------------------------------------------- // Copyright (c) 2015-2016 Worcester Polytechnic Institute and Lening Li. // All Rights Reserved. // // This file and related documentation are part of the // Motion Planning Homework to implement Rapidly-exploring Random Trees. // // Permission to use, copy, and distribute this software and its // documentation is hereby granted free of charge, provided that // (1) it is not a component of a commercial product, and // (2) this notice appears in all copies of the software and // related documentation. // // Worcester Polytechnic Institute and the author make no representations // about the suitability or fitness of this software for any purpose. It is // provided "as is" without express or implied warranty. //---------------------------------------------------------------------- # include "rrtNode.hpp" bool rrtNode::operator == (const rrtNode &Node) { if (_con_f == Node._con_f) return true; else return false; } void rrtNode::operator = (const rrtNode &Node) { _con_f = Node._con_f; _parent = Node._parent; _index = Node._index; } bool rrtNode::operator != (const rrtNode &Node) { if(_con_f != Node._con_f) return true; else return false; }
c++
code
1,472
362
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/storagegateway/model/InternalServerError.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace StorageGateway { namespace Model { InternalServerError::InternalServerError() : m_messageHasBeenSet(false), m_errorHasBeenSet(false) { } InternalServerError::InternalServerError(JsonView jsonValue) : m_messageHasBeenSet(false), m_errorHasBeenSet(false) { *this = jsonValue; } InternalServerError& InternalServerError::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("message")) { m_message = jsonValue.GetString("message"); m_messageHasBeenSet = true; } if(jsonValue.ValueExists("error")) { m_error = jsonValue.GetObject("error"); m_errorHasBeenSet = true; } return *this; } JsonValue InternalServerError::Jsonize() const { JsonValue payload; if(m_messageHasBeenSet) { payload.WithString("message", m_message); } if(m_errorHasBeenSet) { payload.WithObject("error", m_error.Jsonize()); } return payload; } } // namespace Model } // namespace StorageGateway } // namespace Aws
c++
code
1,306
246
#include "TextureDB.h" #include "third-party/fmt/core.h" #include "common/util/Assert.h" namespace decompiler { void TextureDB::add_texture(u32 tpage, u32 texid, const std::vector<u32>& data, u16 w, u16 h, const std::string& tex_name, const std::string& tpage_name) { auto existing_tpage_name = tpage_names.find(tpage); if (existing_tpage_name == tpage_names.end()) { tpage_names[tpage] = tpage_name; } else { ASSERT(existing_tpage_name->second == tpage_name); } u32 combo_id = (tpage << 16) | texid; auto existing_tex = textures.find(combo_id); if (existing_tex != textures.end()) { ASSERT(existing_tex->second.name == tex_name); ASSERT(existing_tex->second.w == w); ASSERT(existing_tex->second.h == h); ASSERT(existing_tex->second.rgba_bytes == data); ASSERT(existing_tex->second.page == tpage); } else { auto& new_tex = textures[combo_id]; new_tex.rgba_bytes = data; new_tex.name = tex_name; new_tex.w = w; new_tex.h = h; new_tex.page = tpage; } } } // namespace decompiler
c++
code
1,220
252
/* * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. * See https://llvm.org/LICENSE.txt for license information. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception * */ #if !(defined _CPU) #error: please define _CPU - specific suffix to a function name #endif #if !(defined _VL) #error: please define _VL - Number of elements per vector register #endif #include <immintrin.h> #define CONFIG 1 #if ((_VL) == (2)) #include "helperavx2_128.h" #elif ((_VL) == (4)) #include "helperavx2.h" #elif ((_VL) == (8)) #include "helperavx512f.h" #endif #define _JOIN4(a,b,c,d) a##b##c##d #define JOIN4(a,b,c,d) _JOIN4(a,b,c,d) #define atan2_d_vec JOIN4(__fd_atan2_,_VL,_,_CPU) extern "C" vdouble atan2_d_vec(vdouble const, vdouble const); #include <atan2_d_vec.h>
c++
code
802
215
#include "duckdb/execution/operator/join/physical_piecewise_merge_join.hpp" #include "duckdb/parallel/thread_context.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/merge_join.hpp" #include "duckdb/common/operator/comparison_operators.hpp" #include "duckdb/main/client_context.hpp" namespace duckdb { PhysicalPiecewiseMergeJoin::PhysicalPiecewiseMergeJoin(LogicalOperator &op, unique_ptr<PhysicalOperator> left, unique_ptr<PhysicalOperator> right, vector<JoinCondition> cond, JoinType join_type, idx_t estimated_cardinality) : PhysicalComparisonJoin(op, PhysicalOperatorType::PIECEWISE_MERGE_JOIN, move(cond), join_type, estimated_cardinality) { // for now we only support one condition! D_ASSERT(conditions.size() == 1); for (auto &cond : conditions) { // COMPARE NOT EQUAL not supported with merge join D_ASSERT(cond.comparison != ExpressionType::COMPARE_NOTEQUAL); D_ASSERT(cond.left->return_type == cond.right->return_type); join_key_types.push_back(cond.left->return_type); } children.push_back(move(left)); children.push_back(move(right)); } //===--------------------------------------------------------------------===// // Sink //===--------------------------------------------------------------------===// class MergeJoinLocalState : public LocalSinkState { public: explicit MergeJoinLocalState(const vector<JoinCondition> &conditions) { vector<LogicalType> condition_types; for (auto &cond : conditions) { rhs_executor.AddExpression(*cond.right); condition_types.push_back(cond.right->return_type); } join_keys.Initialize(condition_types); } //! The chunk holding the right condition DataChunk join_keys; //! The executor of the RHS condition ExpressionExecutor rhs_executor; }; class MergeJoinGlobalState : public GlobalSinkState { public: MergeJoinGlobalState() : has_null(false), right_outer_position(0) { } mutex mj_lock; //! The materialized data of the RHS ChunkCollection right_chunks; //! The materialized join keys of the RHS ChunkCollection right_conditions; //! The join orders of the RHS vector<MergeOrder> right_orders; //! Whether or not the RHS of the nested loop join has NULL values bool has_null; //! A bool indicating for each tuple in the RHS if they found a match (only used in FULL OUTER JOIN) unique_ptr<bool[]> right_found_match; //! The position in the RHS in the final scan of the FULL OUTER JOIN idx_t right_outer_position; }; unique_ptr<GlobalSinkState> PhysicalPiecewiseMergeJoin::GetGlobalSinkState(ClientContext &context) const { return make_unique<MergeJoinGlobalState>(); } unique_ptr<LocalSinkState> PhysicalPiecewiseMergeJoin::GetLocalSinkState(ExecutionContext &context) const { return make_unique<MergeJoinLocalState>(conditions); } SinkResultType PhysicalPiecewiseMergeJoin::Sink(ExecutionContext &context, GlobalSinkState &state, LocalSinkState &lstate, DataChunk &input) const { auto &gstate = (MergeJoinGlobalState &)state; auto &mj_state = (MergeJoinLocalState &)lstate; // resolve the join keys for this chunk mj_state.rhs_executor.SetChunk(input); mj_state.join_keys.Reset(); mj_state.join_keys.SetCardinality(input); for (idx_t k = 0; k < conditions.size(); k++) { // resolve the join key mj_state.rhs_executor.ExecuteExpression(k, mj_state.join_keys.data[k]); } // append the join keys and the chunk to the chunk collection lock_guard<mutex> mj_guard(gstate.mj_lock); gstate.right_chunks.Append(input); gstate.right_conditions.Append(mj_state.join_keys); return SinkResultType::NEED_MORE_INPUT; } void PhysicalPiecewiseMergeJoin::Combine(ExecutionContext &context, GlobalSinkState &gstate, LocalSinkState &lstate) const { auto &state = (MergeJoinLocalState &)lstate; context.thread.profiler.Flush(this, &state.rhs_executor, "rhs_executor", 1); context.client.profiler->Flush(context.thread.profiler); } //===--------------------------------------------------------------------===// // Finalize //===--------------------------------------------------------------------===// static void OrderVector(Vector &vector, idx_t count, MergeOrder &order); SinkFinalizeType PhysicalPiecewiseMergeJoin::Finalize(Pipeline &pipeline, Event &event, ClientContext &context, GlobalSinkState &gstate_p) const { auto &gstate = (MergeJoinGlobalState &)gstate_p; if (gstate.right_conditions.ChunkCount() > 0) { // now order all the chunks gstate.right_orders.resize(gstate.right_conditions.ChunkCount()); for (idx_t i = 0; i < gstate.right_conditions.ChunkCount(); i++) { auto &chunk_to_order = gstate.right_conditions.GetChunk(i); D_ASSERT(chunk_to_order.ColumnCount() == 1); for (idx_t col_idx = 0; col_idx < chunk_to_order.ColumnCount(); col_idx++) { OrderVector(chunk_to_order.data[col_idx], chunk_to_order.size(), gstate.right_orders[i]); if (gstate.right_orders[i].count < chunk_to_order.size()) { // the amount of entries in the order vector is smaller than the amount of entries in the vector // this only happens if there are NULL values in the right-hand side // hence we set the has_null to true (this is required for the MARK join) gstate.has_null = true; } } } } if (IsRightOuterJoin(join_type)) { // for FULL/RIGHT OUTER JOIN, initialize found_match to false for every tuple gstate.right_found_match = unique_ptr<bool[]>(new bool[gstate.right_chunks.Count()]); memset(gstate.right_found_match.get(), 0, sizeof(bool) * gstate.right_chunks.Count()); } if (gstate.right_chunks.Count() == 0 && EmptyResultIfRHSIsEmpty()) { return SinkFinalizeType::NO_OUTPUT_POSSIBLE; } return SinkFinalizeType::READY; } //===--------------------------------------------------------------------===// // Operator //===--------------------------------------------------------------------===// class PiecewiseMergeJoinState : public OperatorState { public: explicit PiecewiseMergeJoinState(const PhysicalPiecewiseMergeJoin &op) : op(op), first_fetch(true), finished(true), left_position(0), right_position(0), right_chunk_index(0) { vector<LogicalType> condition_types; for (auto &cond : op.conditions) { lhs_executor.AddExpression(*cond.left); condition_types.push_back(cond.left->return_type); } join_keys.Initialize(condition_types); if (IsLeftOuterJoin(op.join_type)) { left_found_match = unique_ptr<bool[]>(new bool[STANDARD_VECTOR_SIZE]); memset(left_found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE); } } const PhysicalPiecewiseMergeJoin &op; bool first_fetch; bool finished; idx_t left_position; idx_t right_position; idx_t right_chunk_index; DataChunk left_chunk; DataChunk join_keys; MergeOrder left_orders; //! The executor of the RHS condition ExpressionExecutor lhs_executor; unique_ptr<bool[]> left_found_match; public: void ResolveJoinKeys(DataChunk &input) { // resolve the join keys for the input join_keys.Reset(); lhs_executor.SetChunk(input); join_keys.SetCardinality(input); for (idx_t k = 0; k < op.conditions.size(); k++) { lhs_executor.ExecuteExpression(k, join_keys.data[k]); // sort by join key OrderVector(join_keys.data[k], join_keys.size(), left_orders); } } void Finalize(PhysicalOperator *op, ExecutionContext &context) override { context.thread.profiler.Flush(op, &lhs_executor, "lhs_executor", 0); } }; unique_ptr<OperatorState> PhysicalPiecewiseMergeJoin::GetOperatorState(ClientContext &context) const { return make_unique<PiecewiseMergeJoinState>(*this); } void PhysicalPiecewiseMergeJoin::ResolveSimpleJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state_p) const { auto &state = (PiecewiseMergeJoinState &)state_p; auto &gstate = (MergeJoinGlobalState &)*sink_state; state.ResolveJoinKeys(input); ScalarMergeInfo left_info(state.left_orders, state.join_keys.data[0].GetType(), state.left_position); ChunkMergeInfo right_info(gstate.right_conditions, gstate.right_orders); // perform the actual join MergeJoinSimple::Perform(left_info, right_info, conditions[0].comparison); // now construct the result based ont he join result switch (join_type) { case JoinType::MARK: PhysicalJoin::ConstructMarkJoinResult(state.join_keys, input, chunk, right_info.found_match, gstate.has_null); break; case JoinType::SEMI: PhysicalJoin::ConstructSemiJoinResult(input, chunk, right_info.found_match); break; case JoinType::ANTI: PhysicalJoin::ConstructAntiJoinResult(input, chunk, right_info.found_match); break; default: throw NotImplementedException("Unimplemented join type for merge join"); } } OperatorResultType PhysicalPiecewiseMergeJoin::ResolveComplexJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state_p) const { auto &state = (PiecewiseMergeJoinState &)state_p; auto &gstate = (MergeJoinGlobalState &)*sink_state; do { if (state.first_fetch) { state.ResolveJoinKeys(input); state.right_chunk_index = 0; state.left_position = 0; state.right_position = 0; state.first_fetch = false; state.finished = false; } if (state.finished) { if (IsLeftOuterJoin(join_type)) { // left join: before we move to the next chunk, see if we need to output any vectors that didn't // have a match found PhysicalJoin::ConstructLeftJoinResult(input, chunk, state.left_found_match.get()); memset(state.left_found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE); } state.first_fetch = true; state.finished = false; return OperatorResultType::NEED_MORE_INPUT; } auto &right_chunk = gstate.right_chunks.GetChunk(state.right_chunk_index); auto &right_condition_chunk = gstate.right_conditions.GetChunk(state.right_chunk_index); auto &right_orders = gstate.right_orders[state.right_chunk_index]; ScalarMergeInfo left_info(state.left_orders, state.join_keys.data[0].GetType(), state.left_position); ScalarMergeInfo right_info(right_orders, right_condition_chunk.data[0].GetType(), state.right_position); idx_t result_count = MergeJoinComplex::Perform(left_info, right_info, conditions[0].comparison); if (result_count == 0) { // exhausted this chunk on the right side // move to the next right chunk state.left_position = 0; state.right_position = 0; state.right_chunk_index++; if (state.right_chunk_index >= gstate.right_chunks.ChunkCount()) { state.finished = true; } } else { // found matches: mark the found matches if required if (state.left_found_match) { for (idx_t i = 0; i < result_count; i++) { state.left_found_match[left_info.result.get_index(i)] = true; } } if (gstate.right_found_match) { idx_t base_index = state.right_chunk_index * STANDARD_VECTOR_SIZE; for (idx_t i = 0; i < result_count; i++) { gstate.right_found_match[base_index + right_info.result.get_index(i)] = true; } } // found matches: output them chunk.Slice(input, left_info.result, result_count); chunk.Slice(right_chunk, right_info.result, result_count, input.ColumnCount()); } } while (chunk.size() == 0); return OperatorResultType::HAVE_MORE_OUTPUT; } OperatorResultType PhysicalPiecewiseMergeJoin::Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state) const { auto &gstate = (MergeJoinGlobalState &)*sink_state; if (gstate.right_chunks.Count() == 0) { // empty RHS if (!EmptyResultIfRHSIsEmpty()) { ConstructEmptyJoinResult(join_type, gstate.has_null, input, chunk); return OperatorResultType::NEED_MORE_INPUT; } else { return OperatorResultType::FINISHED; } } switch (join_type) { case JoinType::SEMI: case JoinType::ANTI: case JoinType::MARK: // simple joins can have max STANDARD_VECTOR_SIZE matches per chunk ResolveSimpleJoin(context, input, chunk, state); return OperatorResultType::NEED_MORE_INPUT; case JoinType::LEFT: case JoinType::INNER: case JoinType::RIGHT: case JoinType::OUTER: return ResolveComplexJoin(context, input, chunk, state); default: throw NotImplementedException("Unimplemented type for piecewise merge loop join!"); } } //===--------------------------------------------------------------------===// // OrderVector //===--------------------------------------------------------------------===// template <class T, class OP> static sel_t TemplatedQuicksortInitial(T *data, const SelectionVector &sel, const SelectionVector &not_null_sel, idx_t count, SelectionVector &result) { // select pivot auto pivot_idx = not_null_sel.get_index(0); auto dpivot_idx = sel.get_index(pivot_idx); sel_t low = 0, high = count - 1; // now insert elements for (idx_t i = 1; i < count; i++) { auto idx = not_null_sel.get_index(i); auto didx = sel.get_index(idx); if (OP::Operation(data[didx], data[dpivot_idx])) { result.set_index(low++, idx); } else { result.set_index(high--, idx); } } D_ASSERT(low == high); result.set_index(low, pivot_idx); return low; } struct QuickSortPivot { QuickSortPivot(sel_t left_p, sel_t right_p) : left(left_p), right(right_p) { } sel_t left; sel_t right; }; template <class T, class OP> static void TemplatedQuicksortRefine(T *data, const SelectionVector &sel, idx_t count, SelectionVector &result, sel_t left, sel_t right, vector<QuickSortPivot> &pivots) { if (left >= right) { return; } sel_t middle = left + (right - left) / 2; sel_t dpivot_idx = sel.get_index(result.get_index(middle)); // move the mid point value to the front. sel_t i = left + 1; sel_t j = right; result.swap(middle, left); while (i <= j) { while (i <= j && (OP::Operation(data[sel.get_index(result.get_index(i))], data[dpivot_idx]))) { i++; } while (i <= j && !OP::Operation(data[sel.get_index(result.get_index(j))], data[dpivot_idx])) { j--; } if (i < j) { result.swap(i, j); } } result.swap(i - 1, left); sel_t part = i - 1; if (part > 0) { pivots.emplace_back(left, part - 1); } if (part + 1 < right) { pivots.emplace_back(part + 1, right); } } template <class T, class OP> void TemplatedQuicksort(T *__restrict data, const SelectionVector &sel, const SelectionVector &not_null_sel, idx_t count, SelectionVector &result) { auto part = TemplatedQuicksortInitial<T, OP>(data, sel, not_null_sel, count, result); if (part > count) { return; } vector<QuickSortPivot> pivots; pivots.emplace_back(0, part); pivots.emplace_back(part + 1, count - 1); for (idx_t i = 0; i < pivots.size(); i++) { auto pivot = pivots[i]; TemplatedQuicksortRefine<T, OP>(data, sel, count, result, pivot.left, pivot.right, pivots); } } template <class T> static void TemplatedQuicksort(VectorData &vdata, const SelectionVector &not_null_sel, idx_t not_null_count, SelectionVector &result) { if (not_null_count == 0) { return; } TemplatedQuicksort<T, duckdb::LessThanEquals>((T *)vdata.data, *vdata.sel, not_null_sel, not_null_count, result); } void OrderVector(Vector &vector, idx_t count, MergeOrder &order) { if (count == 0) { order.count = 0; return; } vector.Orrify(count, order.vdata); auto &vdata = order.vdata; // first filter out all the non-null values SelectionVector not_null(STANDARD_VECTOR_SIZE); idx_t not_null_count = 0; for (idx_t i = 0; i < count; i++) { auto idx = vdata.sel->get_index(i); if (vdata.validity.RowIsValid(idx)) { not_null.set_index(not_null_count++, i); } } order.count = not_null_count; order.order.Initialize(STANDARD_VECTOR_SIZE); switch (vector.GetType().InternalType()) { case PhysicalType::BOOL: case PhysicalType::INT8: TemplatedQuicksort<int8_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::INT16: TemplatedQuicksort<int16_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::INT32: TemplatedQuicksort<int32_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::INT64: TemplatedQuicksort<int64_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::UINT8: TemplatedQuicksort<uint8_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::UINT16: TemplatedQuicksort<uint16_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::UINT32: TemplatedQuicksort<uint32_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::UINT64: TemplatedQuicksort<uint64_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::INT128: TemplatedQuicksort<hugeint_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::FLOAT: TemplatedQuicksort<float>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::DOUBLE: TemplatedQuicksort<double>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::INTERVAL: TemplatedQuicksort<interval_t>(vdata, not_null, not_null_count, order.order); break; case PhysicalType::VARCHAR: TemplatedQuicksort<string_t>(vdata, not_null, not_null_count, order.order); break; default: throw NotImplementedException("Unimplemented type for sort"); } } //===--------------------------------------------------------------------===// // Source //===--------------------------------------------------------------------===// class PiecewiseJoinScanState : public GlobalSourceState { public: explicit PiecewiseJoinScanState(const PhysicalPiecewiseMergeJoin &op) : op(op), right_outer_position(0) { } mutex lock; const PhysicalPiecewiseMergeJoin &op; idx_t right_outer_position; public: idx_t MaxThreads() override { auto &sink = (MergeJoinGlobalState &)*op.sink_state; return sink.right_chunks.Count() / (STANDARD_VECTOR_SIZE * 10); } }; unique_ptr<GlobalSourceState> PhysicalPiecewiseMergeJoin::GetGlobalSourceState(ClientContext &context) const { return make_unique<PiecewiseJoinScanState>(*this); } void PhysicalPiecewiseMergeJoin::GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate, LocalSourceState &lstate) const { D_ASSERT(IsRightOuterJoin(join_type)); // check if we need to scan any unmatched tuples from the RHS for the full/right outer join auto &sink = (MergeJoinGlobalState &)*sink_state; auto &state = (PiecewiseJoinScanState &)gstate; // if the LHS is exhausted in a FULL/RIGHT OUTER JOIN, we scan the found_match for any chunks we // still need to output lock_guard<mutex> l(state.lock); ConstructFullOuterJoinResult(sink.right_found_match.get(), sink.right_chunks, chunk, state.right_outer_position); } } // namespace duckdb
c++
code
19,189
4,149
#include <iostream> #include "MethodInvokeAgent.h" #include "jvmti.h" #include "jni.h" #include <time.h> using namespace std; JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { MethodInvokeAgent::start=clock(); try{ MethodInvokeAgent* agent = new MethodInvokeAgent(); agent->Init(vm); agent->ParseOptions(options); agent->AddCapability(); agent->RegisterEvent(); } catch (AgentException& e) { cout << "Error when enter HandleMethodEntry: " << e.what() << " [" << e.ErrCode() << "]"; return JNI_ERR; } cout<<"Init GVM.dll success!!"<<endl; return JNI_OK; } JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { MethodInvokeAgent::end=clock(); cout<<"Run time:"<<MethodInvokeAgent::end-MethodInvokeAgent::start<<endl; }
c++
code
868
205
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "../../../../net/base/url_util.cc" #include <iostream> #include <string> #include "base/strings/string_piece.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/origin.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_canon_ip.h" namespace net { // Copypasta of ParseHostAndPort that extracts the username and // password instead of rejecting them. bool ParseAuthHostAndPort(base::StringPiece input, std::string* username, std::string* password, std::string* host, int* port) { if (input.empty()) return false; url::Component auth_component(0, input.size()); url::Component username_component; url::Component password_component; url::Component hostname_component; url::Component port_component; url::ParseAuthority(input.data(), auth_component, &username_component, &password_component, &hostname_component, &port_component); if (!hostname_component.is_nonempty()) return false; // Failed parsing. int parsed_port_number = -1; if (port_component.is_nonempty()) { parsed_port_number = url::ParsePort(input.data(), port_component); // If parsing failed, port_number will be either PORT_INVALID or // PORT_UNSPECIFIED, both of which are negative. if (parsed_port_number < 0) return false; // Failed parsing the port number. } if (port_component.len == 0) return false; // Reject inputs like "foo:" unsigned char tmp_ipv6_addr[16]; // If the hostname starts with a bracket, it is either an IPv6 literal or // invalid. If it is an IPv6 literal then strip the brackets. if (hostname_component.len > 0 && input[hostname_component.begin] == '[') { if (input[hostname_component.end() - 1] == ']' && url::IPv6AddressToNumber(input.data(), hostname_component, tmp_ipv6_addr)) { // Strip the brackets. hostname_component.begin++; hostname_component.len -= 2; } else { return false; } } // Pass results back to caller. if (username_component.is_valid()) { username->assign(input.data() + username_component.begin, username_component.len); } if (password_component.is_valid()) { password->assign(input.data() + password_component.begin, password_component.len); } host->assign(input.data() + hostname_component.begin, hostname_component.len); *port = parsed_port_number; return true; // Success. } std::string URLToEphemeralStorageDomain(const GURL& url) { std::string domain = registry_controlled_domains::GetDomainAndRegistry( url, registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); // GetDomainAndRegistry might return an empty string if this host is an IP // address or a file URL. if (domain.empty()) domain = url::Origin::Create(url.GetOrigin()).Serialize(); return domain; } } // namespace net
c++
code
3,230
621
// This source file is part of the Argon project. // // Licensed under the Apache License v2.0 #include <thread> #include <condition_variable> #include <cstdarg> #include <object/setup.h> #include <object/datatype/error.h> #include "routine_queue.h" #include "runtime.h" #include "areval.h" using namespace argon::object; using namespace argon::vm; #define VCORE_DEFAULT 2 #define OST_MAX 10000 enum class VCoreStatus { IDLE, RUNNING }; struct VCore { struct OSThread *ost; ArRoutineQueue queue; // ArRoutine queue (No lock needed... In the future, I hope ...)) VCoreStatus status; }; struct OSThread { OSThread *next; OSThread **prev; ArRoutine *routine; VCore *current; VCore *old; bool spinning; std::thread self; }; // OsThread variables OSThread *ost_active = nullptr; // Working OSThread OSThread *ost_idle = nullptr; // IDLE OSThread thread_local OSThread *ost_local = nullptr; // OSThread for actual thread thread_local OSThread *ost_main = nullptr; // OSThread main thread unsigned int ost_total = 0; // OSThread counter unsigned int ost_idle_count = 0; // OSThread counter (idle) std::atomic_uint ost_spinning_count = 0; // OSThread in spinning std::atomic_int ost_worker_count = 0; // OSThread counter (worker) bool should_stop = false; // If true all thread should be stopped bool stw = false; std::mutex ost_lock; std::mutex stw_lock; std::condition_variable ost_cond; std::condition_variable cond_stw; std::condition_variable cond_stopwait; // VCore variables VCore *vcores = nullptr; // List of instantiated VCore unsigned int vc_total = 0; // Maximum concurrent VCore std::atomic_uint vc_idle_count = 0; // IDLE VCore std::mutex vc_lock; /* ArRoutine Global queue */ ArRoutineQueue routine_gq; ArRoutine *FindExecutable() { ArRoutine *routine; VCore *target_vc; VCore *self_vc; unsigned short attempts = 3; if (should_stop) return nullptr; // Check from local queue if ((routine = ost_local->current->queue.Dequeue()) != nullptr) return routine; // Check from global queue if ((routine = routine_gq.Dequeue()) != nullptr) return routine; // Try to steal work from another thread // ▼▼▼▼▼ Busy VCore ▼▼▼▼▼ if (ost_local->spinning || ost_spinning_count < (vc_total - vc_idle_count)) { if (!ost_local->spinning) { ost_local->spinning = true; ost_spinning_count++; } // Steal work from other VCore self_vc = ost_local->current; do { // Scan other VCores for (unsigned int i = 0; i < vc_total; i++) { target_vc = vcores + i; if (target_vc == self_vc) continue; // Steal from queues that contain more than one item if ((routine = self_vc->queue.StealQueue(2, target_vc->queue)) != nullptr) return routine; } } while (--attempts > 0); } return routine; } bool WireVCore(VCore *vcore) { bool ok = false; if (vcore != nullptr && vcore->ost == nullptr) { vcore->ost = ost_local; vcore->status = VCoreStatus::RUNNING; ost_local->current = vcore; vc_idle_count--; ok = true; } return ok; } bool AcquireVCore() { std::unique_lock lck(vc_lock); for (unsigned int i = 0; i < vc_total; i++) { if ((WireVCore(vcores + i))) return true; } return false; } bool InitializeVCores() { if ((vcores = (VCore *) argon::memory::Alloc(sizeof(VCore) * vc_total)) == nullptr) return false; for (unsigned int i = 0; i < vc_total; i++) { vcores[i].ost = nullptr; new(&((vcores + i)->queue))ArRoutineQueue(ARGON_VM_QUEUE_MAX_ROUTINES); vcores[i].status = VCoreStatus::IDLE; } return true; } OSThread *AllocOST() { auto ost = (OSThread *) argon::memory::Alloc(sizeof(OSThread)); if (ost != nullptr) { ost->next = nullptr; ost->prev = nullptr; ost->routine = nullptr; ost->current = nullptr; ost->old = nullptr; ost->spinning = false; ost->self = std::thread(); } return ost; } inline void FreeOST(OSThread *ost) { if (ost != nullptr) argon::memory::Free(ost); } void OSTSleep() { std::unique_lock lck(ost_lock); ost_cond.wait(lck); } void PushOSThread(OSThread *ost, OSThread **list) { if (*list == nullptr) { ost->next = nullptr; ost->prev = list; } else { ost->next = (*list); if ((*list) != nullptr) (*list)->prev = &ost->next; ost->prev = list; } *list = ost; } void ReleaseVCore() { if (ost_local->current == nullptr) return; ost_local->old = ost_local->current; ost_local->current->status = VCoreStatus::IDLE; ost_local->current->ost = nullptr; ost_local->current = nullptr; vc_idle_count++; } void RemoveOSThread(OSThread *ost) { if (ost->prev != nullptr) *ost->prev = ost->next; if (ost->next != nullptr) ost->next->prev = ost->prev; } void ResetSpinning() { ost_local->spinning = false; ost_spinning_count--; if (vc_idle_count > 0) ost_cond.notify_one(); } void FromActiveToIdle(OSThread *ost) { if (ost_worker_count.fetch_sub(1) == 1) cond_stw.notify_one(); if (ost->current != nullptr) ReleaseVCore(); ost_lock.lock(); RemoveOSThread(ost); PushOSThread(ost, &ost_idle); ost_idle_count++; ost_lock.unlock(); } void FromIdleToActive(OSThread *ost) { ost_lock.lock(); RemoveOSThread(ost); PushOSThread(ost, &ost_active); ost_idle_count--; ost_lock.unlock(); ost_worker_count++; } void Schedule(OSThread *self) { ost_local = self; START: // Find a free VCore and associate with it while (!should_stop) { { std::unique_lock lck(vc_lock); if (WireVCore(ost_local->old)) break; } if (AcquireVCore()) break; OSTSleep(); } FromIdleToActive(self); // Main dispatch procedure while (!should_stop) { if ((self->routine = FindExecutable()) == nullptr) { FromActiveToIdle(self); OSTSleep(); goto START; } if (self->spinning) ResetSpinning(); if (should_stop) { RoutineDel(self->routine); self->routine = nullptr; break; } Release(Eval(self->routine)); RoutineDel(self->routine); self->routine = nullptr; if (self->current == nullptr) { FromActiveToIdle(self); goto START; } else STWCheckpoint(); } // Shutdown thread assert(self->routine == nullptr); FromActiveToIdle(self); ost_lock.lock(); RemoveOSThread(self); self->self.detach(); FreeOST(self); ost_total--; ost_lock.unlock(); } void StartOST(OSThread *ost) { ost_lock.lock(); PushOSThread(ost, &ost_idle); ost_total++; ost_idle_count++; ost_lock.unlock(); ost->self = std::thread(Schedule, ost); } ArObject *argon::vm::Call(ArObject *callable, int argc, ArObject **args) { auto func = (Function *) callable; ArObject *result = nullptr; Frame *frame; if (!AR_TYPEOF(callable, type_function_)) return ErrorFormat(type_type_error_, "'%s' object is not callable", AR_TYPE_NAME(func)); if (func->IsNative()) return FunctionCallNative(func, args, argc); if ((frame = FrameNew(func->code, func->gns, nullptr)) != nullptr) { FrameFillForCall(frame, func, args, argc); result = Eval(GetRoutine(), frame); FrameDel(frame); } if (IsPanicking()) Release((ArObject **) &result); return result; } argon::object::ArObject *argon::vm::Call(argon::object::ArObject *callable, int argc, ...) { ArObject **args; ArObject *result; va_list varargs; if ((args = (ArObject **) memory::Alloc(argc * sizeof(void *))) == nullptr) return Panic(error_out_of_memory); va_start(varargs, argc); for (int i = 0; i < argc; i++) args[i] = va_arg(varargs, ArObject*); va_end(varargs); result = Call(callable, argc, args); memory::Free(args); return result; } ArObject *argon::vm::GetLastError() { ArRoutine *routine = GetRoutine(); ArObject *err = nullptr; if (routine->panic != nullptr) err = RoutineRecover(routine); return err; } ArObject *argon::vm::Panic(ArObject *obj) { RoutineNewPanic(GetRoutine(), obj); return nullptr; } ArRoutine *argon::vm::GetRoutine() { if (ost_main != nullptr) return ost_main->routine; return ost_local->routine; } Context *argon::vm::GetContext() { return GetRoutine()->context; } bool argon::vm::AcquireMain() { if (ost_main == nullptr) return false; GetRoutine()->status = ArRoutineStatus::RUNNING; ost_worker_count++; return true; } bool argon::vm::IsPanicking() { return GetRoutine()->panic != nullptr; } bool argon::vm::Initialize() { vc_total = std::thread::hardware_concurrency(); if (vc_total == 0) vc_total = VCORE_DEFAULT; vc_idle_count = vc_total; // Initialize memory subsystem argon::memory::InitializeMemory(); if (!InitializeVCores()) goto ERROR; // Setup default OSThread if ((ost_main = AllocOST()) == nullptr) goto ERROR; // Initialize Main ArRoutine if ((ost_main->routine = RoutineNew(ArRoutineStatus::RUNNABLE)) == nullptr) goto ERROR; // Init Types if (!argon::object::TypesInit()) goto ERROR; // Initialize Main Context if ((ost_main->routine->context = ContextNew()) == nullptr) goto ERROR; return true; ERROR: if (ost_main != nullptr) { if (ost_main->routine != nullptr) { if (ost_main->routine->context != nullptr) ContextDel(ost_main->routine->context); RoutineDel(ost_main->routine); } FreeOST(ost_main); ost_main = nullptr; } vcores = nullptr; argon::memory::FinalizeMemory(); return false; } bool argon::vm::Shutdown() { short attempt = 10; // only the main thread can call shutdown! if (ost_main == nullptr) return false; should_stop = true; ost_cond.notify_all(); while (ost_total > 0 && attempt > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(600)); attempt--; } if (ost_total == 0) { ContextDel(ost_main->routine->context); RoutineDel(ost_main->routine); FreeOST(ost_main); ost_main = nullptr; argon::memory::FinalizeMemory(); return true; } return false; } void argon::vm::StopTheWorld() { std::unique_lock lck(stw_lock); if (stw) { if (ost_worker_count.fetch_sub(1) == 1) cond_stw.notify_one(); cond_stopwait.wait(lck, [] { return !stw; }); ost_worker_count++; } stw = true; if (ost_worker_count.fetch_sub(1) > 1) cond_stw.wait(lck, [] { return ost_worker_count == 0; }); assert(ost_worker_count >= 0); } void argon::vm::StartTheWorld() { stw = false; ost_worker_count++; cond_stopwait.notify_all(); } void argon::vm::STWCheckpoint() { std::unique_lock lck(stw_lock); if (!stw) return; if (ost_worker_count.fetch_sub(1) == 1) cond_stw.notify_one(); cond_stopwait.wait(lck, [] { return !stw; }); ost_worker_count++; } void OSTWakeRun() { std::unique_lock lck(ost_lock); OSThread *ost; if (ost_idle_count > 0) { ost_cond.notify_one(); return; } if (ost_total > OST_MAX) return; if ((ost = AllocOST()) == nullptr) { // TODO: Signal Error?! } lck.unlock(); StartOST(ost); } void argon::vm::ReleaseMain() { if (ost_main == nullptr) return; RoutineReset(GetRoutine(), ArRoutineStatus::RUNNABLE); ost_worker_count--; } void argon::vm::ReleaseQueue() { if (ost_local != nullptr) ReleaseVCore(); OSTWakeRun(); }
c++
code
12,536
2,717
#pragma once /* Bitmask ======= A generic implementation of the BitmaskType C++ concept http://en.cppreference.com/w/cpp/concept/BitmaskType Version: 1.1.2 Latest version and documentation: https://github.com/oliora/bitmask Copyright (c) 2016-2017 Andrey Upadyshev ([email protected]) Distributed under the Boost Software License, Version 1.0. See http://www.boost.org/LICENSE_1_0.txt Changes history --------------- v1.1.2: - Fix: Can not define bitmask for a class local enum (https://github.com/oliora/bitmask/issues/3) v1.1.1: - Added missed `<limits>` header - README and code comments updated v1.1: - Change namespace from `boost` to `bitmask` - Add CMake package https://github.com/oliora/bitmask/issues/1 v1.0: - Initial release */ #include <type_traits> #include <functional> // for std::hash #include <limits> // for std::numeric_limits #include <cassert> namespace bitmask { namespace bitmask_detail { // Let's use std::void_t. It's introduced in C++17 but we can easily add it by ourself // See more at http://en.cppreference.com/w/cpp/types/void_t template<typename... Ts> struct make_void { typedef void type;}; template<typename... Ts> using void_t = typename make_void<Ts...>::type; template<class T> struct underlying_type { static_assert(std::is_enum<T>::value, "T is not a enum type"); using type = typename std::make_unsigned<typename std::underlying_type<T>::type>::type; }; template<class T> using underlying_type_t = typename underlying_type<T>::type; template<class T, T MaxElement = T::_bitmask_max_element> struct mask_from_max_element { static constexpr underlying_type_t<T> max_element_value_ = static_cast<underlying_type_t<T>>(MaxElement); static_assert(max_element_value_ >= 0, "Max element is negative"); // If you really have to define a bitmask that uses the highest bit of signed type (i.e. the sign bit) then // define the value mask rather than the max element. static_assert(max_element_value_ <= (std::numeric_limits<typename std::underlying_type<T>::type>::max() >> 1) + 1, "Max element is greater than the underlying type's highest bit"); // `((value - 1) << 1) + 1` is used rather that simpler `(value << 1) - 1` // because latter overflows in case if `value` is the highest bit of the underlying type. static constexpr underlying_type_t<T> value = max_element_value_ ? ((max_element_value_ - 1) << 1) + 1 : 0; }; template<class, class = void_t<>> struct has_max_element : std::false_type {}; template<class T> struct has_max_element<T, void_t<decltype(T::_bitmask_max_element)>> : std::true_type {}; #if !defined(_MSC_VER) || (_MSC_VER >= 1900) template<class, class = void_t<>> struct has_value_mask : std::false_type {}; template<class T> struct has_value_mask<T, void_t<decltype(T::_bitmask_value_mask)>> : std::true_type {}; #else // Old MS Visual Studio has weird support for expressions SFINAE so I can't get a real check for `has_value_mask` to compile. template<class T> struct has_value_mask: std::integral_constant<bool, !has_max_element<T>::value> {}; #endif template<class T> struct is_valid_enum_definition : std::integral_constant<bool, !(has_value_mask<T>::value && has_max_element<T>::value)> {}; template<class, class = void> struct enum_mask; template<class T> struct enum_mask<T, typename std::enable_if<has_max_element<T>::value>::type> : std::integral_constant<underlying_type_t<T>, mask_from_max_element<T>::value> {}; template<class T> struct enum_mask<T, typename std::enable_if<has_value_mask<T>::value>::type> : std::integral_constant<underlying_type_t<T>, static_cast<underlying_type_t<T>>(T::_bitmask_value_mask)> {}; template<class T> inline constexpr underlying_type_t<T> disable_unused_function_warnings() noexcept { return (static_cast<T>(0) & static_cast<T>(0)).bits() & (static_cast<T>(0) | static_cast<T>(0)).bits() & (static_cast<T>(0) ^ static_cast<T>(0)).bits() & (~static_cast<T>(0)).bits() & bits(static_cast<T>(0)); } template<class Assert> inline void constexpr_assert_failed(Assert&& a) noexcept { a(); } // When evaluated at compile time emits a compilation error if condition is not true. // Invokes the standard assert at run time. #define bitmask_constexpr_assert(cond) \ ((void)((cond) ? 0 : (::bitmask::bitmask_detail::constexpr_assert_failed([](){ assert(!#cond);}), 0))) template<class T> inline constexpr T checked_value(T value, T mask) { return bitmask_constexpr_assert((value & ~mask) == 0), value; } } template<class T> inline constexpr bitmask_detail::underlying_type_t<T> get_enum_mask(const T&) noexcept { static_assert(bitmask_detail::is_valid_enum_definition<T>::value, "Both of _bitmask_max_element and _bitmask_value_mask are specified"); return bitmask_detail::enum_mask<T>::value; } template<class T> class bitmask { public: using value_type = T; using underlying_type = bitmask_detail::underlying_type_t<T>; static constexpr underlying_type mask_value = get_enum_mask(static_cast<value_type>(0)); constexpr bitmask() noexcept = default; constexpr bitmask(std::nullptr_t) noexcept: m_bits{0} {} constexpr bitmask(value_type value) noexcept : m_bits{bitmask_detail::checked_value(static_cast<underlying_type>(value), mask_value)} {} constexpr underlying_type bits() const noexcept { return m_bits; } constexpr explicit operator bool() const noexcept { return bits() ? true : false; } constexpr bitmask operator ~ () const noexcept { return bitmask{std::true_type{}, ~m_bits & mask_value}; } constexpr bitmask operator & (const bitmask& r) const noexcept { return bitmask{std::true_type{}, m_bits & r.m_bits}; } constexpr bitmask operator | (const bitmask& r) const noexcept { return bitmask{std::true_type{}, m_bits | r.m_bits}; } constexpr bitmask operator ^ (const bitmask& r) const noexcept { return bitmask{std::true_type{}, m_bits ^ r.m_bits}; } bitmask& operator |= (const bitmask& r) noexcept { m_bits |= r.m_bits; return *this; } bitmask& operator &= (const bitmask& r) noexcept { m_bits &= r.m_bits; return *this; } bitmask& operator ^= (const bitmask& r) noexcept { m_bits ^= r.m_bits; return *this; } private: template<class U> constexpr bitmask(std::true_type, U bits) noexcept : m_bits(static_cast<underlying_type>(bits)) {} underlying_type m_bits = 0; }; template<class T> inline constexpr bitmask<T> operator & (T l, const bitmask<T>& r) noexcept { return r & l; } template<class T> inline constexpr bitmask<T> operator | (T l, const bitmask<T>& r) noexcept { return r | l; } template<class T> inline constexpr bitmask<T> operator ^ (T l, const bitmask<T>& r) noexcept { return r ^ l; } template<class T> inline constexpr bool operator != (const bitmask<T>& l, const bitmask<T>& r) noexcept { return l.bits() != r.bits(); } template<class T> inline constexpr bool operator == (const bitmask<T>& l, const bitmask<T>& r) noexcept { return ! operator != (l, r); } template<class T> inline constexpr bool operator != (T l, const bitmask<T>& r) noexcept { return static_cast<bitmask_detail::underlying_type_t<T>>(l) != r.bits(); } template<class T> inline constexpr bool operator == (T l, const bitmask<T>& r) noexcept { return ! operator != (l, r); } template<class T> inline constexpr bool operator != (const bitmask<T>& l, T r) noexcept { return l.bits() != static_cast<bitmask_detail::underlying_type_t<T>>(r); } template<class T> inline constexpr bool operator == (const bitmask<T>& l, T r) noexcept { return ! operator != (l, r); } template<class T> inline constexpr bool operator != (const bitmask_detail::underlying_type_t<T>& l, const bitmask<T>& r) noexcept { return l != r.bits(); } template<class T> inline constexpr bool operator == (const bitmask_detail::underlying_type_t<T>& l, const bitmask<T>& r) noexcept { return ! operator != (l, r); } template<class T> inline constexpr bool operator != (const bitmask<T>& l, const bitmask_detail::underlying_type_t<T>& r) noexcept { return l.bits() != r; } template<class T> inline constexpr bool operator == (const bitmask<T>& l, const bitmask_detail::underlying_type_t<T>& r) noexcept { return ! operator != (l, r); } // Allow `bitmask` to be be used as a map key template<class T> inline constexpr bool operator < (const bitmask<T>& l, const bitmask<T>& r) noexcept { return l.bits() < r.bits(); } template<class T> inline constexpr bitmask_detail::underlying_type_t<T> bits(const bitmask<T>& bm) noexcept { return bm.bits(); } // Implementation template<class T> constexpr typename bitmask<T>::underlying_type bitmask<T>::mask_value; } namespace std { template<class T> struct hash<bitmask::bitmask<T>> { constexpr std::size_t operator() (const bitmask::bitmask<T>& op) const noexcept { using ut = typename bitmask::bitmask<T>::underlying_type; return std::hash<ut>{}(op.bits()); } }; } // Implementation detail macros #define BITMASK_DETAIL_CONCAT_IMPL(a, b) a##b #define BITMASK_DETAIL_CONCAT(a, b) BITMASK_DETAIL_CONCAT_IMPL(a, b) // Must be user-defined if compiler doesn't have `__COUNTER__` macro #ifndef BITMASK_MAKE_UNIQUE_NAME #define BITMASK_MAKE_UNIQUE_NAME(prefix) BITMASK_DETAIL_CONCAT(prefix, __COUNTER__) #endif #define BITMASK_DETAIL_DEFINE_OPS(value_type) \ inline constexpr bitmask::bitmask<value_type> operator & (value_type l, value_type r) noexcept { return bitmask::bitmask<value_type>{l} & r; } \ inline constexpr bitmask::bitmask<value_type> operator | (value_type l, value_type r) noexcept { return bitmask::bitmask<value_type>{l} | r; } \ inline constexpr bitmask::bitmask<value_type> operator ^ (value_type l, value_type r) noexcept { return bitmask::bitmask<value_type>{l} ^ r; } \ inline constexpr bitmask::bitmask<value_type> operator ~ (value_type op) noexcept { return ~bitmask::bitmask<value_type>{op}; } \ inline constexpr bitmask::bitmask<value_type>::underlying_type bits(value_type op) noexcept { return bitmask::bitmask<value_type>{op}.bits(); } \ namespace bitmask_definition_detail { \ class BITMASK_MAKE_UNIQUE_NAME(_disable_unused_function_warnings_) { \ static constexpr int _unused() noexcept { return bitmask::bitmask_detail::disable_unused_function_warnings<value_type>(), 0; } \ }; \ } #define BITMASK_DETAIL_DEFINE_VALUE_MASK(value_type, value_mask) \ inline constexpr bitmask::bitmask_detail::underlying_type_t<value_type> get_enum_mask(value_type) noexcept { \ return value_mask; \ } #define BITMASK_DETAIL_DEFINE_MAX_ELEMENT(value_type, max_element) \ inline constexpr bitmask::bitmask_detail::underlying_type_t<value_type> get_enum_mask(value_type) noexcept { \ return bitmask::bitmask_detail::mask_from_max_element<value_type, value_type::max_element>::value; \ } // Public macros // Defines missing operations for a bit-mask elements enum 'value_type' // Value mask is taken from 'value_type' definition. One should has either // '_bitmask_value_mask' or '_bitmask_max_element' element defined. #define BITMASK_DEFINE(value_type) \ BITMASK_DETAIL_DEFINE_OPS(value_type) // Defines missing operations and a value mask for // a bit-mask elements enum 'value_type' #define BITMASK_DEFINE_VALUE_MASK(value_type, value_mask) \ BITMASK_DETAIL_DEFINE_VALUE_MASK(value_type, value_mask) \ BITMASK_DETAIL_DEFINE_OPS(value_type) // Defines missing operations and a value mask based on max element for // a bit-mask elements enum 'value_type' #define BITMASK_DEFINE_MAX_ELEMENT(value_type, max_element) \ BITMASK_DETAIL_DEFINE_MAX_ELEMENT(value_type, max_element) \ BITMASK_DETAIL_DEFINE_OPS(value_type)
c++
code
13,512
2,694
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file Implementation of the PLY parser class */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER #include "PlyLoader.h" #include "fast_atof.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ PLY::EDataType PLY::Property::ParseDataType(const char* pCur,const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); PLY::EDataType eOut = PLY::EDT_INVALID; if (TokenMatch(pCur,"char",4) || TokenMatch(pCur,"int8",4)) { eOut = PLY::EDT_Char; } else if (TokenMatch(pCur,"uchar",5) || TokenMatch(pCur,"uint8",5)) { eOut = PLY::EDT_UChar; } else if (TokenMatch(pCur,"short",5) || TokenMatch(pCur,"int16",5)) { eOut = PLY::EDT_Short; } else if (TokenMatch(pCur,"ushort",6) || TokenMatch(pCur,"uint16",6)) { eOut = PLY::EDT_UShort; } else if (TokenMatch(pCur,"int32",5) || TokenMatch(pCur,"int",3)) { eOut = PLY::EDT_Int; } else if (TokenMatch(pCur,"uint32",6) || TokenMatch(pCur,"uint",4)) { eOut = PLY::EDT_UInt; } else if (TokenMatch(pCur,"float",5) || TokenMatch(pCur,"float32",7)) { eOut = PLY::EDT_Float; } else if (TokenMatch(pCur,"double64",8) || TokenMatch(pCur,"double",6) || TokenMatch(pCur,"float64",7)) { eOut = PLY::EDT_Double; } if (PLY::EDT_INVALID == eOut) { DefaultLogger::get()->info("Found unknown data type in PLY file. This is OK"); } *pCurOut = pCur; return eOut; } // ------------------------------------------------------------------------------------------------ PLY::ESemantic PLY::Property::ParseSemantic(const char* pCur,const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); PLY::ESemantic eOut = PLY::EST_INVALID; if (TokenMatch(pCur,"red",3)) { eOut = PLY::EST_Red; } else if (TokenMatch(pCur,"green",5)) { eOut = PLY::EST_Green; } else if (TokenMatch(pCur,"blue",4)) { eOut = PLY::EST_Blue; } else if (TokenMatch(pCur,"alpha",5)) { eOut = PLY::EST_Alpha; } else if (TokenMatch(pCur,"vertex_index",12) || TokenMatch(pCur,"vertex_indices",14)) { eOut = PLY::EST_VertexIndex; } else if (TokenMatch(pCur,"material_index",14)) { eOut = PLY::EST_MaterialIndex; } else if (TokenMatch(pCur,"ambient_red",11)) { eOut = PLY::EST_AmbientRed; } else if (TokenMatch(pCur,"ambient_green",13)) { eOut = PLY::EST_AmbientGreen; } else if (TokenMatch(pCur,"ambient_blue",12)) { eOut = PLY::EST_AmbientBlue; } else if (TokenMatch(pCur,"ambient_alpha",13)) { eOut = PLY::EST_AmbientAlpha; } else if (TokenMatch(pCur,"diffuse_red",11)) { eOut = PLY::EST_DiffuseRed; } else if (TokenMatch(pCur,"diffuse_green",13)) { eOut = PLY::EST_DiffuseGreen; } else if (TokenMatch(pCur,"diffuse_blue",12)) { eOut = PLY::EST_DiffuseBlue; } else if (TokenMatch(pCur,"diffuse_alpha",13)) { eOut = PLY::EST_DiffuseAlpha; } else if (TokenMatch(pCur,"specular_red",12)) { eOut = PLY::EST_SpecularRed; } else if (TokenMatch(pCur,"specular_green",14)) { eOut = PLY::EST_SpecularGreen; } else if (TokenMatch(pCur,"specular_blue",13)) { eOut = PLY::EST_SpecularBlue; } else if (TokenMatch(pCur,"specular_alpha",14)) { eOut = PLY::EST_SpecularAlpha; } else if (TokenMatch(pCur,"opacity",7)) { eOut = PLY::EST_Opacity; } else if (TokenMatch(pCur,"specular_power",6)) { eOut = PLY::EST_PhongPower; } else if (TokenMatch(pCur,"r",1)) { eOut = PLY::EST_Red; } else if (TokenMatch(pCur,"g",1)) { eOut = PLY::EST_Green; } else if (TokenMatch(pCur,"b",1)) { eOut = PLY::EST_Blue; } // NOTE: Blender3D exports texture coordinates as s,t tuples else if (TokenMatch(pCur,"u",1) || TokenMatch(pCur,"s",1) || TokenMatch(pCur,"tx",2)) { eOut = PLY::EST_UTextureCoord; } else if (TokenMatch(pCur,"v",1) || TokenMatch(pCur,"t",1) || TokenMatch(pCur,"ty",2)) { eOut = PLY::EST_VTextureCoord; } else if (TokenMatch(pCur,"x",1)) { eOut = PLY::EST_XCoord; } else if (TokenMatch(pCur,"y",1)) { eOut = PLY::EST_YCoord; } else if (TokenMatch(pCur,"z",1)) { eOut = PLY::EST_ZCoord; } else if (TokenMatch(pCur,"nx",2)) { eOut = PLY::EST_XNormal; } else if (TokenMatch(pCur,"ny",2)) { eOut = PLY::EST_YNormal; } else if (TokenMatch(pCur,"nz",2)) { eOut = PLY::EST_ZNormal; } else { DefaultLogger::get()->info("Found unknown property semantic in file. This is ok"); SkipLine(&pCur); } *pCurOut = pCur; return eOut; } // ------------------------------------------------------------------------------------------------ bool PLY::Property::ParseProperty (const char* pCur, const char** pCurOut, PLY::Property* pOut) { ai_assert(NULL != pCur && NULL != pCurOut); // Forms supported: // "property float x" // "property list uchar int vertex_index" *pCurOut = pCur; // skip leading spaces if (!SkipSpaces(pCur,&pCur))return false; // skip the "property" string at the beginning if (!TokenMatch(pCur,"property",8)) { // seems not to be a valid property entry return false; } // get next word if (!SkipSpaces(pCur,&pCur))return false; if (TokenMatch(pCur,"list",4)) { pOut->bIsList = true; // seems to be a list. if(EDT_INVALID == (pOut->eFirstType = PLY::Property::ParseDataType(pCur, &pCur))) { // unable to parse list size data type SkipLine(pCur,&pCur); *pCurOut = pCur; return false; } if (!SkipSpaces(pCur,&pCur))return false; if(EDT_INVALID == (pOut->eType = PLY::Property::ParseDataType(pCur, &pCur))) { // unable to parse list data type SkipLine(pCur,&pCur); *pCurOut = pCur; return false; } } else { if(EDT_INVALID == (pOut->eType = PLY::Property::ParseDataType(pCur, &pCur))) { // unable to parse data type. Skip the property SkipLine(pCur,&pCur); *pCurOut = pCur; return false; } } if (!SkipSpaces(pCur,&pCur))return false; const char* szCur = pCur; pOut->Semantic = PLY::Property::ParseSemantic(pCur, &pCur); if (PLY::EST_INVALID == pOut->Semantic) { // store the name of the semantic uintptr_t iDiff = (uintptr_t)pCur - (uintptr_t)szCur; DefaultLogger::get()->info("Found unknown semantic in PLY file. This is OK"); pOut->szName = std::string(szCur,iDiff); } SkipSpacesAndLineEnd(pCur,&pCur); *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ PLY::EElementSemantic PLY::Element::ParseSemantic(const char* pCur, const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); PLY::EElementSemantic eOut = PLY::EEST_INVALID; if (TokenMatch(pCur,"vertex",6)) { eOut = PLY::EEST_Vertex; } else if (TokenMatch(pCur,"face",4)) { eOut = PLY::EEST_Face; } #if 0 // TODO: maybe implement this? else if (TokenMatch(pCur,"range_grid",10)) { eOut = PLY::EEST_Face; } #endif else if (TokenMatch(pCur,"tristrips",9)) { eOut = PLY::EEST_TriStrip; } else if (TokenMatch(pCur,"edge",4)) { eOut = PLY::EEST_Edge; } else if (TokenMatch(pCur,"material",8)) { eOut = PLY::EEST_Material; } *pCurOut = pCur; return eOut; } // ------------------------------------------------------------------------------------------------ bool PLY::Element::ParseElement (const char* pCur, const char** pCurOut, PLY::Element* pOut) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != pOut); // Example format: "element vertex 8" *pCurOut = pCur; // skip leading spaces if (!SkipSpaces(&pCur))return false; // skip the "element" string at the beginning if (!TokenMatch(pCur,"element",7)) { // seems not to be a valid property entry return false; } // get next word if (!SkipSpaces(&pCur))return false; // parse the semantic of the element const char* szCur = pCur; pOut->eSemantic = PLY::Element::ParseSemantic(pCur,&pCur); if (PLY::EEST_INVALID == pOut->eSemantic) { // if the exact semantic can't be determined, just store // the original string identifier uintptr_t iDiff = (uintptr_t)pCur - (uintptr_t)szCur; pOut->szName = std::string(szCur,iDiff); } if (!SkipSpaces(&pCur))return false; //parse the number of occurences of this element pOut->NumOccur = strtoul10(pCur,&pCur); // go to the next line SkipSpacesAndLineEnd(pCur,&pCur); // now parse all properties of the element while(true) { // skip all comments PLY::DOM::SkipComments(pCur,&pCur); PLY::Property prop; if(!PLY::Property::ParseProperty(pCur,&pCur,&prop))break; pOut->alProperties.push_back(prop); } *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::SkipComments (const char* pCur, const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); *pCurOut = pCur; // skip spaces if (!SkipSpaces(pCur,&pCur))return false; if (TokenMatch(pCur,"comment",7)) { SkipLine(pCur,&pCur); SkipComments(pCur,&pCur); *pCurOut = pCur; return true; } *pCurOut = pCur; return false; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::ParseHeader (const char* pCur,const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); DefaultLogger::get()->debug("PLY::DOM::ParseHeader() begin"); // after ply and format line *pCurOut = pCur; // parse all elements while (true) { // skip all comments PLY::DOM::SkipComments(pCur,&pCur); PLY::Element out; if(PLY::Element::ParseElement(pCur,&pCur,&out)) { // add the element to the list of elements alElements.push_back(out); } else if (TokenMatch(pCur,"end_header",10)) { // we have reached the end of the header break; } else { // ignore unknown header elements SkipLine(&pCur); } } SkipSpacesAndLineEnd(pCur,&pCur); *pCurOut = pCur; DefaultLogger::get()->debug("PLY::DOM::ParseHeader() succeeded"); return true; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::ParseElementInstanceLists ( const char* pCur, const char** pCurOut) { ai_assert(NULL != pCur && NULL != pCurOut); DefaultLogger::get()->debug("PLY::DOM::ParseElementInstanceLists() begin"); *pCurOut = pCur; alElementData.resize(alElements.size()); std::vector<PLY::Element>::const_iterator i = alElements.begin(); std::vector<PLY::ElementInstanceList>::iterator a = alElementData.begin(); // parse all element instances for (;i != alElements.end();++i,++a) { (*a).alInstances.resize((*i).NumOccur); PLY::ElementInstanceList::ParseInstanceList(pCur,&pCur,&(*i),&(*a)); } DefaultLogger::get()->debug("PLY::DOM::ParseElementInstanceLists() succeeded"); *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::ParseElementInstanceListsBinary ( const char* pCur, const char** pCurOut, bool p_bBE) { ai_assert(NULL != pCur && NULL != pCurOut); DefaultLogger::get()->debug("PLY::DOM::ParseElementInstanceListsBinary() begin"); *pCurOut = pCur; alElementData.resize(alElements.size()); std::vector<PLY::Element>::const_iterator i = alElements.begin(); std::vector<PLY::ElementInstanceList>::iterator a = alElementData.begin(); // parse all element instances for (;i != alElements.end();++i,++a) { (*a).alInstances.resize((*i).NumOccur); PLY::ElementInstanceList::ParseInstanceListBinary(pCur,&pCur,&(*i),&(*a),p_bBE); } DefaultLogger::get()->debug("PLY::DOM::ParseElementInstanceListsBinary() succeeded"); *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::ParseInstanceBinary (const char* pCur,DOM* p_pcOut,bool p_bBE) { ai_assert(NULL != pCur && NULL != p_pcOut); DefaultLogger::get()->debug("PLY::DOM::ParseInstanceBinary() begin"); if(!p_pcOut->ParseHeader(pCur,&pCur)) { DefaultLogger::get()->debug("PLY::DOM::ParseInstanceBinary() failure"); return false; } if(!p_pcOut->ParseElementInstanceListsBinary(pCur,&pCur,p_bBE)) { DefaultLogger::get()->debug("PLY::DOM::ParseInstanceBinary() failure"); return false; } DefaultLogger::get()->debug("PLY::DOM::ParseInstanceBinary() succeeded"); return true; } // ------------------------------------------------------------------------------------------------ bool PLY::DOM::ParseInstance (const char* pCur,DOM* p_pcOut) { ai_assert(NULL != pCur); ai_assert(NULL != p_pcOut); DefaultLogger::get()->debug("PLY::DOM::ParseInstance() begin"); if(!p_pcOut->ParseHeader(pCur,&pCur)) { DefaultLogger::get()->debug("PLY::DOM::ParseInstance() failure"); return false; } if(!p_pcOut->ParseElementInstanceLists(pCur,&pCur)) { DefaultLogger::get()->debug("PLY::DOM::ParseInstance() failure"); return false; } DefaultLogger::get()->debug("PLY::DOM::ParseInstance() succeeded"); return true; } // ------------------------------------------------------------------------------------------------ bool PLY::ElementInstanceList::ParseInstanceList ( const char* pCur, const char** pCurOut, const PLY::Element* pcElement, PLY::ElementInstanceList* p_pcOut) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != pcElement && NULL != p_pcOut); if (EEST_INVALID == pcElement->eSemantic || pcElement->alProperties.empty()) { // if the element has an unknown semantic we can skip all lines // However, there could be comments for (unsigned int i = 0; i < pcElement->NumOccur;++i) { PLY::DOM::SkipComments(pCur,&pCur); SkipLine(pCur,&pCur); } } else { // be sure to have enough storage for (unsigned int i = 0; i < pcElement->NumOccur;++i) { PLY::DOM::SkipComments(pCur,&pCur); PLY::ElementInstance::ParseInstance(pCur, &pCur,pcElement, &p_pcOut->alInstances[i]); } } *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::ElementInstanceList::ParseInstanceListBinary ( const char* pCur, const char** pCurOut, const PLY::Element* pcElement, PLY::ElementInstanceList* p_pcOut, bool p_bBE /* = false */) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != pcElement && NULL != p_pcOut); // we can add special handling code for unknown element semantics since // we can't skip it as a whole block (we don't know its exact size // due to the fact that lists could be contained in the property list // of the unknown element) for (unsigned int i = 0; i < pcElement->NumOccur;++i) { PLY::ElementInstance::ParseInstanceBinary(pCur, &pCur,pcElement, &p_pcOut->alInstances[i], p_bBE); } *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::ElementInstance::ParseInstance ( const char* pCur, const char** pCurOut, const PLY::Element* pcElement, PLY::ElementInstance* p_pcOut) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != pcElement && NULL != p_pcOut); if (!SkipSpaces(pCur, &pCur))return false; // allocate enough storage p_pcOut->alProperties.resize(pcElement->alProperties.size()); std::vector<PLY::PropertyInstance>::iterator i = p_pcOut->alProperties.begin(); std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin(); for (;i != p_pcOut->alProperties.end();++i,++a) { if(!(PLY::PropertyInstance::ParseInstance(pCur, &pCur,&(*a),&(*i)))) { DefaultLogger::get()->warn("Unable to parse property instance. " "Skipping this element instance"); // skip the rest of the instance SkipLine(pCur, &pCur); PLY::PropertyInstance::ValueUnion v = PLY::PropertyInstance::DefaultValue((*a).eType); (*i).avList.push_back(v); } } *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::ElementInstance::ParseInstanceBinary ( const char* pCur, const char** pCurOut, const PLY::Element* pcElement, PLY::ElementInstance* p_pcOut, bool p_bBE /* = false */) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != pcElement && NULL != p_pcOut); // allocate enough storage p_pcOut->alProperties.resize(pcElement->alProperties.size()); std::vector<PLY::PropertyInstance>::iterator i = p_pcOut->alProperties.begin(); std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin(); for (;i != p_pcOut->alProperties.end();++i,++a) { if(!(PLY::PropertyInstance::ParseInstanceBinary(pCur, &pCur,&(*a),&(*i),p_bBE))) { DefaultLogger::get()->warn("Unable to parse binary property instance. " "Skipping this element instance"); (*i).avList.push_back(PLY::PropertyInstance::DefaultValue((*a).eType)); } } *pCurOut = pCur; return true; } // ------------------------------------------------------------------------------------------------ bool PLY::PropertyInstance::ParseInstance (const char* pCur,const char** pCurOut, const PLY::Property* prop, PLY::PropertyInstance* p_pcOut) { ai_assert(NULL != pCur && NULL != pCurOut && NULL != prop && NULL != p_pcOut); *pCurOut = pCur; // skip spaces at the beginning if (!SkipSpaces(pCur, &pCur))return false; if (prop->bIsList) { // parse the number of elements in the list PLY::PropertyInstance::ValueUnion v; PLY::PropertyInstance::ParseValue(pCur, &pCur,prop->eFirstType,&v); // convert to unsigned int unsigned int iNum = PLY::PropertyInstance::ConvertTo<unsigned int>(v,prop->eFirstType); // parse all list elements p_pcOut
c++
code
20,000
5,628
// Copyright (c) 2012-2013 Plenluno All rights reserved. #include <gtest/gtest.h> #include <libj/js_array_buffer.h> #include <libj/js_data_view.h> namespace libj { TEST(GTestJsArrayBuffer, TestCreate) { JsArrayBuffer::Ptr a = JsArrayBuffer::create(); ASSERT_TRUE(!!a); ASSERT_FALSE(a->data()); a = JsArrayBuffer::create(1); ASSERT_TRUE(!!a); ASSERT_TRUE(!!a->data()); } TEST(GTestJsArrayBuffer, TestByteLength) { JsArrayBuffer::Ptr a = JsArrayBuffer::create(); ASSERT_EQ(0, a->byteLength()); a = JsArrayBuffer::create(100); ASSERT_EQ(100, a->byteLength()); } TEST(GTestJsArrayBuffer, TestSlice) { JsArrayBuffer::Ptr a = JsArrayBuffer::create(10); JsDataView::Ptr d = JsDataView::create(a); d->setUint8(5, 7); a = a->slice(4, 9); d = JsDataView::create(a); UByte b; ASSERT_TRUE(d->getUint8(1, &b)); ASSERT_EQ(7, b); } } // namespace libj
c++
code
919
247
// Copyright GHI Electronics, LLC // // 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 "AT91SAM9Rx64.h" #define AT91SAM9Rx64_RTC_TIMR_AM (0x0) #define AT91SAM9Rx64_RTC_TIMR_PM (0x1) #define AT91C_PMC_CSS (0x3 << 0) // Real Time Clock Register #define RTC_CR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x00))) #define RTC_TIMR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x08))) #define RTC_CALR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x0C))) #define RTC_TIMALR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x10))) #define RTC_CALALR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x14))) #define RTC_SR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x18))) #define RTC_SCCR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x1C))) #define RTC_VER (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_RTCC + 0x2C))) // Real TimeOut #define RTC_TIMEOUT (0x00FFFFFF) //Slow Clock Configuration Register #define SCKCR_SCKCR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_SCKCR + 0x0))) //Power Manager Control Register #define PMC_MCKR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_PMC + 0x0030))) #define PMC_SR (*(reinterpret_cast<volatile uint32_t*>(AT91C_BASE_PMC + 0x0068))) #define TOTAL_RTC_CONTROLLERS 1 static TinyCLR_Rtc_Controller rtcControllers[TOTAL_RTC_CONTROLLERS]; static TinyCLR_Api_Info rtcApi[TOTAL_RTC_CONTROLLERS]; const char* rtcApiNames[TOTAL_RTC_CONTROLLERS] = { "GHIElectronics.TinyCLR.NativeApis.AT91SAM9Rx64.RtcController\\0" }; void AT91SAM9Rx64_Rtc_AddApi(const TinyCLR_Api_Manager* apiManager) { for (auto i = 0; i < TOTAL_RTC_CONTROLLERS; i++) { rtcControllers[i].ApiInfo = &rtcApi[i]; rtcControllers[i].Acquire = &AT91SAM9Rx64_Rtc_Acquire; rtcControllers[i].Release = &AT91SAM9Rx64_Rtc_Release; rtcControllers[i].IsValid = &AT91SAM9Rx64_Rtc_IsValid; rtcControllers[i].GetTime = &AT91SAM9Rx64_Rtc_GetTime; rtcControllers[i].SetTime = &AT91SAM9Rx64_Rtc_SetTime; rtcApi[i].Author = "GHI Electronics, LLC"; rtcApi[i].Name = rtcApiNames[i]; rtcApi[i].Type = TinyCLR_Api_Type::RtcController; rtcApi[i].Version = 0; rtcApi[i].Implementation = &rtcControllers[i]; rtcApi[i].State = nullptr; apiManager->Add(apiManager, &rtcApi[i]); } apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::RtcController, rtcApi[0].Name); } void AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(uint32_t valueToConvert, uint32_t &tens, uint32_t &ones) { tens = valueToConvert / 10; ones = valueToConvert % 10; } uint32_t AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine(uint32_t tens, uint32_t ones) { uint32_t CombinedBinaryCodedDecimal = 0; CombinedBinaryCodedDecimal = tens * 10; CombinedBinaryCodedDecimal += ones; return CombinedBinaryCodedDecimal; } TinyCLR_Result AT91SAM9Rx64_Rtc_Acquire(const TinyCLR_Rtc_Controller* self) { if ((PMC_MCKR & AT91C_PMC_CSS) != 0) { volatile uint32_t dumpReg = SCKCR_SCKCR; //Enable the 32,768 Hz oscillator by setting the bit OSC32EN to 1. SCKCR_SCKCR |= (1 << 1); //Wait 32,768 Hz Startup Time for clock stabilization (software loop). AT91SAM9Rx64_Time_Delay(nullptr, 100000); //Switch from internal RC to 32,768 Hz oscillator by setting the bit OSCSEL to 1. SCKCR_SCKCR |= (1 << 3); //Wait 5 slow clock cycles for internal resynchronization. AT91SAM9Rx64_Time_Delay(nullptr, 100000); //Disable the RC oscillator by setting the bit RCEN to 0. SCKCR_SCKCR &= ~(1 << 0); dumpReg = SCKCR_SCKCR; dumpReg = PMC_SR; } return TinyCLR_Result::Success; } TinyCLR_Result AT91SAM9Rx64_Rtc_Release(const TinyCLR_Rtc_Controller* self) { return TinyCLR_Result::Success; } TinyCLR_Result AT91SAM9Rx64_Rtc_IsValid(const TinyCLR_Rtc_Controller* self, bool& value) { TinyCLR_Rtc_DateTime rtcNow; value = (AT91SAM9Rx64_Rtc_GetTime(self, rtcNow) == TinyCLR_Result::Success); if (rtcNow.Second >= 60 || rtcNow.Minute >= 60 || rtcNow.Hour >= 24 || rtcNow.DayOfMonth >= 32 || rtcNow.Month >= 13 || rtcNow.DayOfWeek >= 8) value = false; return TinyCLR_Result::Success; } TinyCLR_Result AT91SAM9Rx64_Rtc_GetTime(const TinyCLR_Rtc_Controller* self, TinyCLR_Rtc_DateTime& value) { uint32_t calenderRegister = RTC_CALR; uint32_t timeRegister = RTC_TIMR; uint32_t fullYear = 0; uint32_t hundredYear = 0; if (RTC_VER > 0) { // Valid Entry Register, detect any incorrect value this register will be not 0. return TinyCLR_Result::InvalidOperation; } else { if ((calenderRegister & 0x7F) == 0x19) fullYear = 1900; else if ((calenderRegister & 0x7F) == 0x20) fullYear = 2000; hundredYear = AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((calenderRegister & (0xFF << 8)) >> 8) >> 4), (((calenderRegister & (0xFF << 8)) >> 8) & 0xF)); value.Year = (uint32_t)(fullYear + hundredYear); value.Month = (uint32_t)AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((calenderRegister & (0x1F << 16)) >> 16) >> 4), (((calenderRegister & (0x1F << 16)) >> 16) & 0xF)); value.DayOfMonth = (uint32_t)AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((calenderRegister & (0x3F << 24)) >> 24) >> 4), (((calenderRegister & (0x3F << 24)) >> 24) & 0xF)); value.DayOfWeek = (uint32_t)AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((calenderRegister & (0x07 << 21)) >> 21) >> 4), (((calenderRegister & (0x07 << 21)) >> 21) & 0xF)); value.Hour = AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((timeRegister & (0x3F << 16)) >> 16) >> 4), (((timeRegister & (0x3F << 16)) >> 16) & 0xF)); if (((timeRegister & 0x400000) >> 22) == AT91SAM9Rx64_RTC_TIMR_PM) value.Hour = value.Hour + 12; else value.Hour = value.Hour; value.Minute = (uint32_t)AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine((((timeRegister & (0x7F << 8)) >> 8) >> 4), (((timeRegister & (0x7F << 8)) >> 8) & 0xF)); value.Second = (uint32_t)AT91SAM9Rx64_Rtc_BinaryCodedDecimalCombine(((timeRegister & 0x7F) >> 4), ((timeRegister & 0x7F) & 0xF)); value.Millisecond = 1; } return TinyCLR_Result::Success; } TinyCLR_Result AT91SAM9Rx64_Rtc_SetTime(const TinyCLR_Rtc_Controller* self, TinyCLR_Rtc_DateTime value) { uint32_t calenderRegister = 0; uint32_t timeRegister = 0; uint32_t lowerHundredYears = 0; uint32_t tens = 0; uint32_t ones = 0; uint32_t timeout = 0; if (RTC_VER > 0) { // Valid Entry Register, detect any incorrect value this register will be not 0. return TinyCLR_Result::InvalidOperation; } if ((value.Year < 1900) || (value.Year > 2099) || (value.Month < 1) || (value.Month > 12) || (value.DayOfMonth < 1) || (value.DayOfMonth > 31)) { return TinyCLR_Result::ArgumentInvalid; } RTC_CR = 0x2; while ((RTC_SR & 0x1) == 0); while ((RTC_SR & 0x4) == 0); if (value.Year < 2000) { calenderRegister |= ((0x1 << 4) | 0x9); lowerHundredYears = value.Year - 1900; } else { calenderRegister |= ((0x2 << 4) | 0x0); lowerHundredYears = value.Year - 2000; } // Add value.Year AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(lowerHundredYears, tens, ones); calenderRegister |= (uint32_t)((tens << 12) | (ones << 8)); // Add value.Month AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(value.Month, tens, ones); calenderRegister |= (uint32_t)((tens << 20) | (ones << 16)); // Add dayOfWeek calenderRegister |= (uint32_t)(((value.DayOfWeek + 1) << 21)); // Add value.DayOfMonth AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(value.DayOfMonth, tens, ones); calenderRegister |= (uint32_t)((tens << 28) | (ones << 24)); AT91SAM9Rx64_Time_Delay(nullptr, 500000); // Write Calender to register RTC_CALR = calenderRegister; timeRegister = 0; RTC_CR |= (1 << 0); timeout = 0; while ((timeRegister & 0x1) == 0) { timeRegister = RTC_SR; if (timeout++ > RTC_TIMEOUT) return TinyCLR_Result::InvalidOperation; } timeout = 0; while (timeRegister != 0) { timeRegister = RTC_TIMR; RTC_TIMR = 0; if (timeout++ > RTC_TIMEOUT) return TinyCLR_Result::InvalidOperation; } // Add hour AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(value.Hour, tens, ones); timeRegister = (uint32_t)((AT91SAM9Rx64_RTC_TIMR_AM << 22) | (tens << 20) | (ones << 16)); RTC_TIMR = timeRegister; // Add value.Minute AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(value.Minute, tens, ones); timeRegister = (uint32_t)((tens << 12) | (ones << 8)); RTC_TIMR |= timeRegister; // Add value.Second AT91SAM9Rx64_Rtc_BinaryCodedDecimalExtract(value.Second, tens, ones); timeRegister = (uint32_t)((tens << 4) | ones); RTC_TIMR |= timeRegister; // Clear Status Register RTC_SCCR |= 1 << 2; RTC_CR &= ~((1 << 0) | (1 << 1)); return TinyCLR_Result::Success; }
c++
code
9,783
2,011
// Copyright 2012 the V8 project 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 "src/code-stubs.h" #include <memory> #include "src/bailout-reason.h" #include "src/code-factory.h" #include "src/crankshaft/hydrogen.h" #include "src/crankshaft/lithium.h" #include "src/field-index.h" #include "src/ic/ic.h" namespace v8 { namespace internal { static LChunk* OptimizeGraph(HGraph* graph) { DisallowHeapAllocation no_allocation; DisallowHandleAllocation no_handles; DisallowHandleDereference no_deref; DCHECK(graph != NULL); BailoutReason bailout_reason = kNoReason; if (!graph->Optimize(&bailout_reason)) { FATAL(GetBailoutReason(bailout_reason)); } LChunk* chunk = LChunk::NewChunk(graph); if (chunk == NULL) { FATAL(GetBailoutReason(graph->info()->bailout_reason())); } return chunk; } class CodeStubGraphBuilderBase : public HGraphBuilder { public: explicit CodeStubGraphBuilderBase(CompilationInfo* info, CodeStub* code_stub) : HGraphBuilder(info, code_stub->GetCallInterfaceDescriptor(), false), arguments_length_(NULL), info_(info), code_stub_(code_stub), descriptor_(code_stub), context_(NULL) { int parameter_count = GetParameterCount(); parameters_.reset(new HParameter*[parameter_count]); } virtual bool BuildGraph(); protected: virtual HValue* BuildCodeStub() = 0; int GetParameterCount() const { return descriptor_.GetParameterCount(); } int GetRegisterParameterCount() const { return descriptor_.GetRegisterParameterCount(); } HParameter* GetParameter(int parameter) { DCHECK(parameter < GetParameterCount()); return parameters_[parameter]; } Representation GetParameterRepresentation(int parameter) { return RepresentationFromMachineType( descriptor_.GetParameterType(parameter)); } bool IsParameterCountRegister(int index) const { return descriptor_.GetRegisterParameter(index) .is(descriptor_.stack_parameter_count()); } HValue* GetArgumentsLength() { // This is initialized in BuildGraph() DCHECK(arguments_length_ != NULL); return arguments_length_; } CompilationInfo* info() { return info_; } CodeStub* stub() { return code_stub_; } HContext* context() { return context_; } Isolate* isolate() { return info_->isolate(); } HLoadNamedField* BuildLoadNamedField(HValue* object, FieldIndex index); void BuildStoreNamedField(HValue* object, HValue* value, FieldIndex index, Representation representation, bool transition_to_field); HValue* BuildPushElement(HValue* object, HValue* argc, HValue* argument_elements, ElementsKind kind); HValue* BuildToString(HValue* input, bool convert); HValue* BuildToPrimitive(HValue* input, HValue* input_map); private: std::unique_ptr<HParameter* []> parameters_; HValue* arguments_length_; CompilationInfo* info_; CodeStub* code_stub_; CodeStubDescriptor descriptor_; HContext* context_; }; bool CodeStubGraphBuilderBase::BuildGraph() { // Update the static counter each time a new code stub is generated. isolate()->counters()->code_stubs()->Increment(); if (FLAG_trace_hydrogen_stubs) { const char* name = CodeStub::MajorName(stub()->MajorKey()); PrintF("-----------------------------------------------------------\n"); PrintF("Compiling stub %s using hydrogen\n", name); isolate()->GetHTracer()->TraceCompilation(info()); } int param_count = GetParameterCount(); int register_param_count = GetRegisterParameterCount(); HEnvironment* start_environment = graph()->start_environment(); HBasicBlock* next_block = CreateBasicBlock(start_environment); Goto(next_block); next_block->SetJoinId(BailoutId::StubEntry()); set_current_block(next_block); bool runtime_stack_params = descriptor_.stack_parameter_count().is_valid(); HInstruction* stack_parameter_count = NULL; for (int i = 0; i < param_count; ++i) { Representation r = GetParameterRepresentation(i); HParameter* param; if (i >= register_param_count) { param = Add<HParameter>(i - register_param_count, HParameter::STACK_PARAMETER, r); } else { param = Add<HParameter>(i, HParameter::REGISTER_PARAMETER, r); } start_environment->Bind(i, param); parameters_[i] = param; if (i < register_param_count && IsParameterCountRegister(i)) { param->set_type(HType::Smi()); stack_parameter_count = param; arguments_length_ = stack_parameter_count; } } DCHECK(!runtime_stack_params || arguments_length_ != NULL); if (!runtime_stack_params) { stack_parameter_count = Add<HConstant>(param_count - register_param_count - 1); // graph()->GetConstantMinus1(); arguments_length_ = graph()->GetConstant0(); } context_ = Add<HContext>(); start_environment->BindContext(context_); start_environment->Bind(param_count, context_); Add<HSimulate>(BailoutId::StubEntry()); NoObservableSideEffectsScope no_effects(this); HValue* return_value = BuildCodeStub(); // We might have extra expressions to pop from the stack in addition to the // arguments above. HInstruction* stack_pop_count = stack_parameter_count; if (descriptor_.function_mode() == JS_FUNCTION_STUB_MODE) { if (!stack_parameter_count->IsConstant() && descriptor_.hint_stack_parameter_count() < 0) { HInstruction* constant_one = graph()->GetConstant1(); stack_pop_count = AddUncasted<HAdd>(stack_parameter_count, constant_one); stack_pop_count->ClearFlag(HValue::kCanOverflow); // TODO(mvstanton): verify that stack_parameter_count+1 really fits in a // smi. } else { int count = descriptor_.hint_stack_parameter_count(); stack_pop_count = Add<HConstant>(count); } } if (current_block() != NULL) { HReturn* hreturn_instruction = New<HReturn>(return_value, stack_pop_count); FinishCurrentBlock(hreturn_instruction); } return true; } template <class Stub> class CodeStubGraphBuilder: public CodeStubGraphBuilderBase { public: explicit CodeStubGraphBuilder(CompilationInfo* info, CodeStub* stub) : CodeStubGraphBuilderBase(info, stub) {} typedef typename Stub::Descriptor Descriptor; protected: virtual HValue* BuildCodeStub() { if (casted_stub()->IsUninitialized()) { return BuildCodeUninitializedStub(); } else { return BuildCodeInitializedStub(); } } virtual HValue* BuildCodeInitializedStub() { UNIMPLEMENTED(); return NULL; } virtual HValue* BuildCodeUninitializedStub() { // Force a deopt that falls back to the runtime. HValue* undefined = graph()->GetConstantUndefined(); IfBuilder builder(this); builder.IfNot<HCompareObjectEqAndBranch, HValue*>(undefined, undefined); builder.Then(); builder.ElseDeopt(DeoptimizeReason::kForcedDeoptToRuntime); return undefined; } Stub* casted_stub() { return static_cast<Stub*>(stub()); } }; Handle<Code> HydrogenCodeStub::GenerateLightweightMissCode( ExternalReference miss) { Factory* factory = isolate()->factory(); // Generate the new code. MacroAssembler masm(isolate(), NULL, 256, CodeObjectRequired::kYes); { // Update the static counter each time a new code stub is generated. isolate()->counters()->code_stubs()->Increment(); // Generate the code for the stub. masm.set_generating_stub(true); // TODO(yangguo): remove this once we can serialize IC stubs. masm.enable_serializer(); NoCurrentFrameScope scope(&masm); GenerateLightweightMiss(&masm, miss); } // Create the code object. CodeDesc desc; masm.GetCode(&desc); // Copy the generated code into a heap object. Handle<Code> new_object = factory->NewCode( desc, GetCodeFlags(), masm.CodeObject(), NeedsImmovableCode()); return new_object; } Handle<Code> HydrogenCodeStub::GenerateRuntimeTailCall( CodeStubDescriptor* descriptor) { const char* name = CodeStub::MajorName(MajorKey()); Zone zone(isolate()->allocator(), ZONE_NAME); CallInterfaceDescriptor interface_descriptor(GetCallInterfaceDescriptor()); CodeStubAssembler assembler(isolate(), &zone, interface_descriptor, GetCodeFlags(), name); int total_params = interface_descriptor.GetStackParameterCount() + interface_descriptor.GetRegisterParameterCount(); switch (total_params) { case 0: assembler.TailCallRuntime(descriptor->miss_handler_id(), assembler.Parameter(0)); break; case 1: assembler.TailCallRuntime(descriptor->miss_handler_id(), assembler.Parameter(1), assembler.Parameter(0)); break; case 2: assembler.TailCallRuntime(descriptor->miss_handler_id(), assembler.Parameter(2), assembler.Parameter(0), assembler.Parameter(1)); break; case 3: assembler.TailCallRuntime(descriptor->miss_handler_id(), assembler.Parameter(3), assembler.Parameter(0), assembler.Parameter(1), assembler.Parameter(2)); break; case 4: assembler.TailCallRuntime(descriptor->miss_handler_id(), assembler.Parameter(4), assembler.Parameter(0), assembler.Parameter(1), assembler.Parameter(2), assembler.Parameter(3)); break; default: UNIMPLEMENTED(); break; } return assembler.GenerateCode(); } template <class Stub> static Handle<Code> DoGenerateCode(Stub* stub) { Isolate* isolate = stub->isolate(); CodeStubDescriptor descriptor(stub); if (FLAG_minimal && descriptor.has_miss_handler()) { return stub->GenerateRuntimeTailCall(&descriptor); } // If we are uninitialized we can use a light-weight stub to enter // the runtime that is significantly faster than using the standard // stub-failure deopt mechanism. if (stub->IsUninitialized() && descriptor.has_miss_handler()) { DCHECK(!descriptor.stack_parameter_count().is_valid()); return stub->GenerateLightweightMissCode(descriptor.miss_handler()); } base::ElapsedTimer timer; if (FLAG_profile_hydrogen_code_stub_compilation) { timer.Start(); } Zone zone(isolate->allocator(), ZONE_NAME); CompilationInfo info(CStrVector(CodeStub::MajorName(stub->MajorKey())), isolate, &zone, stub->GetCodeFlags()); // Parameter count is number of stack parameters. int parameter_count = descriptor.GetStackParameterCount(); if (descriptor.function_mode() == NOT_JS_FUNCTION_STUB_MODE) { parameter_count--; } info.set_parameter_count(parameter_count); CodeStubGraphBuilder<Stub> builder(&info, stub); LChunk* chunk = OptimizeGraph(builder.CreateGraph()); Handle<Code> code = chunk->Codegen(); if (FLAG_profile_hydrogen_code_stub_compilation) { OFStream os(stdout); os << "[Lazy compilation of " << stub << " took " << timer.Elapsed().InMillisecondsF() << " ms]" << std::endl; } return code; } HValue* CodeStubGraphBuilderBase::BuildPushElement(HValue* object, HValue* argc, HValue* argument_elements, ElementsKind kind) { // Precheck whether all elements fit into the array. if (!IsFastObjectElementsKind(kind)) { LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement); HValue* start = graph()->GetConstant0(); HValue* key = builder.BeginBody(start, argc, Token::LT); { HInstruction* argument = Add<HAccessArgumentsAt>(argument_elements, argc, key); IfBuilder can_store(this); can_store.IfNot<HIsSmiAndBranch>(argument); if (IsFastDoubleElementsKind(kind)) { can_store.And(); can_store.IfNot<HCompareMap>(argument, isolate()->factory()->heap_number_map()); } can_store.ThenDeopt(DeoptimizeReason::kFastPathFailed); can_store.End(); } builder.EndBody(); } HValue* length = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForArrayLength(kind)); HValue* new_length = AddUncasted<HAdd>(length, argc); HValue* max_key = AddUncasted<HSub>(new_length, graph()->GetConstant1()); HValue* elements = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForElementsPointer()); elements = BuildCheckForCapacityGrow(object, elements, kind, length, max_key, true, STORE); LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement); HValue* start = graph()->GetConstant0(); HValue* key = builder.BeginBody(start, argc, Token::LT); { HValue* argument = Add<HAccessArgumentsAt>(argument_elements, argc, key); HValue* index = AddUncasted<HAdd>(key, length); AddElementAccess(elements, index, argument, object, nullptr, kind, STORE); } builder.EndBody(); return new_length; } template <> HValue* CodeStubGraphBuilder<FastArrayPushStub>::BuildCodeStub() { // TODO(verwaest): Fix deoptimizer messages. HValue* argc = GetArgumentsLength(); HInstruction* argument_elements = Add<HArgumentsElements>(false, false); HInstruction* object = Add<HAccessArgumentsAt>(argument_elements, argc, graph()->GetConstantMinus1()); BuildCheckHeapObject(object); HValue* map = Add<HLoadNamedField>(object, nullptr, HObjectAccess::ForMap()); Add<HCheckInstanceType>(object, HCheckInstanceType::IS_JS_ARRAY); // Disallow pushing onto prototypes. It might be the JSArray prototype. // Disallow pushing onto non-extensible objects. { HValue* bit_field2 = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2()); HValue* mask = Add<HConstant>(static_cast<int>(Map::IsPrototypeMapBits::kMask) | (1 << Map::kIsExtensible)); HValue* bits = AddUncasted<HBitwise>(Token::BIT_AND, bit_field2, mask); IfBuilder check(this); check.If<HCompareNumericAndBranch>( bits, Add<HConstant>(1 << Map::kIsExtensible), Token::NE); check.ThenDeopt(DeoptimizeReason::kFastPathFailed); check.End(); } // Disallow pushing onto arrays in dictionary named property mode. We need to // figure out whether the length property is still writable. { HValue* bit_field3 = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField3()); HValue* mask = Add<HConstant>(static_cast<int>(Map::DictionaryMap::kMask)); HValue* bit = AddUncasted<HBitwise>(Token::BIT_AND, bit_field3, mask); IfBuilder check(this); check.If<HCompareNumericAndBranch>(bit, mask, Token::EQ); check.ThenDeopt(DeoptimizeReason::kFastPathFailed); check.End(); } // Check whether the length property is writable. The length property is the // only default named property on arrays. It's nonconfigurable, hence is // guaranteed to stay the first property. { HValue* descriptors = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapDescriptors()); HValue* details = Add<HLoadKeyed>( descriptors, Add<HConstant>(DescriptorArray::ToDetailsIndex(0)), nullptr, nullptr, FAST_SMI_ELEMENTS); HValue* mask = Add<HConstant>(READ_ONLY << PropertyDetails::AttributesField::kShift); HValue* bit = AddUncasted<HBitwise>(Token::BIT_AND, details, mask); IfBuilder readonly(this); readonly.If<HCompareNumericAndBranch>(bit, mask, Token::EQ); readonly.ThenDeopt(DeoptimizeReason::kFastPathFailed); readonly.End(); } HValue* null = Add<HLoadRoot>(Heap::kNullValueRootIndex); HValue* empty = Add<HLoadRoot>(Heap::kEmptyFixedArrayRootIndex); environment()->Push(map); LoopBuilder check_prototypes(this); check_prototypes.BeginBody(1); { HValue* parent_map = environment()->Pop(); HValue* prototype = Add<HLoadNamedField>(parent_map, nullptr, HObjectAccess::ForPrototype()); IfBuilder is_null(this); is_null.If<HCompareObjectEqAndBranch>(prototype, null); is_null.Then(); check_prototypes.Break(); is_null.End(); HValue* prototype_map = Add<HLoadNamedField>(prototype, nullptr, HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>( prototype_map, nullptr, HObjectAccess::ForMapInstanceType()); IfBuilder check_instance_type(this); check_instance_type.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(LAST_CUSTOM_ELEMENTS_RECEIVER), Token::LTE); check_instance_type.ThenDeopt(DeoptimizeReason::kFastPathFailed); check_instance_type.End(); HValue* elements = Add<HLoadNamedField>( prototype, nullptr, HObjectAccess::ForElementsPointer()); IfBuilder no_elements(this); no_elements.IfNot<HCompareObjectEqAndBranch>(elements, empty); no_elements.ThenDeopt(DeoptimizeReason::kFastPathFailed); no_elements.End(); environment()->Push(prototype_map); } check_prototypes.EndBody(); HValue* bit_field2 = Add<HLoadNamedField>(map, nullptr, HObjectAccess::ForMapBitField2()); HValue* kind = BuildDecodeField<Map::ElementsKindBits>(bit_field2); // Below we only check the upper bound of the relevant ranges to include both // holey and non-holey versions. We check them in order smi, object, double // since smi < object < double. STATIC_ASSERT(FAST_SMI_ELEMENTS < FAST_HOLEY_SMI_ELEMENTS); STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS < FAST_HOLEY_ELEMENTS); STATIC_ASSERT(FAST_ELEMENTS < FAST_HOLEY_ELEMENTS); STATIC_ASSERT(FAST_HOLEY_ELEMENTS < FAST_HOLEY_DOUBLE_ELEMENTS); STATIC_ASSERT(FAST_DOUBLE_ELEMENTS < FAST_HOLEY_DOUBLE_ELEMENTS); IfBuilder has_smi_elements(this); has_smi_elements.If<HCompareNumericAndBranch>( kind, Add<HConstant>(FAST_HOLEY_SMI_ELEMENTS), Token::LTE); has_smi_elements.Then(); { HValue* new_length = BuildPushElement(object, argc, argument_elements, FAST_HOLEY_SMI_ELEMENTS); environment()->Push(new_length); } has_smi_elements.Else(); { IfBuilder has_object_elements(this); has_object_elements.If<HCompareNumericAndBranch>( kind, Add<HConstant>(FAST_HOLEY_ELEMENTS), Token::LTE); has_object_elements.Then(); { HValue* new_length = BuildPushElement(object, argc, argument_elements, FAST_HOLEY_ELEMENTS); environment()->Push(new_length); } has_object_elements.Else(); { IfBuilder has_double_elements(this); has_double_elements.If<HCompareNumericAndBranch>( kind, Add<HConstant>(FAST_HOLEY_DOUBLE_ELEMENTS), Token::LTE); has_double_elements.Then(); { HValue* new_length = BuildPushElement(object, argc, argument_elements, FAST_HOLEY_DOUBLE_ELEMENTS); environment()->Push(new_length); } has_double_elements.ElseDeopt(DeoptimizeReason::kFastPathFailed); has_double_elements.End(); } has_object_elements.End(); } has_smi_elements.End(); return environment()->Pop(); } Handle<Code> FastArrayPushStub::GenerateCode() { return DoGenerateCode(this); } template <> HValue* CodeStubGraphBuilder<FastFunctionBindStub>::BuildCodeStub() { // TODO(verwaest): Fix deoptimizer messages. HValue* argc = GetArgumentsLength(); HInstruction* argument_elements = Add<HArgumentsElements>(false, false); HInstruction* object = Add<HAccessArgumentsAt>(argument_elements, argc, g
c++
code
20,000
3,832
#include <cstddef> #include <gsl/gsl> #include <iostream> #include <limits> #include <vector> class BigScalar { public: std::vector<double> data{}; BigScalar(gsl::not_null<std::vector<double>*> initial_data, const double special_value) { (*initial_data)[4] = special_value; data = *initial_data; } BigScalar(std::vector<double>&& initial_data, const double special_value) { initial_data[4] = special_value; data = std::move(initial_data); } // ... lots of other features like doing math with scalars }; // template <size_t Size> // std::array<double, Size + 1> append_to_array( // std::array<double, Size>&& input_array, double new_value) { // std::array<double, Size + 1> new_array{}; // // for loop to fill in the old values // for (...) { // gsl::at(new_array, i) = gsl::at(old_array, i); // } // new_array[Size] = new_value; // return new_array; // } int main() { constexpr auto size = 100000; constexpr double special_value = 4.0; std::vector<double> test_vector{}; test_vector.resize(size); for (double& element : test_vector) { element = 5.0; } // BigScalar big_scalar{gsl::make_not_null(&test_vector), special_value}; BigScalar big_scalar{std::move(test_vector), special_value}; // std::cout << test_vector[4] << "\n"; std::cout << gsl::at(big_scalar.data, size / 2) << "\n"; std::cout << big_scalar.data[4] << "\n"; double x = std::numeric_limits<double>::signaling_NaN(); // x = 7; std::cout << x + big_scalar.data[4] << "\n"; /* tnsr::I<double, 3, Frame::Inertial> x; tnsr::I<double, 3, Frame::Inertial> y; double dot_product = get<0>(x) * get<0>(y); */ return 0; }
c++
code
1,693
464
#include "../include/UCTSearch.h" using namespace SparCraft; UCTSearch::UCTSearch(const UCTSearchParameters & params) : _params(params) , _memoryPool(NULL) { for (size_t p(0); p<Constants::Num_Players; ++p) { // set ordered move script player objects for (size_t s(0); s<_params.getOrderedMoveScripts().size(); ++s) { _allScripts[p].push_back(AllPlayers::getPlayerPtr(p, _params.getOrderedMoveScripts()[s])); } // set player model objects if (_params.playerModel(p) != PlayerModels::None) { _playerModels[p] = AllPlayers::getPlayerPtr(p, _params.playerModel(p)); } } } void UCTSearch::setMemoryPool(UCTMemoryPool * pool) { _memoryPool = pool; } void UCTSearch::doSearch(GameState & initialState, std::vector<Action> & move) { Timer t; t.start(); _rootNode = UCTNode(NULL, Players::Player_None, SearchNodeType::RootNode, _actionVec, _params.maxChildren(), _memoryPool ? _memoryPool->alloc() : NULL); // do the required number of traversals for (size_t traversals(0); traversals < _params.maxTraversals(); ++traversals) { GameState state(initialState); traverse(_rootNode, state); if (traversals && (traversals % 5 == 0)) { if (_params.timeLimit() && (t.getElapsedTimeInMilliSec() >= _params.timeLimit())) { break; } } _results.traversals++; //printSubTree(_rootNode, initialState, "__uct.txt"); //system("\"C:\\Program Files (x86)\\Graphviz2.30\\bin\\dot.exe\" < __uct.txt -Tpng > uct.png"); } // choose the move to return if (_params.rootMoveSelectionMethod() == UCTMoveSelect::HighestValue) { move = _rootNode.bestUCTValueChild(true, _params).getMove(); } else if (_params.rootMoveSelectionMethod() == UCTMoveSelect::MostVisited) { move = _rootNode.mostVisitedChild().getMove(); } if (_params.graphVizFilename().length() > 0) { //printSubTree(_rootNode, initialState, _params.graphVizFilename()); //system("\"C:\\Program Files (x86)\\Graphviz2.30\\bin\\dot.exe\" < __uct.txt -Tpng > uct.png"); } double ms = t.getElapsedTimeInMilliSec(); _results.timeElapsed = ms; //printf("Search took %lf ms\n", ms); //printf("Hello\n"); } const bool UCTSearch::searchTimeOut() { return (_params.timeLimit() && (_searchTimer.getElapsedTimeInMilliSec() >= _params.timeLimit())); } const bool UCTSearch::terminalState(GameState & state, const size_t & depth) const { return (depth <= 0 || state.isTerminal()); } void UCTSearch::generateOrderedMoves(GameState & state, MoveArray & moves, const IDType & playerToMove) { _orderedMoves.clear(); // if we are using opponent modeling, get the move and then return, we don't want to put any more moves in if (_params.playerModel(playerToMove) != PlayerModels::None) { // put the vector into the ordered moves array _orderedMoves.add(std::vector<Action>()); // generate the moves into that vector _playerModels[playerToMove]->getMoves(state, moves, _orderedMoves[0]); return; } // if we are using script move ordering, insert the script moves we want if (_params.moveOrderingMethod() == MoveOrderMethod::ScriptFirst) { for (size_t s(0); s<_params.getOrderedMoveScripts().size(); s++) { std::vector<Action> moveVec; _allScripts[playerToMove][s]->getMoves(state, moves, moveVec); _orderedMoves.add(moveVec); } } } const size_t UCTSearch::getChildNodeType(UCTNode & parent, const GameState & prevState) const { if (!prevState.bothCanMove()) { return SearchNodeType::SoloNode; } else { if (parent.getNodeType() == SearchNodeType::RootNode) { return SearchNodeType::FirstSimNode; } else if (parent.getNodeType() == SearchNodeType::SoloNode) { return SearchNodeType::FirstSimNode; } else if (parent.getNodeType() == SearchNodeType::SecondSimNode) { return SearchNodeType::FirstSimNode; } else if (parent.getNodeType() == SearchNodeType::FirstSimNode) { return SearchNodeType::SecondSimNode; } } return SearchNodeType::Default; } const bool UCTSearch::getNextMove(IDType playerToMove, MoveArray & moves, const size_t & moveNumber, std::vector<Action> & actionVec) { if (moveNumber > _params.maxChildren()) { return false; } // if this move is beyond the first, check to see if we are only using a single move if (moveNumber == 1) { // if we are player modeling, we should have only generated the first move if (_params.playerModel(playerToMove) != PlayerModels::None) { // so return false return false; } } actionVec.clear(); // if this move should be from the ordered list, return it from the list if (moveNumber < _orderedMoves.size()) { actionVec.assign(_orderedMoves[moveNumber].begin(), _orderedMoves[moveNumber].end()); return true; } // otherwise return the next move vector starting from the beginning else { if (moves.hasMoreMoves()) { moves.getNextMoveVec(actionVec); return true; } else { return false; } } } const IDType UCTSearch::getPlayerToMove(UCTNode & node, const GameState & state) const { const IDType whoCanMove(state.whoCanMove()); // if both players can move if (whoCanMove == Players::Player_Both) { // pick the first move based on our policy const IDType policy(_params.playerToMoveMethod()); const IDType maxPlayer(_params.maxPlayer()); // the max player always chooses at the root if (isRoot(node)) { return maxPlayer; } // the type of node this is const IDType nodeType = node.getNodeType(); // the 2nd player in a sim move is always the enemy of the first if (nodeType == SearchNodeType::FirstSimNode) { return state.getEnemy(node.getPlayer()); } // otherwise use our policy to see who goes first in a sim move state else { if (policy == SparCraft::PlayerToMove::Alternate) { return state.getEnemy(node.getPlayer()); } else if (policy == SparCraft::PlayerToMove::Not_Alternate) { return node.getPlayer(); } else if (policy == SparCraft::PlayerToMove::Random) { return rand() % 2; } // we should never get to this state System::FatalError("UCT Error: Nobody can move for some reason"); return Players::Player_None; } } else { return whoCanMove; } } UCTNode & UCTSearch::UCTNodeSelect(UCTNode & parent) { UCTNode * bestNode = NULL; bool maxPlayer = isRoot(parent) || (parent.getChild(0).getPlayer() == _params.maxPlayer()); double bestVal = maxPlayer ? std::numeric_limits<double>::min() : std::numeric_limits<double>::max(); // loop through each child to find the best node for (size_t c(0); c < parent.numChildren(); ++c) { UCTNode & child = parent.getChild(c); double currentVal(0); // if we have visited this node already, get its UCT value if (child.numVisits() > 0) { double winRate = (double)child.numWins() / (double)child.numVisits(); double uctVal = _params.cValue() * sqrt( log( (double)parent.numVisits() ) / ( child.numVisits() ) ); currentVal = maxPlayer ? (winRate + uctVal) : (winRate - uctVal); child.setUCTVal(currentVal); } else { // if we haven't visited it yet, return it and visit immediately return child; } // choose the best node depending on max or min player if (maxPlayer) { if (currentVal > bestVal) { bestVal = currentVal; bestNode = &child; } } else if (currentVal < bestVal) { bestVal = currentVal; bestNode = &child; } } return *bestNode; } void UCTSearch::updateState(UCTNode & node, GameState & state, bool isLeaf) { // if it's the first sim move with children, or the root node if ((node.getNodeType() != SearchNodeType::FirstSimNode) || isLeaf) { // if this is a second sim node if (node.getNodeType() == SearchNodeType::SecondSimNode) { // make the parent's moves on the state because they haven't been done yet state.makeMoves(node.getParent()->getMove()); } // do the current node moves and call finished moving state.makeMoves(node.getMove()); state.finishedMoving(); } } StateEvalScore UCTSearch::traverse(UCTNode & node, GameState & currentState) { StateEvalScore playoutVal; _results.totalVisits++; // if we haven't visited this node yet, do a playout if (node.numVisits() == 0) { // update the status of the current state with this node's moves //updateState(node, currentState, !node.hasChildren()); updateState(node, currentState, true); // do the playout playoutVal = currentState.eval(_params.maxPlayer(), _params.evalMethod(), _params.simScript(Players::Player_One), _params.simScript(Players::Player_Two)); _results.nodesVisited++; } // otherwise we have seen this node before else { // update the state for a non-leaf node updateState(node, currentState, false); if (currentState.isTerminal()) { playoutVal = currentState.eval(_params.maxPlayer(), EvaluationMethods::LTD2); } else { // if the children haven't been generated yet if (!node.hasChildren()) { generateChildren(node, currentState); } UCTNode & next = UCTNodeSelect(node); playoutVal = traverse(next, currentState); } } node.incVisits(); if (playoutVal.val() > 0) { node.addWins(1); } else if (playoutVal.val() == 0) { node.addWins(0.5); } return playoutVal; } // generate the children of state 'node' // state is the GameState after node's moves have been performed void UCTSearch::generateChildren(UCTNode & node, GameState & state) { // figure out who is next to move in the game const IDType playerToMove(getPlayerToMove(node, state)); // generate all the moves possible from this state state.generateMoves(_moveArray, playerToMove); _moveArray.shuffleMoveActions(); // generate the 'ordered moves' for move ordering generateOrderedMoves(state, _moveArray, playerToMove); // for each child of this state, add a child to the current node for (size_t child(0); (child < _params.maxChildren()) && getNextMove(playerToMove, _moveArray, child, _actionVec); ++child) { // add the child to the tree node.addChild(&node, playerToMove, getChildNodeType(node, state), _actionVec, _params.maxChildren(), _memoryPool ? _memoryPool->alloc() : NULL); _results.nodesCreated++; } } StateEvalScore UCTSearch::performPlayout(GameState & state) { GameState copy(state); copy.finishedMoving(); return copy.eval(_params.maxPlayer(), _params.evalMethod(), _params.simScript(Players::Player_One), _params.simScript(Players::Player_Two)); } const bool UCTSearch::isRoot(UCTNode & node) const { return &node == &_rootNode; } void UCTSearch::printSubTree(UCTNode & node, GameState s, std::string filename) { std::ofstream out(filename.c_str()); GraphViz::Graph G("g"); G.set("bgcolor", "#ffffff"); printSubTreeGraphViz(node, G, s); G.print(out); } void UCTSearch::printSubTreeGraphViz(UCTNode & node, GraphViz::Graph & g, GameState state) { if (node.getNodeType() == SearchNodeType::FirstSimNode && node.hasChildren()) { // don't make any moves if it is a first simnode } else { if (node.getNodeType() == SearchNodeType::SecondSimNode) { state.makeMoves(node.getParent()->getMove()); } state.makeMoves(node.getMove()); state.finishedMoving(); } std::stringstream label; std::stringstream move; for (size_t a(0); a<node.getMove().size(); ++a) { move << node.getMove()[a].moveString() << "\\n"; } if (node.getMove().size() == 0) { move << "root"; } std::string firstSim = SearchNodeType::getName(node.getNodeType()); Unit p1 = state.getUnit(0,0); Unit p2 = state.getUnit(1,0); label << move.str() << "\\nVal: " << node.getUCTVal() << "\\nWins: " << node.numWins() << "\\nVisits: " << node.numVisits() << "\\nChildren: " << node.numChildren() << "\\n" << firstSim << "\\nPtr: " << &node << "\\n---------------" << "\\nFrame: " << state.getTime() << "\\nHP: " << p1.currentHP() << " " << p2.currentHP() << "\\nAtk: " << p1.nextAttackActionTime() << " " << p2.nextAttackActionTime() << "\\nMove: " << p1.nextMoveActionTime() << " " << p2.nextMoveActionTime() << "\\nPrev: " << p1.previousActionTime() << " " << p2.previousActionTime(); std::string fillcolor ("#aaaaaa"); if (node.getPlayer() == Players::Player_One) { fillcolor = "#ff0000"; } else if (node.getPlayer() == Players::Player_Two) { fillcolor = "#00ff00"; } GraphViz::Node n(getNodeIDString(node)); n.set("label", label.str()); n.set("fillcolor", fillcolor); n.set("color", "#000000"); n.set("fontcolor", "#000000"); n.set("style", "filled,bold"); n.set("shape", "box"); g.addNode(n); // recurse for each child for (size_t c(0); c<node.numChildren(); ++c) { UCTNode & child = node.getChild(c); if (child.numVisits() > 0) { GraphViz::Edge edge(getNodeIDString(node), getNodeIDString(child)); g.addEdge(edge); printSubTreeGraphViz(child, g, state); } } } std::string UCTSearch::getNodeIDString(UCTNode & node) { std::stringstream ss; ss << (unsigned long long)&node; return ss.str(); } UCTSearchResults & UCTSearch::getResults() { return _results; }
c++
code
14,773
3,259
#ifndef _CLIQUES_HPP_ #define _CLIQUES_HPP_ #include "graph/network.hpp" typedef const graph :: VerySimpleGraphInterface * SimpleIntGraph; namespace cliques { void cliquesToStdout (const graph :: NetworkInterfaceConvertedToString * net, unsigned int minimumSize); // You're not allowed to ask for the 2-cliques void cliquesToVector(std :: vector< std :: vector<int64_t> > &all_cliques_by_orig_name, graph :: NetworkInterfaceConvertedToString *net, unsigned int minimumSize /* = 3*/ ); } // namespace cliques #endif
c++
code
531
92
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.DateTimeParse/System.TM #include "System/DateTimeParse_TM.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Globalization namespace System::Globalization { // Forward declaring type: Calendar class Calendar; } // Completed forward declares // Type namespace: System namespace System { // Size: 0x20 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: System.ParsingInfo // [TokenAttribute] Offset: FFFFFFFF struct ParsingInfo/*, public System::ValueType*/ { public: // System.Globalization.Calendar calendar // Size: 0x8 // Offset: 0x0 System::Globalization::Calendar* calendar; // Field size check static_assert(sizeof(System::Globalization::Calendar*) == 0x8); // System.Int32 dayOfWeek // Size: 0x4 // Offset: 0x8 int dayOfWeek; // Field size check static_assert(sizeof(int) == 0x4); // System.DateTimeParse/System.TM timeMark // Size: 0x4 // Offset: 0xC System::DateTimeParse::TM timeMark; // Field size check static_assert(sizeof(System::DateTimeParse::TM) == 0x4); // System.Boolean fUseHour12 // Size: 0x1 // Offset: 0x10 bool fUseHour12; // Field size check static_assert(sizeof(bool) == 0x1); // System.Boolean fUseTwoDigitYear // Size: 0x1 // Offset: 0x11 bool fUseTwoDigitYear; // Field size check static_assert(sizeof(bool) == 0x1); // System.Boolean fAllowInnerWhite // Size: 0x1 // Offset: 0x12 bool fAllowInnerWhite; // Field size check static_assert(sizeof(bool) == 0x1); // System.Boolean fAllowTrailingWhite // Size: 0x1 // Offset: 0x13 bool fAllowTrailingWhite; // Field size check static_assert(sizeof(bool) == 0x1); // System.Boolean fCustomNumberParser // Size: 0x1 // Offset: 0x14 bool fCustomNumberParser; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: fCustomNumberParser and: parseNumberDelegate char __padding7[0x3] = {}; // System.DateTimeParse/System.MatchNumberDelegate parseNumberDelegate // Size: 0x8 // Offset: 0x18 System::DateTimeParse::MatchNumberDelegate* parseNumberDelegate; // Field size check static_assert(sizeof(System::DateTimeParse::MatchNumberDelegate*) == 0x8); // Creating value type constructor for type: ParsingInfo constexpr ParsingInfo(System::Globalization::Calendar* calendar_ = {}, int dayOfWeek_ = {}, System::DateTimeParse::TM timeMark_ = {}, bool fUseHour12_ = {}, bool fUseTwoDigitYear_ = {}, bool fAllowInnerWhite_ = {}, bool fAllowTrailingWhite_ = {}, bool fCustomNumberParser_ = {}, System::DateTimeParse::MatchNumberDelegate* parseNumberDelegate_ = {}) noexcept : calendar{calendar_}, dayOfWeek{dayOfWeek_}, timeMark{timeMark_}, fUseHour12{fUseHour12_}, fUseTwoDigitYear{fUseTwoDigitYear_}, fAllowInnerWhite{fAllowInnerWhite_}, fAllowTrailingWhite{fAllowTrailingWhite_}, fCustomNumberParser{fCustomNumberParser_}, parseNumberDelegate{parseNumberDelegate_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Get instance field reference: System.Globalization.Calendar calendar System::Globalization::Calendar*& dyn_calendar(); // Get instance field reference: System.Int32 dayOfWeek int& dyn_dayOfWeek(); // Get instance field reference: System.DateTimeParse/System.TM timeMark System::DateTimeParse::TM& dyn_timeMark(); // Get instance field reference: System.Boolean fUseHour12 bool& dyn_fUseHour12(); // Get instance field reference: System.Boolean fUseTwoDigitYear bool& dyn_fUseTwoDigitYear(); // Get instance field reference: System.Boolean fAllowInnerWhite bool& dyn_fAllowInnerWhite(); // Get instance field reference: System.Boolean fAllowTrailingWhite bool& dyn_fAllowTrailingWhite(); // Get instance field reference: System.Boolean fCustomNumberParser bool& dyn_fCustomNumberParser(); // Get instance field reference: System.DateTimeParse/System.MatchNumberDelegate parseNumberDelegate System::DateTimeParse::MatchNumberDelegate*& dyn_parseNumberDelegate(); // System.Void Init() // Offset: 0x1D137C8 void Init(); }; // System.ParsingInfo #pragma pack(pop) static check_size<sizeof(ParsingInfo), 24 + sizeof(System::DateTimeParse::MatchNumberDelegate*)> __System_ParsingInfoSizeCheck; static_assert(sizeof(ParsingInfo) == 0x20); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::ParsingInfo, "System", "ParsingInfo"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::ParsingInfo::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::ParsingInfo::*)()>(&System::ParsingInfo::Init)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ParsingInfo), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
c++
code
5,748
972
#include <cstring> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { //#ifndef CPU_ONLY //extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; //#endif template <typename TypeParam> class InnerProductLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: InnerProductLayerTest() : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)), blob_top_(new Blob<Dtype>()) { // fill the values FillerParameter filler_param; UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~InnerProductLayerTest() { delete blob_bottom_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(InnerProductLayerTest, TestDtypesAndDevices); TYPED_TEST(InnerProductLayerTest, TestSetUp) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; InnerProductParameter* inner_product_param = layer_param.mutable_inner_product_param(); inner_product_param->set_num_output(10); shared_ptr<InnerProductLayer<Dtype> > layer( new InnerProductLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->height(), 1); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_->channels(), 10); } TYPED_TEST(InnerProductLayerTest, TestForward) { typedef typename TypeParam::Dtype Dtype; if (Caffe::mode() == Caffe::CPU || sizeof(Dtype) == 4 ) { LayerParameter layer_param; InnerProductParameter* inner_product_param = layer_param.mutable_inner_product_param(); inner_product_param->set_num_output(10); inner_product_param->mutable_weight_filler()->set_type("uniform"); inner_product_param->mutable_bias_filler()->set_type("uniform"); inner_product_param->mutable_bias_filler()->set_min(1); inner_product_param->mutable_bias_filler()->set_max(2); shared_ptr<InnerProductLayer<Dtype> > layer( new InnerProductLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* data = this->blob_top_->cpu_data(); const int count = this->blob_top_->count(); for (int i = 0; i < count; ++i) { EXPECT_GE(data[i], 1.); } } else { LOG(ERROR) << "Skipping test due to old architecture."; } } TYPED_TEST(InnerProductLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; if (Caffe::mode() == Caffe::CPU || sizeof(Dtype) == 4 ) { LayerParameter layer_param; InnerProductParameter* inner_product_param = layer_param.mutable_inner_product_param(); inner_product_param->set_num_output(10); inner_product_param->mutable_weight_filler()->set_type("gaussian"); inner_product_param->mutable_bias_filler()->set_type("gaussian"); inner_product_param->mutable_bias_filler()->set_min(1); inner_product_param->mutable_bias_filler()->set_max(2); InnerProductLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } else { LOG(ERROR) << "Skipping test due to old architecture."; } } } // namespace caffe
c++
code
3,719
772
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gquiche/quic/core/quic_config.h" #include <algorithm> #include <cstring> #include <limits> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "gquiche/quic/core/crypto/crypto_handshake_message.h" #include "gquiche/quic/core/crypto/crypto_protocol.h" #include "gquiche/quic/core/quic_connection_id.h" #include "gquiche/quic/core/quic_constants.h" #include "gquiche/quic/core/quic_socket_address_coder.h" #include "gquiche/quic/core/quic_types.h" #include "gquiche/quic/core/quic_utils.h" #include "gquiche/quic/platform/api/quic_bug_tracker.h" #include "gquiche/quic/platform/api/quic_flag_utils.h" #include "gquiche/quic/platform/api/quic_flags.h" #include "gquiche/quic/platform/api/quic_logging.h" #include "gquiche/quic/platform/api/quic_socket_address.h" namespace quic { // Reads the value corresponding to |name_| from |msg| into |out|. If the // |name_| is absent in |msg| and |presence| is set to OPTIONAL |out| is set // to |default_value|. QuicErrorCode ReadUint32(const CryptoHandshakeMessage& msg, QuicTag tag, QuicConfigPresence presence, uint32_t default_value, uint32_t* out, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); QuicErrorCode error = msg.GetUint32(tag, out); switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence == PRESENCE_REQUIRED) { *error_details = "Missing " + QuicTagToString(tag); break; } error = QUIC_NO_ERROR; *out = default_value; break; case QUIC_NO_ERROR: break; default: *error_details = "Bad " + QuicTagToString(tag); break; } return error; } QuicConfigValue::QuicConfigValue(QuicTag tag, QuicConfigPresence presence) : tag_(tag), presence_(presence) {} QuicConfigValue::~QuicConfigValue() {} QuicFixedUint32::QuicFixedUint32(QuicTag tag, QuicConfigPresence presence) : QuicConfigValue(tag, presence), has_send_value_(false), has_receive_value_(false) {} QuicFixedUint32::~QuicFixedUint32() {} bool QuicFixedUint32::HasSendValue() const { return has_send_value_; } uint32_t QuicFixedUint32::GetSendValue() const { QUIC_BUG_IF(quic_bug_12743_1, !has_send_value_) << "No send value to get for tag:" << QuicTagToString(tag_); return send_value_; } void QuicFixedUint32::SetSendValue(uint32_t value) { has_send_value_ = true; send_value_ = value; } bool QuicFixedUint32::HasReceivedValue() const { return has_receive_value_; } uint32_t QuicFixedUint32::GetReceivedValue() const { QUIC_BUG_IF(quic_bug_12743_2, !has_receive_value_) << "No receive value to get for tag:" << QuicTagToString(tag_); return receive_value_; } void QuicFixedUint32::SetReceivedValue(uint32_t value) { has_receive_value_ = true; receive_value_ = value; } void QuicFixedUint32::ToHandshakeMessage(CryptoHandshakeMessage* out) const { if (tag_ == 0) { QUIC_BUG(quic_bug_12743_3) << "This parameter does not support writing to CryptoHandshakeMessage"; return; } if (has_send_value_) { out->SetValue(tag_, send_value_); } } QuicErrorCode QuicFixedUint32::ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType /*hello_type*/, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); if (tag_ == 0) { *error_details = "This parameter does not support reading from CryptoHandshakeMessage"; QUIC_BUG(quic_bug_10575_1) << *error_details; return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND; } QuicErrorCode error = peer_hello.GetUint32(tag_, &receive_value_); switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence_ == PRESENCE_OPTIONAL) { return QUIC_NO_ERROR; } *error_details = "Missing " + QuicTagToString(tag_); break; case QUIC_NO_ERROR: has_receive_value_ = true; break; default: *error_details = "Bad " + QuicTagToString(tag_); break; } return error; } QuicFixedUint62::QuicFixedUint62(QuicTag name, QuicConfigPresence presence) : QuicConfigValue(name, presence), has_send_value_(false), has_receive_value_(false) {} QuicFixedUint62::~QuicFixedUint62() {} bool QuicFixedUint62::HasSendValue() const { return has_send_value_; } uint64_t QuicFixedUint62::GetSendValue() const { if (!has_send_value_) { QUIC_BUG(quic_bug_10575_2) << "No send value to get for tag:" << QuicTagToString(tag_); return 0; } return send_value_; } void QuicFixedUint62::SetSendValue(uint64_t value) { if (value > kVarInt62MaxValue) { QUIC_BUG(quic_bug_10575_3) << "QuicFixedUint62 invalid value " << value; value = kVarInt62MaxValue; } has_send_value_ = true; send_value_ = value; } bool QuicFixedUint62::HasReceivedValue() const { return has_receive_value_; } uint64_t QuicFixedUint62::GetReceivedValue() const { if (!has_receive_value_) { QUIC_BUG(quic_bug_10575_4) << "No receive value to get for tag:" << QuicTagToString(tag_); return 0; } return receive_value_; } void QuicFixedUint62::SetReceivedValue(uint64_t value) { has_receive_value_ = true; receive_value_ = value; } void QuicFixedUint62::ToHandshakeMessage(CryptoHandshakeMessage* out) const { if (!has_send_value_) { return; } uint32_t send_value32; if (send_value_ > std::numeric_limits<uint32_t>::max()) { QUIC_BUG(quic_bug_10575_5) << "Attempting to send " << send_value_ << " for tag:" << QuicTagToString(tag_); send_value32 = std::numeric_limits<uint32_t>::max(); } else { send_value32 = static_cast<uint32_t>(send_value_); } out->SetValue(tag_, send_value32); } QuicErrorCode QuicFixedUint62::ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType /*hello_type*/, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); uint32_t receive_value32; QuicErrorCode error = peer_hello.GetUint32(tag_, &receive_value32); // GetUint32 is guaranteed to always initialize receive_value32. receive_value_ = receive_value32; switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence_ == PRESENCE_OPTIONAL) { return QUIC_NO_ERROR; } *error_details = "Missing " + QuicTagToString(tag_); break; case QUIC_NO_ERROR: has_receive_value_ = true; break; default: *error_details = "Bad " + QuicTagToString(tag_); break; } return error; } QuicFixedStatelessResetToken::QuicFixedStatelessResetToken( QuicTag tag, QuicConfigPresence presence) : QuicConfigValue(tag, presence), has_send_value_(false), has_receive_value_(false) {} QuicFixedStatelessResetToken::~QuicFixedStatelessResetToken() {} bool QuicFixedStatelessResetToken::HasSendValue() const { return has_send_value_; } const StatelessResetToken& QuicFixedStatelessResetToken::GetSendValue() const { QUIC_BUG_IF(quic_bug_12743_4, !has_send_value_) << "No send value to get for tag:" << QuicTagToString(tag_); return send_value_; } void QuicFixedStatelessResetToken::SetSendValue( const StatelessResetToken& value) { has_send_value_ = true; send_value_ = value; } bool QuicFixedStatelessResetToken::HasReceivedValue() const { return has_receive_value_; } const StatelessResetToken& QuicFixedStatelessResetToken::GetReceivedValue() const { QUIC_BUG_IF(quic_bug_12743_5, !has_receive_value_) << "No receive value to get for tag:" << QuicTagToString(tag_); return receive_value_; } void QuicFixedStatelessResetToken::SetReceivedValue( const StatelessResetToken& value) { has_receive_value_ = true; receive_value_ = value; } void QuicFixedStatelessResetToken::ToHandshakeMessage( CryptoHandshakeMessage* out) const { if (has_send_value_) { out->SetValue(tag_, send_value_); } } QuicErrorCode QuicFixedStatelessResetToken::ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType /*hello_type*/, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); QuicErrorCode error = peer_hello.GetStatelessResetToken(tag_, &receive_value_); switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence_ == PRESENCE_OPTIONAL) { return QUIC_NO_ERROR; } *error_details = "Missing " + QuicTagToString(tag_); break; case QUIC_NO_ERROR: has_receive_value_ = true; break; default: *error_details = "Bad " + QuicTagToString(tag_); break; } return error; } QuicFixedTagVector::QuicFixedTagVector(QuicTag name, QuicConfigPresence presence) : QuicConfigValue(name, presence), has_send_values_(false), has_receive_values_(false) {} QuicFixedTagVector::QuicFixedTagVector(const QuicFixedTagVector& other) = default; QuicFixedTagVector::~QuicFixedTagVector() {} bool QuicFixedTagVector::HasSendValues() const { return has_send_values_; } const QuicTagVector& QuicFixedTagVector::GetSendValues() const { QUIC_BUG_IF(quic_bug_12743_6, !has_send_values_) << "No send values to get for tag:" << QuicTagToString(tag_); return send_values_; } void QuicFixedTagVector::SetSendValues(const QuicTagVector& values) { has_send_values_ = true; send_values_ = values; } bool QuicFixedTagVector::HasReceivedValues() const { return has_receive_values_; } const QuicTagVector& QuicFixedTagVector::GetReceivedValues() const { QUIC_BUG_IF(quic_bug_12743_7, !has_receive_values_) << "No receive value to get for tag:" << QuicTagToString(tag_); return receive_values_; } void QuicFixedTagVector::SetReceivedValues(const QuicTagVector& values) { has_receive_values_ = true; receive_values_ = values; } void QuicFixedTagVector::ToHandshakeMessage(CryptoHandshakeMessage* out) const { if (has_send_values_) { out->SetVector(tag_, send_values_); } } QuicErrorCode QuicFixedTagVector::ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType /*hello_type*/, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); QuicTagVector values; QuicErrorCode error = peer_hello.GetTaglist(tag_, &values); switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence_ == PRESENCE_OPTIONAL) { return QUIC_NO_ERROR; } *error_details = "Missing " + QuicTagToString(tag_); break; case QUIC_NO_ERROR: QUIC_DVLOG(1) << "Received Connection Option tags from receiver."; has_receive_values_ = true; receive_values_.insert(receive_values_.end(), values.begin(), values.end()); break; default: *error_details = "Bad " + QuicTagToString(tag_); break; } return error; } QuicFixedSocketAddress::QuicFixedSocketAddress(QuicTag tag, QuicConfigPresence presence) : QuicConfigValue(tag, presence), has_send_value_(false), has_receive_value_(false) {} QuicFixedSocketAddress::~QuicFixedSocketAddress() {} bool QuicFixedSocketAddress::HasSendValue() const { return has_send_value_; } const QuicSocketAddress& QuicFixedSocketAddress::GetSendValue() const { QUIC_BUG_IF(quic_bug_12743_8, !has_send_value_) << "No send value to get for tag:" << QuicTagToString(tag_); return send_value_; } void QuicFixedSocketAddress::SetSendValue(const QuicSocketAddress& value) { has_send_value_ = true; send_value_ = value; } bool QuicFixedSocketAddress::HasReceivedValue() const { return has_receive_value_; } const QuicSocketAddress& QuicFixedSocketAddress::GetReceivedValue() const { QUIC_BUG_IF(quic_bug_12743_9, !has_receive_value_) << "No receive value to get for tag:" << QuicTagToString(tag_); return receive_value_; } void QuicFixedSocketAddress::SetReceivedValue(const QuicSocketAddress& value) { has_receive_value_ = true; receive_value_ = value; } void QuicFixedSocketAddress::ToHandshakeMessage( CryptoHandshakeMessage* out) const { if (has_send_value_) { QuicSocketAddressCoder address_coder(send_value_); out->SetStringPiece(tag_, address_coder.Encode()); } } QuicErrorCode QuicFixedSocketAddress::ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType /*hello_type*/, std::string* error_details) { absl::string_view address; if (!peer_hello.GetStringPiece(tag_, &address)) { if (presence_ == PRESENCE_REQUIRED) { *error_details = "Missing " + QuicTagToString(tag_); return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND; } } else { QuicSocketAddressCoder address_coder; if (address_coder.Decode(address.data(), address.length())) { SetReceivedValue( QuicSocketAddress(address_coder.ip(), address_coder.port())); } } return QUIC_NO_ERROR; } QuicConfig::QuicConfig() : negotiated_(false), max_time_before_crypto_handshake_(QuicTime::Delta::Zero()), max_idle_time_before_crypto_handshake_(QuicTime::Delta::Zero()), max_undecryptable_packets_(0), connection_options_(kCOPT, PRESENCE_OPTIONAL), client_connection_options_(kCLOP, PRESENCE_OPTIONAL), max_idle_timeout_to_send_(QuicTime::Delta::Infinite()), max_bidirectional_streams_(kMIBS, PRESENCE_REQUIRED), max_unidirectional_streams_(kMIUS, PRESENCE_OPTIONAL), bytes_for_connection_id_(kTCID, PRESENCE_OPTIONAL), initial_round_trip_time_us_(kIRTT, PRESENCE_OPTIONAL), initial_max_stream_data_bytes_incoming_bidirectional_(0, PRESENCE_OPTIONAL), initial_max_stream_data_bytes_outgoing_bidirectional_(0, PRESENCE_OPTIONAL), initial_max_stream_data_bytes_unidirectional_(0, PRESENCE_OPTIONAL), initial_stream_flow_control_window_bytes_(kSFCW, PRESENCE_OPTIONAL), initial_session_flow_control_window_bytes_(kCFCW, PRESENCE_OPTIONAL), connection_migration_disabled_(kNCMR, PRESENCE_OPTIONAL), key_update_supported_remotely_(false), key_update_supported_locally_(false), alternate_server_address_ipv6_(kASAD, PRESENCE_OPTIONAL), alternate_server_address_ipv4_(kASAD, PRESENCE_OPTIONAL), stateless_reset_token_(kSRST, PRESENCE_OPTIONAL), max_ack_delay_ms_(kMAD, PRESENCE_OPTIONAL), min_ack_delay_ms_(0, PRESENCE_OPTIONAL), ack_delay_exponent_(kADE, PRESENCE_OPTIONAL), max_udp_payload_size_(0, PRESENCE_OPTIONAL), max_datagram_frame_size_(0, PRESENCE_OPTIONAL), active_connection_id_limit_(0, PRESENCE_OPTIONAL) { SetDefaults(); } QuicConfig::QuicConfig(const QuicConfig& other) = default; QuicConfig::~QuicConfig() {} bool QuicConfig::SetInitialReceivedConnectionOptions( const QuicTagVector& tags) { if (HasReceivedConnectionOptions()) { // If we have already received connection options (via handshake or due to // a previous call), don't re-initialize. return false; } connection_options_.SetReceivedValues(tags); return true; } void QuicConfig::SetConnectionOptionsToSend( const QuicTagVector& connection_options) { connection_options_.SetSendValues(connection_options); } bool QuicConfig::HasReceivedConnectionOptions() const { return connection_options_.HasReceivedValues(); } const QuicTagVector& QuicConfig::ReceivedConnectionOptions() const { return connection_options_.GetReceivedValues(); } bool QuicConfig::HasSendConnectionOptions() const { return connection_options_.HasSendValues(); } const QuicTagVector& QuicConfig::SendConnectionOptions() const { return connection_options_.GetSendValues(); } bool QuicConfig::HasClientSentConnectionOption(QuicTag tag, Perspective perspective) const { if (perspective == Perspective::IS_SERVER) { if (HasReceivedConnectionOptions() && ContainsQuicTag(ReceivedConnectionOptions(), tag)) { return true; } } else if (HasSendConnectionOptions() && ContainsQuicTag(SendConnectionOptions(), tag)) { return true; } return false; } void QuicConfig::SetClientConnectionOptions( const QuicTagVector& client_connection_options) { client_connection_options_.SetSendValues(client_connection_options); } bool QuicConfig::HasClientRequestedIndependentOption( QuicTag tag, Perspective perspective) const { if (perspective == Perspective::IS_SERVER) { return (HasReceivedConnectionOptions() && ContainsQuicTag(ReceivedConnectionOptions(), tag)); } return (client_connection_options_.HasSendValues() && ContainsQuicTag(client_connection_options_.GetSendValues(), tag)); } const QuicTagVector& QuicConfig::ClientRequestedIndependentOptions( Perspective perspective) const { static const QuicTagVector* no_options = new QuicTagVector; if (perspective == Perspective::IS_SERVER) { return HasReceivedConnectionOptions() ? ReceivedConnectionOptions() : *no_options; } return client_connection_options_.HasSendValues() ? client_connection_options_.GetSendValues() : *no_options; } void QuicConfig::SetIdleNetworkTimeout(QuicTime::Delta idle_network_timeout) { if (idle_network_timeout.ToMicroseconds() <= 0) { QUIC_BUG(quic_bug_10575_6) << "Invalid idle network timeout " << idle_network_timeout; return; } max_idle_timeout_to_send_ = idle_network_timeout; } QuicTime::Delta QuicConfig::IdleNetworkTimeout() const { // TODO(b/152032210) add a QUIC_BUG to ensure that is not called before we've // received the peer's values. This is true in production code but not in all // of our tests that use a fake QuicConfig. if (!received_max_idle_timeout_.has_value()) { return max_idle_timeout_to_send_; } return received_max_idle_timeout_.value(); } void QuicConfig::SetMaxBidirectionalStreamsToSend(uint32_t max_streams) { max_bidirectional_streams_.SetSendValue(max_streams); } uint32_t QuicConfig::GetMaxBidirectionalStreamsToSend() const { return max_bidirectional_streams_.GetSendValue(); } bool QuicConfig::HasReceivedMaxBidirectionalStreams() const { return max_bidirectional_streams_.HasReceivedValue(); } uint32_t QuicConfig::ReceivedMaxBidirectionalStreams() const { return max_bidirectional_streams_.GetReceivedValue(); } void QuicConfig::SetMaxUnidirectionalStreamsToSend(uint32_t max_streams) { max_unidirectional_streams_.SetSendValue(max_streams); } uint32_t QuicConfig::GetMaxUnidirectionalStreamsToSend() const { return max_unidirectional_streams_.GetSendValue(); } bool QuicConfig::HasReceivedMaxUnidirectionalStreams() const { return max_unidirectional_streams_.HasReceivedValue(); } uint32_t QuicConfig::ReceivedMaxUnidirectionalStreams() const { return max_unidirectional_streams_.GetReceivedValue(); } void QuicConfig::SetMaxAckDelayToSendMs(uint32_t max_ack_delay_ms) { max_ack_delay_ms_.SetSendValue(max_ack_delay_ms); } uint32_t QuicConfig::GetMaxAckDelayToSendMs() const { return max_ack_delay_ms_.GetSendValue(); } bool QuicConfig::HasReceivedMaxAckDelayMs() const { return max_ack_delay_ms_.HasReceivedValue(); } uint32_t QuicConfig::ReceivedMaxAckDelayMs() const { return max_ack_delay_ms_.GetReceivedValue(); } void QuicConfig::SetMinAckDelayMs(uint32_t min_ack_delay_ms) { min_ack_delay_ms_.SetSendValue(min_ack_delay_ms); } uint32_t QuicConfig::GetMinAckDelayToSendMs() const { return min_ack_delay_ms_.GetSendValue(); } bool QuicConfig::HasReceivedMinAckDelayMs() const { ret
c++
code
20,000
3,215
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/desktop_capture/win/dxgi_output_duplicator.h" #include <string.h> #include <unknwn.h> #include <DXGI.h> #include <DXGIFormat.h> #include BOSS_FAKEWIN_V_windows_h //original-code:<Windows.h> #include <algorithm> #include "modules/desktop_capture/win/dxgi_texture_mapping.h" #include "modules/desktop_capture/win/dxgi_texture_staging.h" #include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" #include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" #include BOSS_WEBRTC_U_rtc_base__win32_h //original-code:"rtc_base/win32.h" namespace webrtc { using Microsoft::WRL::ComPtr; namespace { // Timeout for AcquireNextFrame() call. // DxgiDuplicatorController leverages external components to do the capture // scheduling. So here DxgiOutputDuplicator does not need to actively wait for a // new frame. const int kAcquireTimeoutMs = 0; DesktopRect RECTToDesktopRect(const RECT& rect) { return DesktopRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom); } Rotation DxgiRotationToRotation(DXGI_MODE_ROTATION rotation) { switch (rotation) { case DXGI_MODE_ROTATION_IDENTITY: case DXGI_MODE_ROTATION_UNSPECIFIED: return Rotation::CLOCK_WISE_0; case DXGI_MODE_ROTATION_ROTATE90: return Rotation::CLOCK_WISE_90; case DXGI_MODE_ROTATION_ROTATE180: return Rotation::CLOCK_WISE_180; case DXGI_MODE_ROTATION_ROTATE270: return Rotation::CLOCK_WISE_270; } RTC_NOTREACHED(); return Rotation::CLOCK_WISE_0; } } // namespace DxgiOutputDuplicator::DxgiOutputDuplicator(const D3dDevice& device, const ComPtr<IDXGIOutput1>& output, const DXGI_OUTPUT_DESC& desc) : device_(device), output_(output), device_name_(rtc::ToUtf8(desc.DeviceName)), desktop_rect_(RECTToDesktopRect(desc.DesktopCoordinates)) { RTC_DCHECK(output_); RTC_DCHECK(!desktop_rect_.is_empty()); RTC_DCHECK_GT(desktop_rect_.width(), 0); RTC_DCHECK_GT(desktop_rect_.height(), 0); } DxgiOutputDuplicator::DxgiOutputDuplicator(DxgiOutputDuplicator&& other) = default; DxgiOutputDuplicator::~DxgiOutputDuplicator() { if (duplication_) { duplication_->ReleaseFrame(); } texture_.reset(); } bool DxgiOutputDuplicator::Initialize() { if (DuplicateOutput()) { if (desc_.DesktopImageInSystemMemory) { texture_.reset(new DxgiTextureMapping(duplication_.Get())); } else { texture_.reset(new DxgiTextureStaging(device_)); } return true; } else { duplication_.Reset(); return false; } } bool DxgiOutputDuplicator::DuplicateOutput() { RTC_DCHECK(!duplication_); _com_error error = output_->DuplicateOutput(static_cast<IUnknown*>(device_.d3d_device()), duplication_.GetAddressOf()); if (error.Error() != S_OK || !duplication_) { RTC_LOG(LS_WARNING) << "Failed to duplicate output from IDXGIOutput1, error " << error.ErrorMessage() << ", with code " << error.Error(); return false; } memset(&desc_, 0, sizeof(desc_)); duplication_->GetDesc(&desc_); if (desc_.ModeDesc.Format != DXGI_FORMAT_B8G8R8A8_UNORM) { RTC_LOG(LS_ERROR) << "IDXGIDuplicateOutput does not use RGBA (8 bit) " "format, which is required by downstream components, " "format is " << desc_.ModeDesc.Format; return false; } if (static_cast<int>(desc_.ModeDesc.Width) != desktop_rect_.width() || static_cast<int>(desc_.ModeDesc.Height) != desktop_rect_.height()) { RTC_LOG(LS_ERROR) << "IDXGIDuplicateOutput does not return a same size as its " "IDXGIOutput1, size returned by IDXGIDuplicateOutput is " << desc_.ModeDesc.Width << " x " << desc_.ModeDesc.Height << ", size returned by IDXGIOutput1 is " << desktop_rect_.width() << " x " << desktop_rect_.height(); return false; } rotation_ = DxgiRotationToRotation(desc_.Rotation); unrotated_size_ = RotateSize(desktop_size(), ReverseRotation(rotation_)); return true; } bool DxgiOutputDuplicator::ReleaseFrame() { RTC_DCHECK(duplication_); _com_error error = duplication_->ReleaseFrame(); if (error.Error() != S_OK) { RTC_LOG(LS_ERROR) << "Failed to release frame from IDXGIOutputDuplication, " "error" << error.ErrorMessage() << ", code " << error.Error(); return false; } return true; } bool DxgiOutputDuplicator::Duplicate(Context* context, DesktopVector offset, SharedDesktopFrame* target) { RTC_DCHECK(duplication_); RTC_DCHECK(texture_); RTC_DCHECK(target); if (!DesktopRect::MakeSize(target->size()) .ContainsRect(GetTranslatedDesktopRect(offset))) { // target size is not large enough to cover current output region. return false; } DXGI_OUTDUPL_FRAME_INFO frame_info; memset(&frame_info, 0, sizeof(frame_info)); ComPtr<IDXGIResource> resource; _com_error error = duplication_->AcquireNextFrame( kAcquireTimeoutMs, &frame_info, resource.GetAddressOf()); if (error.Error() != S_OK && error.Error() != DXGI_ERROR_WAIT_TIMEOUT) { RTC_LOG(LS_ERROR) << "Failed to capture frame, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } // We need to merge updated region with the one from context, but only spread // updated region from current frame. So keeps a copy of updated region from // context here. The |updated_region| always starts from (0, 0). DesktopRegion updated_region; updated_region.Swap(&context->updated_region); if (error.Error() == S_OK && frame_info.AccumulatedFrames > 0 && resource) { DetectUpdatedRegion(frame_info, &context->updated_region); SpreadContextChange(context); if (!texture_->CopyFrom(frame_info, resource.Get())) { return false; } updated_region.AddRegion(context->updated_region); // TODO(zijiehe): Figure out why clearing context->updated_region() here // triggers screen flickering? const DesktopFrame& source = texture_->AsDesktopFrame(); if (rotation_ != Rotation::CLOCK_WISE_0) { for (DesktopRegion::Iterator it(updated_region); !it.IsAtEnd(); it.Advance()) { // The |updated_region| returned by Windows is rotated, but the |source| // frame is not. So we need to rotate it reversely. const DesktopRect source_rect = RotateRect( it.rect(), desktop_size(), ReverseRotation(rotation_)); RotateDesktopFrame(source, source_rect, rotation_, offset, target); } } else { for (DesktopRegion::Iterator it(updated_region); !it.IsAtEnd(); it.Advance()) { // The DesktopRect in |target|, starts from offset. DesktopRect dest_rect = it.rect(); dest_rect.Translate(offset); target->CopyPixelsFrom(source, it.rect().top_left(), dest_rect); } } last_frame_ = target->Share(); last_frame_offset_ = offset; updated_region.Translate(offset.x(), offset.y()); target->mutable_updated_region()->AddRegion(updated_region); num_frames_captured_++; return texture_->Release() && ReleaseFrame(); } if (last_frame_) { // No change since last frame or AcquireNextFrame() timed out, we will // export last frame to the target. for (DesktopRegion::Iterator it(updated_region); !it.IsAtEnd(); it.Advance()) { // The DesktopRect in |source|, starts from last_frame_offset_. DesktopRect source_rect = it.rect(); // The DesktopRect in |target|, starts from offset. DesktopRect target_rect = source_rect; source_rect.Translate(last_frame_offset_); target_rect.Translate(offset); target->CopyPixelsFrom(*last_frame_, source_rect.top_left(), target_rect); } updated_region.Translate(offset.x(), offset.y()); target->mutable_updated_region()->AddRegion(updated_region); } else { // If we were at the very first frame, and capturing failed, the // context->updated_region should be kept unchanged for next attempt. context->updated_region.Swap(&updated_region); } // If AcquireNextFrame() failed with timeout error, we do not need to release // the frame. return error.Error() == DXGI_ERROR_WAIT_TIMEOUT || ReleaseFrame(); } DesktopRect DxgiOutputDuplicator::GetTranslatedDesktopRect( DesktopVector offset) const { DesktopRect result(DesktopRect::MakeSize(desktop_size())); result.Translate(offset); return result; } DesktopRect DxgiOutputDuplicator::GetUntranslatedDesktopRect() const { return DesktopRect::MakeSize(desktop_size()); } void DxgiOutputDuplicator::DetectUpdatedRegion( const DXGI_OUTDUPL_FRAME_INFO& frame_info, DesktopRegion* updated_region) { if (DoDetectUpdatedRegion(frame_info, updated_region)) { // Make sure even a region returned by Windows API is out of the scope of // desktop_rect_, we still won't export it to the target DesktopFrame. updated_region->IntersectWith(GetUntranslatedDesktopRect()); } else { updated_region->SetRect(GetUntranslatedDesktopRect()); } } bool DxgiOutputDuplicator::DoDetectUpdatedRegion( const DXGI_OUTDUPL_FRAME_INFO& frame_info, DesktopRegion* updated_region) { RTC_DCHECK(updated_region); updated_region->Clear(); if (frame_info.TotalMetadataBufferSize == 0) { // This should not happen, since frame_info.AccumulatedFrames > 0. RTC_LOG(LS_ERROR) << "frame_info.AccumulatedFrames > 0, " "but TotalMetadataBufferSize == 0"; return false; } if (metadata_.capacity() < frame_info.TotalMetadataBufferSize) { metadata_.clear(); // Avoid data copy metadata_.reserve(frame_info.TotalMetadataBufferSize); } UINT buff_size = 0; DXGI_OUTDUPL_MOVE_RECT* move_rects = reinterpret_cast<DXGI_OUTDUPL_MOVE_RECT*>(metadata_.data()); size_t move_rects_count = 0; _com_error error = duplication_->GetFrameMoveRects( static_cast<UINT>(metadata_.capacity()), move_rects, &buff_size); if (error.Error() != S_OK) { RTC_LOG(LS_ERROR) << "Failed to get move rectangles, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } move_rects_count = buff_size / sizeof(DXGI_OUTDUPL_MOVE_RECT); RECT* dirty_rects = reinterpret_cast<RECT*>(metadata_.data() + buff_size); size_t dirty_rects_count = 0; error = duplication_->GetFrameDirtyRects( static_cast<UINT>(metadata_.capacity()) - buff_size, dirty_rects, &buff_size); if (error.Error() != S_OK) { RTC_LOG(LS_ERROR) << "Failed to get dirty rectangles, error " << error.ErrorMessage() << ", code " << error.Error(); return false; } dirty_rects_count = buff_size / sizeof(RECT); while (move_rects_count > 0) { // DirectX capturer API may randomly return unmoved move_rects, which should // be skipped to avoid unnecessary wasting of differing and encoding // resources. // By using testing application it2me_standalone_host_main, this check // reduces average capture time by 0.375% (4.07 -> 4.055), and average // encode time by 0.313% (8.042 -> 8.016) without other impacts. if (move_rects->SourcePoint.x != move_rects->DestinationRect.left || move_rects->SourcePoint.y != move_rects->DestinationRect.top) { updated_region->AddRect( RotateRect(DesktopRect::MakeXYWH(move_rects->SourcePoint.x, move_rects->SourcePoint.y, move_rects->DestinationRect.right - move_rects->DestinationRect.left, move_rects->DestinationRect.bottom - move_rects->DestinationRect.top), unrotated_size_, rotation_)); updated_region->AddRect( RotateRect(DesktopRect::MakeLTRB(move_rects->DestinationRect.left, move_rects->DestinationRect.top, move_rects->DestinationRect.right, move_rects->DestinationRect.bottom), unrotated_size_, rotation_)); } else { RTC_LOG(LS_INFO) << "Unmoved move_rect detected, [" << move_rects->DestinationRect.left << ", " << move_rects->DestinationRect.top << "] - [" << move_rects->DestinationRect.right << ", " << move_rects->DestinationRect.bottom << "]."; } move_rects++; move_rects_count--; } while (dirty_rects_count > 0) { updated_region->AddRect(RotateRect( DesktopRect::MakeLTRB(dirty_rects->left, dirty_rects->top, dirty_rects->right, dirty_rects->bottom), unrotated_size_, rotation_)); dirty_rects++; dirty_rects_count--; } return true; } void DxgiOutputDuplicator::Setup(Context* context) { RTC_DCHECK(context->updated_region.is_empty()); // Always copy entire monitor during the first Duplicate() function call. context->updated_region.AddRect(GetUntranslatedDesktopRect()); RTC_DCHECK(std::find(contexts_.begin(), contexts_.end(), context) == contexts_.end()); contexts_.push_back(context); } void DxgiOutputDuplicator::Unregister(const Context* const context) { auto it = std::find(contexts_.begin(), contexts_.end(), context); RTC_DCHECK(it != contexts_.end()); contexts_.erase(it); } void DxgiOutputDuplicator::SpreadContextChange(const Context* const source) { for (Context* dest : contexts_) { RTC_DCHECK(dest); if (dest != source) { dest->updated_region.AddRegion(source->updated_region); } } } DesktopSize DxgiOutputDuplicator::desktop_size() const { return desktop_rect_.size(); } int64_t DxgiOutputDuplicator::num_frames_captured() const { #if !defined(NDEBUG) RTC_DCHECK_EQ(!!last_frame_, num_frames_captured_ > 0); #endif return num_frames_captured_; } void DxgiOutputDuplicator::TranslateRect(const DesktopVector& position) { desktop_rect_.Translate(position); RTC_DCHECK_GE(desktop_rect_.left(), 0); RTC_DCHECK_GE(desktop_rect_.top(), 0); } } // namespace webrtc
c++
code
14,904
2,843
/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan 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 "mkn/kul/proc.hpp" #include "mkn/kul/os/nix/src/proc/xparse_line.ipp" #include "mkn/kul/os/nix/src/proc/xphysical.ipp" #include "mkn/kul/os/nix/src/proc/xvirtual.ipp"
c++
code
1,667
287
// // Created by nathan on 11/02/16. // #ifndef RUBKIS_SOLVER_H #define RUBKIS_SOLVER_H #include "rCube.hpp" #include <stack> #include <vector> #include <queue> #include <cstdlib> #include <ctime> class solver { public: /* * Constructs the object that can do solving * of a rubiks cube */ solver(); /* * Gathers all possible states at current state * returns an array of states */ std::vector<rCube> getCurrentStates(rCube &currentState); /* * Counts how many tiles are not in the correct place */ int cubesOutOfPlace(rCube &cube); /* * Solver to try upto 18 random moves */ void randomSolver(rCube &cube); void multiStageSolver(rCube &cube); std::vector<moves> whiteCross(rCube &cube); private: std::vector<rCube> visited; std::priority_queue<rCube, std::vector<rCube>, rCube::compareF> frontier; }; #endif //RUBKIS_SOLVER_H
c++
code
945
206
// dear imgui, v1.51 WIP // (main code and documentation) // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // This library is free but I need your support to sustain development and maintenance. // If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui /* Index - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - Read first - How to update to a newer version of ImGui - Getting started with integrating ImGui in your code/engine - API BREAKING CHANGES (read me when you update!) - ISSUES & TODO LIST - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - How can I help? - What is ImTextureID and how do I display an image? - I integrated ImGui in my engine and the text or lines are blurry.. - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels/IDs. - How can I tell when ImGui wants my mouse/keyboard inputs VS when I can pass them to my application? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I preserve my ImGui context across reloading a DLL? (loss of the global/static variables) - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - ISSUES & TODO-LIST - CODE MISSION STATEMENT ================= - Easy to use to create code-driven and data-driven tools - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools - Easy to hack and improve - Minimize screen real-estate usage - Minimize setup and maintenance - Minimize state storage on user side - Portable, minimize dependencies, run on target (consoles, phones, etc.) - Efficient runtime and memory consumption (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - Doesn't look fancy, doesn't animate - Limited layout features, intricate layouts are typically crafted in code END-USER GUIDE ============== - Double-click title bar to collapse window - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() - Click and drag on lower right corner to resize window - Click and drag on any empty space to move window - Double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - Use mouse wheel to scroll - Use CTRL+mouse wheel to zoom window contents (if io.FontAllowScaling is true) - CTRL+Click on a slider or drag box to input value as text - Text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump - CTRL+Shift+Left/Right to select words - CTRL+A our Double-Click to select all - CTRL+X,CTRL+C,CTRL+V to use OS clipboard - CTRL+Z,CTRL+Y to undo/redo - ESCAPE to revert text to its original value - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) - Controls are automatically adjusted for OSX to match standard OSX text editing operations. PROGRAMMER GUIDE ================ READ FIRST - Read the FAQ below this section! - Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - Call and read ImGui::ShowTestWindow() for demo code demonstrating most features. - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861 HOW TO UPDATE TO A NEWER VERSION OF IMGUI - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h) - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! - Try to keep your copy of dear imgui reasonably up to date. GETTING STARTED WITH INTEGRATING IMGUI IN YOUR CODE/ENGINE - Add the ImGui source files to your projects, using your preferred build system. It is recommended you build the .cpp files as part of your project and not as a library. - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types. - See examples/ folder for standalone sample applications. To understand the integration process, you can read examples/opengl2_example/ because it is short, then switch to the one more appropriate to your use case. - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - When using ImGui, your programming IDE if your friend: follow the declaration of variables, functions and types to find comments about them. - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize (application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic integration you don't need to worry about it all. - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory. - Every frame: - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.) - Call ImGui::NewFrame() to begin the imgui frame - You can use any ImGui function you want between NewFrame() and Render() - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler. (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) - All rendering information are stored into command-lists until ImGui::Render() is called. - ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. - Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. - Refer to the examples applications in the examples/ folder for instruction on how to setup your code. - A minimal application skeleton may be: // Application init ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; io.RenderDrawListsFn = MyRenderFunction; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. // TODO: Fill others settings of the io structure later. // Load texture atlas (there is a default font so you don't need to care about choosing a font yet) unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); // TODO: At this points you've got the texture data and you need to upload that your your graphic system: MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA) // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer. io.Fonts->TexID = (void*)texture; // Application main loop while (true) { // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.) ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = 1.0f/60.0f; io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; io.MouseDown[1] = mouse_button_1; // Call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); // Most of your application code here MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any ImGui functions as well! // Render & swap video buffers ImGui::Render(); SwapBuffers(); } - A minimal render function skeleton may be: void void MyRenderFunction(ImDrawData* draw_data)(ImDrawData* draw_data) { // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup viewport, orthographic projection matrix // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { // Render 'pcmd->ElemCount/3' texture triangles MyEngineBindTexture(pcmd->TextureId); MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer); } idx_buffer += pcmd->ElemCount; } } } - The examples/ folders contains many functional implementation of the pseudo-code above. - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated. They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide mouse inputs from the rest of your application. Read the FAQ below for more information about those flags. API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. Also read releases logs https://github.com/ocornut/imgui/releases for more details. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete). - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete). - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marg
c++
code
20,000
3,834
//================================================================================================= /*! // \file src/mathtest/smatdmatmult/LCbL3x3b.cpp // \brief Source file for the LCbL3x3b sparse matrix/dense matrix multiplication math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'LCbL3x3b'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions using LCb = blaze::LowerMatrix< blaze::CompressedMatrix<TypeB> >; using L3x3b = blaze::LowerMatrix< blaze::StaticMatrix<TypeB,3UL,3UL> >; // Creator type definitions using CLCb = blazetest::Creator<LCb>; using CL3x3b = blazetest::Creator<L3x3b>; // Running the tests for( size_t i=0UL; i<=6UL; ++i ) { RUN_SMATDMATMULT_OPERATION_TEST( CLCb( 3UL, i ), CL3x3b() ); } } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
c++
code
3,830
974
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "ui_interface.h" #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if(!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b>"); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if(rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if(!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } formatted.append(recipientElement); } fNewRecipientAllowed = false; WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } // prepare transaction for getting txFee earlier WalletModelTransaction currentTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl); else prepareStatus = model->prepareTransaction(currentTransaction); // process prepareStatus and on error generate message shown to user processSendCoinsReturn(prepareStatus, BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee())); if(prepareStatus.status != WalletModel::OK) { fNewRecipientAllowed = true; return; } qint64 txFee = currentTransaction.getTransactionFee(); QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><br />%1"); if(txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><span style='color:#aa0000;'>"); questionString.append(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee)); questionString.append("</span> "); questionString.append(tr("added as transaction fee")); } // add total amount in all subdivision units questionString.append("<hr />"); qint64 totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; foreach(BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { if(u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatWithUnit(u, totalAmount)); } questionString.append(tr("Total Amount %1 (= %2)") .arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)) .arg(alternativeUnits.join(" " + tr("or") + " "))); QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } // now send the prepared transaction WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user processSendCoinsReturn(sendStatus); if (sendStatus.status == WalletModel::OK) { accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateTabsAndLabels(); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateTabsAndLabels(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateTabsAndLabels() { setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->hide(); // If the last entry is about to be removed add an empty one if (ui->entries->count() == 1) addEntry(); entry->deleteLater(); updateTabsAndLabels(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->sendButton); QWidget::setTabOrder(ui->sendButton, ui->clearButton); QWidget::setTabOrder(ui->clearButton, ui->addButton); return ui->addButton; } void SendCoinsDialog::setAddress(const QString &address) { SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); updateTabsAndLabels(); } bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv) { QString strSendCoins = tr("Send Coins"); if (rv.paymentRequest.IsInitialized()) { // Expired payment request? const payments::PaymentDetails& details = rv.paymentRequest.getDetails(); if (details.has_expires() && (int64_t)details.expires() < GetTime()) { emit message(strSendCoins, tr("Payment request expired"), CClientUIInterface::MSG_WARNING); return false; } } else { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) { emit message(strSendCoins, tr("Invalid payment address %1").arg(rv.address), CClientUIInterface::MSG_WARNING); return false; } } pasteEntry(rv); return true; } void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(model && model->getOptionsModel()) { ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance)); } } void SendCoinsDialog::updateDisplayUnit() { setBalance(model->getBalance(), 0, 0); } void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg) { QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn. // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins() // all others are used only in WalletModel::prepareTransaction() switch(sendCoinsReturn.status) { case WalletModel::InvalidAddress: msgParams.first = tr("The recipient address is not valid, please recheck."); break; case WalletModel::InvalidAmount: msgParams.first = tr("The amount to pay must be larger than 0."); break; case WalletModel::AmountExceedsBalance: msgParams.first = tr("The amount exceeds your balance."); break; case WalletModel::AmountWithFeeExceedsBalance: msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg); break; case WalletModel::DuplicateAddress: msgParams.first = tr("Duplicate address found, can only send to each address once per send operation."); break; case WalletModel::TransactionCreationFailed: msgParams.first = tr("Transaction creation failed!"); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::TransactionCommitFailed: msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); msgParams.second = CClientUIInterface::MSG_ERROR; break; // included to prevent a compiler warning. case WalletModel::OK: default: return; } emit message(tr("Send Coins"), msgParams.first, msgParams.second); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); if (checked) coinControlUpdateLabels(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (state == Qt::Unchecked) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->clear(); } else // use this to re-validate an already entered address coinControlChangeEdited(ui->lineEditCoinControlChange->text()); ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString& text) { if (model && model->getAddressTableModel()) { // Default to no change address until verified CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); CBitcoinAddress addr = CBitcoinAddress(text.toStdString()); if (text.isEmpty()) // Nothing entered { ui->labelCoinControlChangeLabel->setText(""); } else if (!addr.IsValid()) // Invalid address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Smileycoin address")); } else // Valid address { CPubKey pubkey; CKeyID keyid; addr.GetKeyID(keyid); if (!model->getPubKey(keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } else // Known change address { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); // Query label QString associatedLabel = model->ge
c++
code
20,000
4,233
/******************************************************************************* * This file was auto-generated using the AutoGemm.py python script. * DO NOT modify this file! Instead, make changes to scripts in * clBLAS/src/library/blas/AutoGemm/ then re-generate files * (otherwise local changes will be lost after re-generation). ******************************************************************************/ #ifndef KERNEL_SGEMM_COL_NT_B1_MX064_NX064_KX08_SRC_H #define KERNEL_SGEMM_COL_NT_B1_MX064_NX064_KX08_SRC_H const unsigned int sgemm_Col_NT_B1_MX064_NX064_KX08_workGroupNumRows = 16; const unsigned int sgemm_Col_NT_B1_MX064_NX064_KX08_workGroupNumCols = 16; const unsigned int sgemm_Col_NT_B1_MX064_NX064_KX08_microTileNumRows = 4; const unsigned int sgemm_Col_NT_B1_MX064_NX064_KX08_microTileNumCols = 4; const unsigned int sgemm_Col_NT_B1_MX064_NX064_KX08_unroll = 8; const char * const sgemm_Col_NT_B1_MX064_NX064_KX08_src ="\n" "/* sgemm_Col_NT_B1_MX064_NX064_KX08 */\n" "\n" "/* kernel parameters */\n" "#define WG_NUM_ROWS 16\n" "#define WG_NUM_COLS 16\n" "#define MICRO_TILE_NUM_ROWS 4\n" "#define MICRO_TILE_NUM_COLS 4\n" "#define MACRO_TILE_NUM_ROWS 64\n" "#define MACRO_TILE_NUM_COLS 64\n" "#define NUM_UNROLL_ITER 8\n" "\n" "#define LOCAL_ROW_PAD 0\n" "#define LOCAL_COL_PAD 0\n" "\n" "/* global memory indices */\n" "#define GET_GLOBAL_INDEX_A(ROW,COL) ((COL)*lda+(ROW))\n" "#define GET_GLOBAL_INDEX_B(ROW,COL) ((ROW)*ldb+(COL))\n" "#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n" "\n" "/* local memory indices */\n" "#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n" "#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n" "\n" "/* data types */\n" "#define DATA_TYPE_STR float\n" "#define TYPE_MAD(MULA,MULB,DST) DST = mad(MULA,MULB,DST);\n" "#define TYPE_MAD_WRITE(DST,ALPHA,REG,BETA) DST = (ALPHA)*(REG) + (BETA)*(DST);\n" "\n" "/* 4x4 micro-tile */\n" "#define MICRO_TILE \\\n" " rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n" " rA[1] = localA[offA + 1*WG_NUM_ROWS]; \\\n" " rA[2] = localA[offA + 2*WG_NUM_ROWS]; \\\n" " rA[3] = localA[offA + 3*WG_NUM_ROWS]; \\\n" " rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n" " rB[1] = localB[offB + 1*WG_NUM_COLS]; \\\n" " rB[2] = localB[offB + 2*WG_NUM_COLS]; \\\n" " rB[3] = localB[offB + 3*WG_NUM_COLS]; \\\n" " offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n" " offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n" " TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n" " TYPE_MAD(rA[0],rB[1],rC[0][1]); \\\n" " TYPE_MAD(rA[0],rB[2],rC[0][2]); \\\n" " TYPE_MAD(rA[0],rB[3],rC[0][3]); \\\n" " TYPE_MAD(rA[1],rB[0],rC[1][0]); \\\n" " TYPE_MAD(rA[1],rB[1],rC[1][1]); \\\n" " TYPE_MAD(rA[1],rB[2],rC[1][2]); \\\n" " TYPE_MAD(rA[1],rB[3],rC[1][3]); \\\n" " TYPE_MAD(rA[2],rB[0],rC[2][0]); \\\n" " TYPE_MAD(rA[2],rB[1],rC[2][1]); \\\n" " TYPE_MAD(rA[2],rB[2],rC[2][2]); \\\n" " TYPE_MAD(rA[2],rB[3],rC[2][3]); \\\n" " TYPE_MAD(rA[3],rB[0],rC[3][0]); \\\n" " TYPE_MAD(rA[3],rB[1],rC[3][1]); \\\n" " TYPE_MAD(rA[3],rB[2],rC[3][2]); \\\n" " TYPE_MAD(rA[3],rB[3],rC[3][3]); \\\n" " mem_fence(CLK_LOCAL_MEM_FENCE);\n" "\n" "__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n" "__kernel void sgemm_Col_NT_B1_MX064_NX064_KX08(\n" " __global DATA_TYPE_STR const * restrict A,\n" " __global DATA_TYPE_STR const * restrict B,\n" " __global DATA_TYPE_STR * C,\n" " DATA_TYPE_STR const alpha,\n" " DATA_TYPE_STR const beta,\n" " uint const M,\n" " uint const N,\n" " uint const K,\n" " uint const lda,\n" " uint const ldb,\n" " uint const ldc,\n" " uint const offsetA,\n" " uint const offsetB,\n" " uint const offsetC\n" ") {\n" "\n" " /* apply offsets */\n" " A += offsetA;\n" " B += offsetB;\n" " C += offsetC;\n" "\n" " /* allocate registers */\n" " DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n" " DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n" " DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n" "\n" " /* allocate local memory */\n" " __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n" " __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n" "\n" " /* work item indices */\n" " uint groupRow = get_group_id(0);\n" " uint groupCol = get_group_id(1);\n" " uint localRow = get_local_id(0);\n" " uint localCol = get_local_id(1);\n" " uint localSerial = localRow + localCol*WG_NUM_ROWS;\n" "\n" " /* global indices being loaded */\n" "#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_ROWS)\n" "#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_ROWS)\n" "#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_COLS)\n" "#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_COLS)\n" "\n" " /* loop over k */\n" " uint block_k = K / NUM_UNROLL_ITER;\n" " do {\n" "\n" " /* local indices being written */\n" "#define localARow (localSerial % MACRO_TILE_NUM_ROWS)\n" "#define localACol (localSerial / MACRO_TILE_NUM_ROWS)\n" "#define localAStride (WG_NUM_ROWS*WG_NUM_COLS)\n" "#define localBRow ( localSerial / MACRO_TILE_NUM_COLS )\n" "#define localBCol ( localSerial % MACRO_TILE_NUM_COLS )\n" "#define localBStride (WG_NUM_ROWS*WG_NUM_COLS)\n" " __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n" " __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "\n" " /* load global -> local */\n" " lA[ 0*localAStride ] = A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n" " lA[ 1*localAStride ] = A[ GET_GLOBAL_INDEX_A( globalARow(1), globalACol(1) ) ];\n" " lB[ 0*localBStride ] = B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n" " lB[ 1*localBStride ] = B[ GET_GLOBAL_INDEX_B( globalBRow(1), globalBCol(1) ) ];\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " uint offA = localRow;\n" " uint offB = localCol;\n" "\n" " /* do mads */\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" " MICRO_TILE\n" "\n" " /* shift to next k block */\n" " A += lda*NUM_UNROLL_ITER;\n" " B += ldb*NUM_UNROLL_ITER;\n" "\n" " } while (--block_k > 0);\n" "\n" "\n" " /* which global Cij index */\n" " uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n" " uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n" "\n" " /* write global Cij */\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[0][1], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[0][2], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[0][3], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[1][0], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[1][1], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[1][2], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[1][3], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[2][0], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[2][1], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[2][2], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[2][3], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[3][0], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[3][1], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[3][2], beta )\n" " TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[3][3], beta )\n" "\n" "}\n" ""; #else #endif
c++
code
8,741
2,538
/* _______ ________ \ \ / _____/ ____ ___ / | \/ \ ____/ __ \ / \ / | \ \_\ \ ___/| | \ \____|__ /\______ /\___ >___| / \/ \/ \/ \/ The MIT License (MIT) COPYRIGHT (C) 2016 FIXCOM, LLC 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, sub-license, 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 "_External.hpp" using namespace Ngen; using namespace Ngen::Diagnostic; t_testgroup(class_String); t_begin_test(class_String, HashCollision) [] (TestResult& result) { List<string> check; if(true) { check.Add(const_string("ngen")); check.Add(const_string("NGEN")); check.Add(const_string("negn")); check.Add(const_string("NEGN")); check.Add(const_string("f00")); check.Add(const_string("00f")); check.Add(const_string("0f0")); check.Add(const_string("?")); check.Add(const_string("??")); check.Add(const_string("00")); check.Add(const_string("ff")); check.Add(const_string("NGEO")); check.Add(const_string("NGEM")); check.Add(const_string("a")); check.Add(const_string("A")); check.Add(const_string("a")); check.Add(const_string("A")); check.Add(const_string("anthropologically")); check.Add(const_string("Christianizations")); check.Add(const_string("compartmentalized")); check.Add(const_string("compartmentalizes")); check.Add(const_string("comprehensibility")); check.Add(const_string("conceptualization")); check.Add(const_string("constitutionality")); check.Add(const_string("contradistinction")); check.Add(const_string("counterproductive")); check.Add(const_string("counterrevolution")); check.Add(const_string("cryptographically")); check.Add(const_string("deterministically")); check.Add(const_string("disinterestedness")); check.Add(const_string("electrocardiogram")); check.Add(const_string("electromechanical")); check.Add(const_string("extraordinariness")); check.Add(const_string("heterogeneousness")); check.Add(const_string("inappropriateness")); check.Add(const_string("incompatibilities")); check.Add(const_string("inconsequentially")); check.Add(const_string("inconsiderateness")); check.Add(const_string("indistinguishable")); check.Add(const_string("industrialization")); check.Add(const_string("institutionalized")); check.Add(const_string("institutionalizes")); check.Add(const_string("intercommunicated")); check.Add(const_string("intercommunicates")); check.Add(const_string("interdependencies")); check.Add(const_string("interdisciplinary")); check.Add(const_string("interrelationship")); check.Add(const_string("irreproducibility")); check.Add(const_string("lexicographically")); check.Add(const_string("Mediterraneanizes")); check.Add(const_string("microarchitecture")); check.Add(const_string("microinstructions")); check.Add(const_string("microprogrammable")); check.Add(const_string("miscellaneousness")); check.Add(const_string("misrepresentation")); check.Add(const_string("misunderstandings")); check.Add(const_string("Mohammedanization")); check.Add(const_string("Occidentalization")); check.Add(const_string("parameterizations")); check.Add(const_string("probabilistically")); check.Add(const_string("pseudoinstruction")); check.Add(const_string("pseudoparallelism")); check.Add(const_string("psychotherapeutic")); check.Add(const_string("reproducibilities")); check.Add(const_string("resynchronization")); check.Add(const_string("spectrophotometer")); check.Add(const_string("spectrophotometry")); check.Add(const_string("straightforwardly")); check.Add(const_string("telecommunication")); check.Add(const_string("uncontrollability")); check.Add(const_string("understandability")); check.Add(const_string("unidirectionality")); check.Add(const_string("antifundamentalist")); check.Add(const_string("autosuggestibility")); check.Add(const_string("characteristically")); check.Add(const_string("compartmentalizing")); check.Add(const_string("conceptualizations")); check.Add(const_string("consequentialities")); check.Add(const_string("contradistinctions")); check.Add(const_string("electrocardiograph")); check.Add(const_string("institutionalizing")); check.Add(const_string("interchangeability")); check.Add(const_string("intercommunicating")); check.Add(const_string("intercommunication")); check.Add(const_string("interrelationships")); check.Add(const_string("microarchitectures")); check.Add(const_string("Perpetual-notion")); check.Add(const_string("educationnation")); } List<string>::Node* i = check.Begin(); while(!isnull(i)) { string x = i->Data(); List<string>::Node* j = check.Begin(); while(!isnull(j)) { string y = j->Data(); if(x != y) { if (y.ToHashcode() == x.ToHashcode()) { result.Error("Hash-code collision was detected!"); } } j = j->Next(); } i = i->Next(); } } t_end_test t_begin_test(class_String, Add_string) [] (TestResult& result) { string hello = const_string("Hello"); string world = const_string(" World"); string helloWorld = hello + world; if(helloWorld != const_string("Hello World")) { result.Error(const_string("string was incorrectly formatted!")); } } t_end_test t_begin_test(class_String, Add_Char) [] (TestResult& result) { string str = string("A"); str.Append('a'); if(str != const_string("Aa")) { result.Error(const_string("string was incorrectly formatted.")); } if(str.Length() != 3) { result.Error(const_string("string length is incorrect.")); } } t_end_test t_begin_test(class_String, ReadTo_Char) [] (TestResult& result) { string mirrorHash = const_string("0x11:0x02@0x0F=0x00|0xDF,0xFA"); string mirrorName = const_string("Namespace:Type@void=Method|uword,float32&"); string namspc = mirrorHash.ReadTo(':'); string typnam = mirrorName.ReadTo('@'); if(namspc != const_string("0x11") || typnam != const_string("Namespace:Type")) { result.Error(const_string("string was incorrectly read.")); } } t_end_test t_begin_test(class_String, Split_Char) [] (TestResult& result) { string mirror = const_string("d:b"); auto split = mirror.Split(':'); if(split.Length() != 2) { result.Error(const_string("string was incorrectly split.")); return; } if(split[0] != const_string("d")) { result.Error(const_string("The first token was invalid.")); } if(split[1] != const_string("b")) { result.Error(const_string("The second token was invalid.")); } } t_end_test t_begin_test(class_String, FormatThree) [] (TestResult& result) { auto unform = const_string("The ~ ~ jumped over the ~."); auto params = Array<string>({ const_string("brown-red"), const_string("fox"), const_string("fence") }); auto format = string::Format(unform, params); if(format != const_string(E"The brown-red fox jumped over the fence.")) { result.Error(format); } } t_end_test t_begin_test(class_String, ExtractIntegers) [] (TestResult& result) { auto wordform = const_string("989776729"); auto numberform = wordform.ExtractUInt64(); if(numberform != 989776729){ result.Error("The number was not extracted correctly.") } } t_end_test
c++
code
8,101
2,066
#pragma once #include "Models/Model.hpp" #include "Renderer/IRenderer.hpp" #include "Renderer/Handlers/DescriptorsHandler.hpp" #include "Renderer/Pipelines/Pipeline.hpp" namespace acid { /// <summary> /// Represents a post effect shader and on application saves the result into a fbo. /// </summary> class ACID_EXPORT IPostFilter : public IRenderer { protected: DescriptorsHandler m_descriptorSet; Pipeline m_pipeline; std::shared_ptr<Model> m_model; public: /// <summary> /// Creates a new post effect filter /// </summary> /// <param name="graphicsStage"> The pipelines graphics stage. </param> /// <param name="shaderStages"> The pipelines shader stages. </param> /// <param name="defines"> A list of names that will be added as a #define. </param> IPostFilter(const GraphicsStage &graphicsStage, const std::vector<std::string> &shaderStages, const std::vector<PipelineDefine> &defines = {}); /// <summary> /// Deconstructor for the post filter. /// </summary> virtual ~IPostFilter(); virtual void Render(const CommandBuffer &commandBuffer, const Vector4 &clipPlane, const ICamera &camera) override = 0; DescriptorsHandler GetDescriptorSet() const { return m_descriptorSet; } Pipeline GetPipeline() const { return m_pipeline; } std::shared_ptr<Model> GetModel() const { return m_model; } }; }
c++
code
1,349
266
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2018 The LINC Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/linc-config.h" #endif #include "util.h" #include "support/allocators/secure.h" #include "chainparamsbase.h" #include "random.h" #include "serialize.h" #include "sync.h" #include "utilstrencodings.h" #include "utiltime.h" #include <stdarg.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <fcntl.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include <shlobj.h> #endif #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/conf.h> // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } // namespace boost using namespace std; //LINC only features bool fMasterNode = false; bool fLiteMode = false; /** nWalletBackups: 1..10 - number of automatic backups to keep 0 - disabled by command-line -1 - disabled because of some error during run-time -2 - disabled because wallet was locked and we were not able to replenish keypool */ int nWalletBackups = 10; const char * const BITCOIN_CONF_FILENAME = "linc.conf"; const char * const BITCOIN_PID_FILENAME = "lincd.pid"; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; bool fServer = false; string strMiscWarning; bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS; bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS; bool fLogThreadNames = DEFAULT_LOGTHREADNAMES; bool fLogIPs = DEFAULT_LOGIPS; volatile bool fReopenDebugLog = false; CTranslationInterface translationInterface; /** Init OpenSSL library multithreading support */ static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); // OpenSSL can optionally load a config file which lists optional loadable modules and engines. // We don't use them so we don't require the config. However some of our libs may call functions // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be // that the config appears to have been loaded and there are no modules/engines available. OPENSSL_no_config(); #ifdef WIN32 // Seed OpenSSL PRNG with current contents of the screen RAND_screen(); #endif // Seed OpenSSL PRNG with performance counter RandAddSeed(); } ~CInit() { // Securely erase the memory used by the PRNG RAND_cleanup(); // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; /** * LogPrintf() has been broken a couple of times now * by well-meaning people adding mutexes in the most straightforward way. * It breaks because it may be called by global destructors during shutdown. * Since the order of destruction of static/global objects is undefined, * defining a mutex as a global object doesn't work (the mutex gets * destroyed, and then some later destructor calls OutputDebugStringF, * maybe indirectly, and you get a core dump at shutdown trying to lock * the mutex). */ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; /** * We use boost::call_once() to make sure mutexDebugLog and * vMsgsBeforeOpenLog are initialized in a thread-safe manner. * * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog * are leaked on exit. This is ugly, but will be cleaned up by * the OS/libc. When the shutdown sequence is fully audited and * tested, explicit destruction of these objects can be implemented. */ static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static list<string> *vMsgsBeforeOpenLog; static int FileWriteStr(const std::string &str, FILE *fp) { return fwrite(str.data(), 1, str.size(), fp); } static void DebugPrintInit() { assert(mutexDebugLog == NULL); mutexDebugLog = new boost::mutex(); vMsgsBeforeOpenLog = new list<string>; } void OpenDebugLog() { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); assert(fileout == NULL); assert(vMsgsBeforeOpenLog); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered // dump buffered messages from before we opened the log while (!vMsgsBeforeOpenLog->empty()) { FileWriteStr(vMsgsBeforeOpenLog->front(), fileout); vMsgsBeforeOpenLog->pop_front(); } delete vMsgsBeforeOpenLog; vMsgsBeforeOpenLog = NULL; } bool LogAcceptCategory(const char* category) { if (category != NULL) { // Give each thread quick access to -debug settings. // This helps prevent issues debugging global destructors, // where mapMultiArgs might be deleted before another // global destructor calls LogPrint() static boost::thread_specific_ptr<set<string> > ptrCategory; if (!fDebug) { if (ptrCategory.get() != NULL) { LogPrintf("debug turned off: thread %s\n", GetThreadName()); ptrCategory.release(); } return false; } if (ptrCategory.get() == NULL) { std::string strThreadName = GetThreadName(); LogPrintf("debug turned on:\n"); for (int i = 0; i < (int)mapMultiArgs["-debug"].size(); ++i) LogPrintf(" thread %s category %s\n", strThreadName, mapMultiArgs["-debug"][i]); const vector<string>& categories = mapMultiArgs["-debug"]; ptrCategory.reset(new set<string>(categories.begin(), categories.end())); // thread_specific_ptr automatically deletes the set when the thread ends. // "linc" is a composite category enabling all LINC-related debug output if(ptrCategory->count(string("linc"))) { ptrCategory->insert(string("privatesend")); ptrCategory->insert(string("instantsend")); ptrCategory->insert(string("masternode")); ptrCategory->insert(string("spork")); ptrCategory->insert(string("keepass")); ptrCategory->insert(string("mnpayments")); ptrCategory->insert(string("gobject")); } } const set<string>& setCategories = *ptrCategory.get(); // if not debugging everything and not debugging specific category, LogPrint does nothing. if (setCategories.count(string("")) == 0 && setCategories.count(string("1")) == 0 && setCategories.count(string(category)) == 0) return false; } return true; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the timestamp when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine) { string strStamped; if (!fLogTimestamps) return str; if (*fStartedNewLine) { int64_t nTimeMicros = GetLogTimeMicros(); strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000); if (fLogTimeMicros) strStamped += strprintf(".%06d", nTimeMicros%1000000); strStamped += ' ' + str; } else strStamped = str; return strStamped; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the thread name when multiple calls are made that don't * end in a newline. Initialize it to true, and hold/manage it, in the calling context. */ static std::string LogThreadNameStr(const std::string &str, bool *fStartedNewLine) { string strThreadLogged; if (!fLogThreadNames) return str; std::string strThreadName = GetThreadName(); if (*fStartedNewLine) strThreadLogged = strprintf("%16s | %s", strThreadName.c_str(), str.c_str()); else strThreadLogged = str; return strThreadLogged; } int LogPrintStr(const std::string &str) { int ret = 0; // Returns total number of characters written static bool fStartedNewLine = true; std::string strThreadLogged = LogThreadNameStr(str, &fStartedNewLine); std::string strTimestamped = LogTimestampStr(strThreadLogged, &fStartedNewLine); if (!str.empty() && str[str.size()-1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; if (fPrintToConsole) { // print to console ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout); fflush(stdout); } else if (fPrintToDebugLog) { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // buffer if we haven't opened the log yet if (fileout == NULL) { assert(vMsgsBeforeOpenLog); ret = strTimestamped.length(); vMsgsBeforeOpenLog->push_back(strTimestamped); } else { // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } ret = FileWriteStr(strTimestamped, fileout); } } return ret; } /** Interpret string as boolean, for argument parsing */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (atoi(strValue) != 0); } /** Turn -noX into -X=0 */ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue) { if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o') { strKey = "-" + strKey.substr(3); strValue = InterpretBool(strValue) ? "0" : "1"; } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; // Interpret --foo as -foo. // If both --foo and -foo are set, the last takes effect. if (str.length() > 1 && str[1] == '-') str = str.substr(1); InterpretNegativeSetting(str, strValue); mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64_t GetArg(const std::string& strArg, int64_t nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) return InterpretBool(mapArgs[strArg]); return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "linc"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintExceptionContinue(const std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\LINC // Windows >= Vista: C:\Users\Username\AppData\Roaming\LINC // Mac: ~/Library/Application Support/LINC // Unix: ~/.linc #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "LINC"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac return pathRet / "Library/Application Support/LINC"; #else // Unix return pathRet / ".linc"; #endif #endif } static boost::filesystem::path pathCached; static boost::filesystem::path pathCachedNetSpecific; static CCriticalSection csPathCached; const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; LOCK(csPathCached); fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= BaseParams().DataDir(); fs::create_directories(path); return path; } static boost::filesystem::path backupsDirCached; static CCriticalSection csBackupsDirCached; const boost::filesystem::path &GetBackupsDir() { namespace fs = boost::filesystem; LOCK(csBackupsDirCached); fs::path &backupsDir = backupsDirCached; if (!backupsDir.empty()) return backupsDir; if (mapArgs.count("-walletbackupsdir")) { backupsDir = fs::absolute(mapArgs["-walletbackupsdir"]); // Path must exist if (fs::is_directory(backupsDir)) return backupsDir; // Fallback to default path if it doesn't LogPrintf("%s: Warning: incorrect parameter -walletbackupsdir, path must exist! Using default path.\n", __func__); strMiscWarning = _("Warning: incorrect parameter -walletbackupsdir, path must exist! Using default path."); } // Default path backupsDir = GetDataDir() / "backups"; return backupsDir; } void ClearDatadirCache() { pathCached = boost::filesystem::path(); pathCachedNetSpecific = boost::filesystem::path(); } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } boost::filesystem::path GetMasternodeConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-mnconf", "masternode.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir() / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()){ // Create empty linc.conf if it does not excist FILE* configFile = fopen(GetConfigFile().string().c_str(), "a"); if (configFile != NULL) fclose(configFile); return; // Nothing to read, so just return } set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override linc.conf string strKey = string("-") + it->string_key; string strValue = it->value[0];
c++
code
19,991
4,211
/* 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/lite/delegates/xnnpack/prelu_tester.h" #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <numeric> #include <random> #include <vector> #include <gtest/gtest.h> #include "fp16.h" // from @FP16 #include "flatbuffers/flatbuffers.h" // from @flatbuffers #include "tensorflow/lite/delegates/xnnpack/test_util.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_conversion_utils.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/version.h" namespace tflite { namespace xnnpack { void PreluTester::Test(TfLiteDelegate* delegate) const { if (INT8ChannelWiseWeights()) { ASSERT_FALSE(SlopeShape().empty()); } std::random_device random_device; auto rng = std::mt19937(random_device()); auto input_rng = std::bind(std::uniform_real_distribution<float>(-1.0f, 1.0f), std::ref(rng)); std::vector<char> buffer = CreateTfLiteModel(); const Model* model = GetModel(buffer.data()); std::unique_ptr<Interpreter> delegate_interpreter; ASSERT_EQ( InterpreterBuilder( model, ::tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates())( &delegate_interpreter), kTfLiteOk); std::unique_ptr<Interpreter> default_interpreter; ASSERT_EQ( InterpreterBuilder( model, ::tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates())( &default_interpreter), kTfLiteOk); ASSERT_TRUE(delegate_interpreter); ASSERT_TRUE(default_interpreter); ASSERT_EQ(delegate_interpreter->inputs().size(), 1); ASSERT_EQ(default_interpreter->inputs().size(), 1); ASSERT_EQ(delegate_interpreter->outputs().size(), 1); ASSERT_EQ(default_interpreter->outputs().size(), 1); ASSERT_EQ(delegate_interpreter->AllocateTensors(), kTfLiteOk); ASSERT_EQ(default_interpreter->AllocateTensors(), kTfLiteOk); ASSERT_EQ(delegate_interpreter->ModifyGraphWithDelegate(delegate), kTfLiteOk); float* default_input_data = default_interpreter->typed_input_tensor<float>(0); std::generate(default_input_data, default_input_data + ComputeSize(InputShape()), std::ref(input_rng)); float* xnnpack_input_data = delegate_interpreter->typed_input_tensor<float>(0); std::copy(default_input_data, default_input_data + ComputeSize(InputShape()), xnnpack_input_data); ASSERT_EQ(default_interpreter->Invoke(), kTfLiteOk); ASSERT_EQ(delegate_interpreter->Invoke(), kTfLiteOk); float* default_output_data = default_interpreter->typed_output_tensor<float>(0); float* xnnpack_output_data = delegate_interpreter->typed_output_tensor<float>(0); for (size_t i = 0; i < ComputeSize(OutputShape()); i++) { ASSERT_EQ(default_output_data[i], xnnpack_output_data[i]); } } std::vector<char> PreluTester::CreateTfLiteModel() const { std::random_device random_device; auto rng = std::mt19937(random_device()); auto slope_rng = std::bind(std::uniform_real_distribution<float>(0.25f, 0.5f), std::ref(rng)); flatbuffers::FlatBufferBuilder builder; std::vector<flatbuffers::Offset<OperatorCode>> operator_codes{ {CreateOperatorCode(builder, BuiltinOperator_PRELU)}}; if (FP16Weights() || INT8Weights() || INT8ChannelWiseWeights()) { operator_codes.emplace_back( CreateOperatorCode(builder, BuiltinOperator_DEQUANTIZE)); } else if (SparseWeights()) { operator_codes.emplace_back( CreateOperatorCode(builder, BuiltinOperator_DENSIFY)); } std::vector<flatbuffers::Offset<Buffer>> buffers{{ CreateBuffer(builder, builder.CreateVector({})), }}; std::vector<float> slope_scales; std::vector<int64_t> slope_zero_points; int32_t slope_quantized_dimension = 0; if (FP16Weights()) { std::vector<uint16_t> slope_data(ComputeSize(SlopeShape())); std::generate(slope_data.begin(), slope_data.end(), std::bind(fp16_ieee_from_fp32_value, slope_rng)); buffers.push_back(CreateBuffer( builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(slope_data.data()), sizeof(uint16_t) * slope_data.size()))); } else { std::vector<float> slope_data(ComputeSize(SlopeShape())); std::generate(slope_data.begin(), slope_data.end(), slope_rng); if (INT8Weights()) { std::vector<int8_t> quantized_slope_data(slope_data.size()); slope_scales.resize(1, GetInt8QuantizationScale(slope_data)); slope_zero_points.resize(1, 0); std::transform( slope_data.begin(), slope_data.end(), quantized_slope_data.begin(), std::bind(QuantizeInt8, std::placeholders::_1, 0, slope_scales[0])); buffers.push_back(CreateBuffer( builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(quantized_slope_data.data()), sizeof(int8_t) * quantized_slope_data.size()))); } else if (INT8ChannelWiseWeights()) { std::vector<int8_t> quantized_slope_data(slope_data.size()); slope_quantized_dimension = static_cast<int32_t>(SlopeShape().size()) - 1; const int32_t num_scales = SlopeShape()[slope_quantized_dimension]; slope_scales = GetInt8QuantizationScalePerChannel( slope_data.data(), slope_quantized_dimension, SlopeShape()); slope_zero_points.resize(num_scales, 0); QuantizeInt8PerChannel(slope_scales.data(), slope_zero_points.data(), slope_quantized_dimension, slope_data.data(), quantized_slope_data.data(), SlopeShape()); buffers.push_back(CreateBuffer( builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(quantized_slope_data.data()), sizeof(int8_t) * quantized_slope_data.size()))); } else { buffers.push_back(CreateBuffer( builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(slope_data.data()), sizeof(float) * slope_data.size()))); } } std::vector<flatbuffers::Offset<Tensor>> tensors; std::vector<flatbuffers::Offset<Operator>> operators; if (FP16Weights()) { tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(SlopeShape().data(), SlopeShape().size()), TensorType_FLOAT16, /*buffer=*/1)); } else if (INT8Weights() || INT8ChannelWiseWeights()) { tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(SlopeShape().data(), SlopeShape().size()), TensorType_INT8, /*buffer=*/1, /*name=*/0, CreateQuantizationParameters( builder, /*min=*/0, /*max=*/0, builder.CreateVector<float>(slope_scales), builder.CreateVector<int64_t>(slope_zero_points), /*details_type=*/QuantizationDetails_NONE, /*details=*/0, slope_quantized_dimension))); } else if (SparseWeights()) { const int dims_count = SlopeShape().size(); std::vector<flatbuffers::Offset<DimensionMetadata>> dim_metadata( dims_count); std::vector<int> traversal_order(dims_count); for (int i = 0; i < dims_count; i++) { traversal_order[i] = i; dim_metadata[i] = CreateDimensionMetadata(builder, DimensionType_DENSE, SlopeShape()[i]); } const flatbuffers::Offset<SparsityParameters> sparsity_param = CreateSparsityParameters(builder, builder.CreateVector(traversal_order), 0, builder.CreateVector(dim_metadata)); tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(SlopeShape().data(), SlopeShape().size()), TensorType_FLOAT32, /*buffer=*/1, /*name=*/0, /*quantization=*/0, /*is_variable=*/false, /*sparsity=*/sparsity_param)); } if (FP16Weights() || INT8Weights() || INT8ChannelWiseWeights()) { const std::array<int32_t, 1> dequantize_inputs{{0}}; const std::array<int32_t, 1> dequantize_outputs{{2}}; operators.emplace_back(CreateOperator( builder, /*opcode_index=*/1, builder.CreateVector<int32_t>(dequantize_inputs.data(), dequantize_inputs.size()), builder.CreateVector<int32_t>(dequantize_outputs.data(), dequantize_outputs.size()))); } else if (SparseWeights()) { const std::array<int32_t, 1> densify_inputs{{0}}; const std::array<int32_t, 1> densify_outputs{{2}}; operators.emplace_back( CreateOperator(builder, /*opcode_index=*/1, builder.CreateVector<int32_t>(densify_inputs.data(), densify_inputs.size()), builder.CreateVector<int32_t>(densify_outputs.data(), densify_outputs.size()))); } tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(InputShape().data(), InputShape().size()), TensorType_FLOAT32)); tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(SlopeShape().data(), SlopeShape().size()), TensorType_FLOAT32, /*buffer=*/ (FP16Weights() || INT8Weights() || INT8ChannelWiseWeights() || SparseWeights()) ? 0 : 1)); tensors.emplace_back(CreateTensor( builder, builder.CreateVector<int32_t>(OutputShape().data(), OutputShape().size()), TensorType_FLOAT32)); const std::array<int32_t, 2> op_inputs{ {static_cast<int>(tensors.size()) - 3, static_cast<int>(tensors.size()) - 2}}; const std::array<int32_t, 1> op_outputs{ {static_cast<int>(tensors.size()) - 1}}; operators.emplace_back(CreateOperator( builder, /*opcode_index=*/0, builder.CreateVector<int32_t>(op_inputs.data(), op_inputs.size()), builder.CreateVector<int32_t>(op_outputs.data(), op_outputs.size()))); const std::array<int32_t, 1> subgraph_inputs{ {static_cast<int32_t>(tensors.size() - 3)}}; const std::array<int32_t, 1> subgraph_outputs{ {static_cast<int32_t>(tensors.size()) - 1}}; flatbuffers::Offset<SubGraph> subgraph = CreateSubGraph( builder, builder.CreateVector(tensors.data(), tensors.size()), builder.CreateVector<int32_t>(subgraph_inputs.data(), subgraph_inputs.size()), builder.CreateVector<int32_t>(subgraph_outputs.data(), subgraph_outputs.size()), builder.CreateVector(operators.data(), operators.size())); flatbuffers::Offset<flatbuffers::String> description = builder.CreateString("PReLU model"); flatbuffers::Offset<Model> model_buffer = CreateModel( builder, TFLITE_SCHEMA_VERSION, builder.CreateVector(operator_codes.data(), operator_codes.size()), builder.CreateVector(&subgraph, 1), description, builder.CreateVector(buffers.data(), buffers.size())); builder.Finish(model_buffer); return std::vector<char>(builder.GetBufferPointer(), builder.GetBufferPointer() + builder.GetSize()); } int32_t PreluTester::ComputeSize(const std::vector<int32_t>& shape) { return std::accumulate(shape.cbegin(), shape.cend(), 1, std::multiplies<int32_t>()); } } // namespace xnnpack } // namespace tflite
c++
code
12,261
2,526
#include <iostream> using namespace std; int main() { int menu; float rate, invst, sum; cout << "Personal Finances 1.0 Menu:" << endl; cout << " 1. Personal Finance" << endl; cout << " 2. Personal Homeover" << endl; cout << " 3. Personal Gold" << endl; cout << " 4. Small Business" << endl; cout << " 5. Big Business" << endl; cout << " 6. Gold Business" << endl << endl; cout << "Make your choice: "; cin >> menu; cout << "Please enter your investment sum: "; cin >> invst; switch (menu) { case 1: {rate = 2.3; break; } case 2: {rate = 2.6; break; } case 3: {rate = 2.9; break; } case 4: {rate = 3.3; break; } case 5: {rate = 3.5; break; } case 6: {rate = 3.8; break; } } sum = invst + (invst + rate) / 100; cout << "Deposit: " << sum; return 0; }
c++
code
849
250
#include "Node.hpp" #include <QtCore/QObject> #include <utility> #include <iostream> #include "../scene/FlowScene.hpp" #include "NodeGraphicsObject.hpp" #include "NodeDataModel.hpp" #include "../connection/ConnectionGraphicsObject.hpp" #include "../connection/ConnectionState.hpp" using QtNodes::Node; using QtNodes::NodeGeometry; using QtNodes::NodeState; using QtNodes::NodeData; using QtNodes::NodeDataType; using QtNodes::NodeDataModel; using QtNodes::NodeGraphicsObject; using QtNodes::PortIndex; using QtNodes::PortType; namespace QtNodes { Node::Node(std::unique_ptr<NodeDataModel>&& dataModel) : m_uid(QUuid::createUuid()) , m_nodeDataModel(std::move(dataModel)) , m_nodeState(m_nodeDataModel) , m_nodeGeometry(m_nodeDataModel) , m_nodeGraphicsObject(nullptr) { m_nodeGeometry.recalculateSize(); // propagate data: model => node QObject::connect(m_nodeDataModel.get(), &NodeDataModel::dataUpdated, this, &Node::onDataUpdated); QObject::connect(m_nodeDataModel.get(), &NodeDataModel::embeddedWidgetSizeUpdated, this, &Node::onNodeSizeUpdated); QObject::connect(m_nodeDataModel.get(), &NodeDataModel::portUpdated, this, &Node::onPortUpdated); QObject::connect(m_nodeDataModel.get(), &NodeDataModel::captionUpdated, this, &Node::onCaptionUpdated); } Node::~Node() = default; QJsonObject Node::save() const { QJsonObject nodeJson; nodeJson["id"] = m_uid.toString(); nodeJson["model"] = m_nodeDataModel->save(); QJsonObject obj; obj["x"] = m_nodeGraphicsObject->pos().x(); obj["y"] = m_nodeGraphicsObject->pos().y(); nodeJson["position"] = obj; return nodeJson; } void Node::restore(QJsonObject const& json) { m_uid = QUuid(json["id"].toString()); QJsonObject positionJson = json["position"].toObject(); QPointF point(positionJson["x"].toDouble(), positionJson["y"].toDouble()); m_nodeGraphicsObject->setPos(point); m_nodeDataModel->restore(json["model"].toObject()); } QUuid Node::id() const { return m_uid; } void Node::reactToPossibleConnection(PortType reactingPortType, NodeDataType const& reactingDataType, QPointF const& scenePoint) { QTransform const t = m_nodeGraphicsObject->sceneTransform(); QPointF p = t.inverted().map(scenePoint); m_nodeGeometry.setDraggingPosition(p); m_nodeGraphicsObject->update(); m_nodeState.setReaction(NodeState::REACTING, reactingPortType, reactingDataType); } void Node::resetReactionToConnection() { m_nodeState.setReaction(NodeState::NOT_REACTING); m_nodeGraphicsObject->update(); } NodeGraphicsObject const& Node::nodeGraphicsObject() const { return *m_nodeGraphicsObject.get(); } NodeGraphicsObject& Node::nodeGraphicsObject() { return *m_nodeGraphicsObject.get(); } void Node::setGraphicsObject(std::unique_ptr<NodeGraphicsObject> && graphics) { m_nodeGraphicsObject = std::move(graphics); m_nodeGeometry.recalculateSize(); } NodeGeometry& Node::nodeGeometry() { return m_nodeGeometry; } NodeGeometry const& Node::nodeGeometry() const { return m_nodeGeometry; } NodeState const& Node::nodeState() const { return m_nodeState; } NodeState& Node::nodeState() { return m_nodeState; } NodeDataModel* Node::nodeDataModel() const { return m_nodeDataModel.get(); } void Node::propagateData(std::shared_ptr<NodeData> nodeData, PortIndex inPortIndex) const { m_nodeDataModel->setInData(std::move(nodeData), inPortIndex); //Recalculate the nodes visuals. A data change can result in the node taking more space than before, so this forces a recalculate+repaint on the affected node m_nodeGraphicsObject->setGeometryChanged(); m_nodeGeometry.recalculateSize(); m_nodeGraphicsObject->update(); m_nodeGraphicsObject->moveConnections(); } void Node::onDataUpdated(PortIndex index) { auto nodeData = m_nodeDataModel->outData(index); auto connections = m_nodeState.connections(PortType::Out, index); for (auto const& c : connections) c.second->propagateData(nodeData); } void Node::onNodeSizeUpdated() { if (nodeDataModel()->embeddedWidget()) { nodeDataModel()->embeddedWidget()->adjustSize(); } nodeGeometry().recalculateSize(); for (PortType type : {PortType::In, PortType::Out}) { for (auto& conn_set : nodeState().getEntries(type)) { for (auto& pair : conn_set) { Connection* conn = pair.second; conn->getConnectionGraphicsObject().move(); } } } } void Node::onPortUpdated() { nodeState().reset(m_nodeDataModel); onNodeSizeUpdated(); nodeGraphicsObject().setSelected(false); nodeGraphicsObject().setSelected(true); } void Node::onCaptionUpdated() { nodeGraphicsObject().setSelected(false); nodeGraphicsObject().setSelected(true); } }
c++
code
4,916
1,042
/* * Copyright (C) 2006 Lars Knoll <[email protected]> * Copyright (C) 2007-2009 Torch Mobile, Inc. * * This library 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 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #include "config.h" #include "TextBreakIterator.h" #include "PlatformString.h" #include <wtf/StdLibExtras.h> #include <wtf/unicode/Unicode.h> using namespace std; using namespace WTF::Unicode; namespace WebCore { // Hack, not entirely correct static inline bool isCharStop(UChar c) { CharCategory charCategory = category(c); return charCategory != Mark_NonSpacing && (charCategory != Other_Surrogate || (c < 0xd800 || c >= 0xdc00)); } static inline bool isLineStop(UChar c) { return category(c) != Separator_Line; } static inline bool isSentenceStop(UChar c) { return isPunct(c); } class TextBreakIterator { public: void reset(const UChar* str, int len) { string = str; length = len; currentPos = 0; } int first() { currentPos = 0; return currentPos; } int last() { currentPos = length; return currentPos; } virtual int next() = 0; virtual int previous() = 0; int following(int position) { currentPos = position; return next(); } int preceding(int position) { currentPos = position; return previous(); } int currentPos; const UChar* string; int length; }; struct WordBreakIterator: TextBreakIterator { virtual int next(); virtual int previous(); }; struct CharBreakIterator: TextBreakIterator { virtual int next(); virtual int previous(); }; struct LineBreakIterator: TextBreakIterator { virtual int next(); virtual int previous(); }; struct SentenceBreakIterator : TextBreakIterator { virtual int next(); virtual int previous(); }; int WordBreakIterator::next() { if (currentPos == length) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos < length) { if (haveSpace && !isSpace(string[currentPos])) break; if (isSpace(string[currentPos])) haveSpace = true; ++currentPos; } return currentPos; } int WordBreakIterator::previous() { if (!currentPos) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos > 0) { if (haveSpace && !isSpace(string[currentPos])) break; if (isSpace(string[currentPos])) haveSpace = true; --currentPos; } return currentPos; } int CharBreakIterator::next() { if (currentPos >= length) return -1; ++currentPos; while (currentPos < length && !isCharStop(string[currentPos])) ++currentPos; return currentPos; } int CharBreakIterator::previous() { if (currentPos <= 0) return -1; if (currentPos > length) currentPos = length; --currentPos; while (currentPos > 0 && !isCharStop(string[currentPos])) --currentPos; return currentPos; } int LineBreakIterator::next() { if (currentPos == length) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos < length) { if (haveSpace && !isLineStop(string[currentPos])) break; if (isLineStop(string[currentPos])) haveSpace = true; ++currentPos; } return currentPos; } int LineBreakIterator::previous() { if (!currentPos) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos > 0) { if (haveSpace && !isLineStop(string[currentPos])) break; if (isLineStop(string[currentPos])) haveSpace = true; --currentPos; } return currentPos; } int SentenceBreakIterator::next() { if (currentPos == length) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos < length) { if (haveSpace && !isSentenceStop(string[currentPos])) break; if (isSentenceStop(string[currentPos])) haveSpace = true; ++currentPos; } return currentPos; } int SentenceBreakIterator::previous() { if (!currentPos) { currentPos = -1; return currentPos; } bool haveSpace = false; while (currentPos > 0) { if (haveSpace && !isSentenceStop(string[currentPos])) break; if (isSentenceStop(string[currentPos])) haveSpace = true; --currentPos; } return currentPos; } TextBreakIterator* wordBreakIterator(const UChar* string, int length) { DEFINE_STATIC_LOCAL(WordBreakIterator, iterator, ()); iterator.reset(string, length); return &iterator; } TextBreakIterator* characterBreakIterator(const UChar* string, int length) { DEFINE_STATIC_LOCAL(CharBreakIterator, iterator, ()); iterator.reset(string, length); return &iterator; } static TextBreakIterator* staticLineBreakIterator; TextBreakIterator* acquireLineBreakIterator(const UChar* string, int length, const AtomicString&) { TextBreakIterator* lineBreakIterator = 0; if (staticLineBreakIterator) { staticLineBreakIterator->reset(string, length); swap(staticLineBreakIterator, lineBreakIterator); } if (!lineBreakIterator && string && length) { lineBreakIterator = new LineBreakIterator; lineBreakIterator->reset(string, length); } return lineBreakIterator; } void releaseLineBreakIterator(TextBreakIterator* iterator) { ASSERT(iterator); if (!staticLineBreakIterator) staticLineBreakIterator = iterator; else delete iterator; } TextBreakIterator* sentenceBreakIterator(const UChar* string, int length) { DEFINE_STATIC_LOCAL(SentenceBreakIterator, iterator, ()); iterator.reset(string, length); return &iterator; } int textBreakFirst(TextBreakIterator* breakIterator) { return breakIterator->first(); } int textBreakLast(TextBreakIterator* breakIterator) { return breakIterator->last(); } int textBreakNext(TextBreakIterator* breakIterator) { return breakIterator->next(); } int textBreakPrevious(TextBreakIterator* breakIterator) { return breakIterator->previous(); } int textBreakPreceding(TextBreakIterator* breakIterator, int position) { return breakIterator->preceding(position); } int textBreakFollowing(TextBreakIterator* breakIterator, int position) { return breakIterator->following(position); } int textBreakCurrent(TextBreakIterator* breakIterator) { return breakIterator->currentPos; } bool isTextBreak(TextBreakIterator*, int) { return true; } TextBreakIterator* cursorMovementIterator(const UChar* string, int length) { return characterBreakIterator(string, length); } } // namespace WebCore
c++
code
7,605
1,410
/* Copyright 2015 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/core/util/work_sharder.h" #include "tensorflow/core/lib/core/blocking_counter.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { void Shard(int max_parallelism, thread::ThreadPool* workers, int64 total, int64 cost_per_unit, std::function<void(int64, int64)> work) { CHECK_GE(total, 0); if (total == 0) { return; } if (max_parallelism <= 1) { // Just inline the whole work since we only have 1 thread (core). work(0, total); return; } if (max_parallelism >= workers->NumThreads()) { workers->ParallelFor(total, cost_per_unit, work); return; } cost_per_unit = std::max(1LL, cost_per_unit); // We shard [0, total) into "num_shards" shards. // 1 <= num_shards <= num worker threads // // If total * cost_per_unit is small, it is not worth shard too // much. Let us assume each cost unit is 1ns, kMinCostPerShard=10000 // is 10us. static const int64 kMinCostPerShard = 10000; const int num_shards = std::max<int>(1, std::min(static_cast<int64>(max_parallelism), total * cost_per_unit / kMinCostPerShard)); // Each shard contains up to "block_size" units. [0, total) is sharded // into: // [0, block_size), [block_size, 2*block_size), ... // The 1st shard is done by the caller thread and the other shards // are dispatched to the worker threads. The last shard may be smaller than // block_size. const int64 block_size = (total + num_shards - 1) / num_shards; CHECK_GT(block_size, 0); // total > 0 guarantees this. if (block_size >= total) { work(0, total); return; } const int num_shards_used = (total + block_size - 1) / block_size; BlockingCounter counter(num_shards_used - 1); for (int64 start = block_size; start < total; start += block_size) { auto limit = std::min(start + block_size, total); workers->Schedule([&work, &counter, start, limit]() { work(start, limit); // Compute the shard. counter.DecrementCount(); // The shard is done. }); } // Inline execute the 1st shard. work(0, std::min(block_size, total)); counter.Wait(); } } // end namespace tensorflow
c++
code
2,866
602
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "ast.h" #include "code-stubs.h" #include "compiler.h" #include "ic.h" #include "macro-assembler.h" #include "stub-cache.h" #include "type-info.h" #include "ic-inl.h" #include "objects-inl.h" namespace v8 { namespace internal { TypeInfo TypeInfo::TypeFromValue(Handle<Object> value) { TypeInfo info; if (value->IsSmi()) { info = TypeInfo::Smi(); } else if (value->IsHeapNumber()) { info = TypeInfo::IsInt32Double(HeapNumber::cast(*value)->value()) ? TypeInfo::Integer32() : TypeInfo::Double(); } else if (value->IsString()) { info = TypeInfo::String(); } else { info = TypeInfo::Unknown(); } return info; } TypeFeedbackOracle::TypeFeedbackOracle(Handle<Code> code, Handle<Context> global_context, Isolate* isolate) { global_context_ = global_context; isolate_ = isolate; BuildDictionary(code); ASSERT(reinterpret_cast<Address>(*dictionary_.location()) != kHandleZapValue); } Handle<Object> TypeFeedbackOracle::GetInfo(unsigned ast_id) { int entry = dictionary_->FindEntry(ast_id); return entry != NumberDictionary::kNotFound ? Handle<Object>(dictionary_->ValueAt(entry)) : Handle<Object>::cast(isolate_->factory()->undefined_value()); } bool TypeFeedbackOracle::LoadIsMonomorphicNormal(Property* expr) { Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsMap()) return true; if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); return code->is_keyed_load_stub() && code->ic_state() == MONOMORPHIC && Code::ExtractTypeFromFlags(code->flags()) == NORMAL && code->FindFirstMap() != NULL && !CanRetainOtherContext(code->FindFirstMap(), *global_context_); } return false; } bool TypeFeedbackOracle::LoadIsMegamorphicWithTypeInfo(Property* expr) { Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); Builtins* builtins = isolate_->builtins(); return code->is_keyed_load_stub() && *code != builtins->builtin(Builtins::kKeyedLoadIC_Generic) && code->ic_state() == MEGAMORPHIC; } return false; } bool TypeFeedbackOracle::StoreIsMonomorphicNormal(Expression* expr) { Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsMap()) return true; if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); return code->is_keyed_store_stub() && code->ic_state() == MONOMORPHIC && Code::ExtractTypeFromFlags(code->flags()) == NORMAL && code->FindFirstMap() != NULL && !CanRetainOtherContext(code->FindFirstMap(), *global_context_); } return false; } bool TypeFeedbackOracle::StoreIsMegamorphicWithTypeInfo(Expression* expr) { Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); Builtins* builtins = isolate_->builtins(); return code->is_keyed_store_stub() && *code != builtins->builtin(Builtins::kKeyedStoreIC_Generic) && *code != builtins->builtin(Builtins::kKeyedStoreIC_Generic_Strict) && code->ic_state() == MEGAMORPHIC; } return false; } bool TypeFeedbackOracle::CallIsMonomorphic(Call* expr) { Handle<Object> value = GetInfo(expr->id()); return value->IsMap() || value->IsSmi() || value->IsJSFunction(); } Handle<Map> TypeFeedbackOracle::LoadMonomorphicReceiverType(Property* expr) { ASSERT(LoadIsMonomorphicNormal(expr)); Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); Map* first_map = code->FindFirstMap(); ASSERT(first_map != NULL); return CanRetainOtherContext(first_map, *global_context_) ? Handle<Map>::null() : Handle<Map>(first_map); } return Handle<Map>::cast(map_or_code); } Handle<Map> TypeFeedbackOracle::StoreMonomorphicReceiverType(Expression* expr) { ASSERT(StoreIsMonomorphicNormal(expr)); Handle<Object> map_or_code = GetInfo(expr->id()); if (map_or_code->IsCode()) { Handle<Code> code = Handle<Code>::cast(map_or_code); Map* first_map = code->FindFirstMap(); ASSERT(first_map != NULL); return CanRetainOtherContext(first_map, *global_context_) ? Handle<Map>::null() : Handle<Map>(first_map); } return Handle<Map>::cast(map_or_code); } void TypeFeedbackOracle::LoadReceiverTypes(Property* expr, Handle<String> name, SmallMapList* types) { Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, NORMAL); CollectReceiverTypes(expr->id(), name, flags, types); } void TypeFeedbackOracle::StoreReceiverTypes(Assignment* expr, Handle<String> name, SmallMapList* types) { Code::Flags flags = Code::ComputeMonomorphicFlags(Code::STORE_IC, NORMAL); CollectReceiverTypes(expr->id(), name, flags, types); } void TypeFeedbackOracle::CallReceiverTypes(Call* expr, Handle<String> name, CallKind call_kind, SmallMapList* types) { int arity = expr->arguments()->length(); // Note: Currently we do not take string extra ic data into account // here. Code::ExtraICState extra_ic_state = CallIC::Contextual::encode(call_kind == CALL_AS_FUNCTION); Code::Flags flags = Code::ComputeMonomorphicFlags(Code::CALL_IC, NORMAL, extra_ic_state, OWN_MAP, arity); CollectReceiverTypes(expr->id(), name, flags, types); } CheckType TypeFeedbackOracle::GetCallCheckType(Call* expr) { Handle<Object> value = GetInfo(expr->id()); if (!value->IsSmi()) return RECEIVER_MAP_CHECK; CheckType check = static_cast<CheckType>(Smi::cast(*value)->value()); ASSERT(check != RECEIVER_MAP_CHECK); return check; } Handle<JSObject> TypeFeedbackOracle::GetPrototypeForPrimitiveCheck( CheckType check) { JSFunction* function = NULL; switch (check) { case RECEIVER_MAP_CHECK: UNREACHABLE(); break; case STRING_CHECK: function = global_context_->string_function(); break; case NUMBER_CHECK: function = global_context_->number_function(); break; case BOOLEAN_CHECK: function = global_context_->boolean_function(); break; } ASSERT(function != NULL); return Handle<JSObject>(JSObject::cast(function->instance_prototype())); } Handle<JSFunction> TypeFeedbackOracle::GetCallTarget(Call* expr) { return Handle<JSFunction>::cast(GetInfo(expr->id())); } bool TypeFeedbackOracle::LoadIsBuiltin(Property* expr, Builtins::Name id) { return *GetInfo(expr->id()) == isolate_->builtins()->builtin(id); } TypeInfo TypeFeedbackOracle::CompareType(CompareOperation* expr) { Handle<Object> object = GetInfo(expr->id()); TypeInfo unknown = TypeInfo::Unknown(); if (!object->IsCode()) return unknown; Handle<Code> code = Handle<Code>::cast(object); if (!code->is_compare_ic_stub()) return unknown; CompareIC::State state = static_cast<CompareIC::State>(code->compare_state()); switch (state) { case CompareIC::UNINITIALIZED: // Uninitialized means never executed. return TypeInfo::Uninitialized(); case CompareIC::SMIS: return TypeInfo::Smi(); case CompareIC::HEAP_NUMBERS: return TypeInfo::Number(); case CompareIC::SYMBOLS: case CompareIC::STRINGS: return TypeInfo::String(); case CompareIC::OBJECTS: case CompareIC::KNOWN_OBJECTS: // TODO(kasperl): We really need a type for JS objects here. return TypeInfo::NonPrimitive(); case CompareIC::GENERIC: default: return unknown; } } bool TypeFeedbackOracle::IsSymbolCompare(CompareOperation* expr) { Handle<Object> object = GetInfo(expr->id()); if (!object->IsCode()) return false; Handle<Code> code = Handle<Code>::cast(object); if (!code->is_compare_ic_stub()) return false; CompareIC::State state = static_cast<CompareIC::State>(code->compare_state()); return state == CompareIC::SYMBOLS; } Handle<Map> TypeFeedbackOracle::GetCompareMap(CompareOperation* expr) { Handle<Object> object = GetInfo(expr->id()); if (!object->IsCode()) return Handle<Map>::null(); Handle<Code> code = Handle<Code>::cast(object); if (!code->is_compare_ic_stub()) return Handle<Map>::null(); CompareIC::State state = static_cast<CompareIC::State>(code->compare_state()); if (state != CompareIC::KNOWN_OBJECTS) { return Handle<Map>::null(); } Map* first_map = code->FindFirstMap(); ASSERT(first_map != NULL); return CanRetainOtherContext(first_map, *global_context_) ? Handle<Map>::null() : Handle<Map>(first_map); } TypeInfo TypeFeedbackOracle::UnaryType(UnaryOperation* expr) { Handle<Object> object = GetInfo(expr->id()); TypeInfo unknown = TypeInfo::Unknown(); if (!object->IsCode()) return unknown; Handle<Code> code = Handle<Code>::cast(object); ASSERT(code->is_unary_op_stub()); UnaryOpIC::TypeInfo type = static_cast<UnaryOpIC::TypeInfo>( code->unary_op_type()); switch (type) { case UnaryOpIC::SMI: return TypeInfo::Smi(); case UnaryOpIC::HEAP_NUMBER: return TypeInfo::Double(); default: return unknown; } } TypeInfo TypeFeedbackOracle::BinaryType(BinaryOperation* expr) { Handle<Object> object = GetInfo(expr->id()); TypeInfo unknown = TypeInfo::Unknown(); if (!object->IsCode()) return unknown; Handle<Code> code = Handle<Code>::cast(object); if (code->is_binary_op_stub()) { BinaryOpIC::TypeInfo type = static_cast<BinaryOpIC::TypeInfo>( code->binary_op_type()); BinaryOpIC::TypeInfo result_type = static_cast<BinaryOpIC::TypeInfo>( code->binary_op_result_type()); switch (type) { case BinaryOpIC::UNINITIALIZED: // Uninitialized means never executed. return TypeInfo::Uninitialized(); case BinaryOpIC::SMI: switch (result_type) { case BinaryOpIC::UNINITIALIZED: case BinaryOpIC::SMI: return TypeInfo::Smi(); case BinaryOpIC::INT32: return TypeInfo::Integer32(); case BinaryOpIC::HEAP_NUMBER: return TypeInfo::Double(); default: return unknown; } case BinaryOpIC::INT32: if (expr->op() == Token::DIV || result_type == BinaryOpIC::HEAP_NUMBER) { return TypeInfo::Double(); } return TypeInfo::Integer32(); case BinaryOpIC::HEAP_NUMBER: return TypeInfo::Double(); case BinaryOpIC::BOTH_STRING: return TypeInfo::String(); case BinaryOpIC::STRING: case BinaryOpIC::GENERIC: return unknown; default: return unknown; } } return unknown; } TypeInfo TypeFeedbackOracle::SwitchType(CaseClause* clause) { Handle<Object> object = GetInfo(clause->CompareId()); TypeInfo unknown = TypeInfo::Unknown(); if (!object->IsCode()) return unknown; Handle<Code> code = Handle<Code>::cast(object); if (!code->is_compare_ic_stub()) return unknown; CompareIC::State state = static_cast<CompareIC::State>(code->compare_state()); switch (state) { case CompareIC::UNINITIALIZED: // Uninitialized means never executed. // TODO(fschneider): Introduce a separate value for never-executed ICs. return unknown; case CompareIC::SMIS: return TypeInfo::Smi(); case CompareIC::STRINGS: return TypeInfo::String(); case CompareIC::SYMBOLS: return TypeInfo::Symbol(); case CompareIC::HEAP_NUMBERS: return TypeInfo::Number(); case CompareIC::OBJECTS: case CompareIC::KNOWN_OBJECTS: // TODO(kasperl): We really need a type for JS objects here. return TypeInfo::NonPrimitive(); case CompareIC::GENERIC: default: return unknown; } } TypeInfo TypeFeedbackOracle::IncrementType(CountOperation* expr) { Handle<Object> object = GetInfo(expr->CountId()); TypeInfo unknown = TypeInfo::Unknown(); if (!object->IsCode()) return unknown; Handle<Code> code = Handle<Code>::cast(object); if (!code->is_binary_op_stub()) return unknown; BinaryOpIC::TypeInfo type = static_cast<BinaryOpIC::TypeInfo>( code->binary_op_type()); switch (type) { case BinaryOpIC::UNINITIALIZED: case BinaryOpIC::SMI: return TypeInfo::Smi(); case BinaryOpIC::INT32: return TypeInfo::Integer32(); case BinaryOpIC::HEAP_NUMBER: return TypeInfo::Double(); case BinaryOpIC::BOTH_STRING: case BinaryOpIC::STRING: case BinaryOpIC::GENERIC: return unknown; default: return unknown; } UNREACHABLE(); return unknown; } void TypeFeedbackOracle::CollectReceiverTypes(unsigned ast_id, Handle<String> name, Code::Flags flags, SmallMapList* types) { Handle<Object> object = GetInfo(ast_id); if (object->IsUndefined() || object->IsSmi()) return; if (*object == isolate_->builtins()->builtin(Builtins::kStoreIC_GlobalProxy)) { // TODO(fschneider): We could collect the maps and signal that // we need a generic store (or load) here. ASSERT(Handle<Code>::cast(object)->ic_state() == MEGAMORPHIC); } else if (object->IsMap()) { types->Add(Handle<Map>::cast(object)); } else if (FLAG_collect_megamorphic_maps_from_stub_cache && Handle<Code>::cast(object)->ic_state() == MEGAMORPHIC) { types->Reserve(4); ASSERT(object->IsCode()); isolate_->stub_cache()->CollectMatchingMaps(types, *name, flags, global_context_); } } // Check if a map originates from a given global context. We use this // information to filter out maps from different context to avoid // retaining objects from different tabs in Chrome via optimized code. bool TypeFeedbackOracle::CanRetainOtherContext(Map* map, Context* global_context) { Object* constructor = NULL; while (!map->prototype()->IsNull()) { constructor = map->constructor(); if (!constructor->IsNull()) { // If the constructor is not null or a JSFunction, we have to // conservatively assume that it may retain a global context. if (!constructor->IsJSFunction()) return true; // Check if the constructor directly references a foreign context. if (CanRetainOtherContext(JSFunction::cast(constructor), global_context)) { return true; } } map = HeapObject::cast(map->prototype())->map(); } constructor = map->constructor(); if (constructor->IsNull()) return false; JSFunction* function = JSFunction::cast(constructor); return CanRetainOtherContext(function, global_context); } bool TypeFeedbackOracle::CanRetainOtherContext(JSFunction* function, Context* global_context) { return function->context()->global() != global_context->global() && function->context()->global() != global_context->builtins(); } static void AddMapIfMissing(Handle<Map> map, SmallMapList* list) { for (int i = 0; i < list->length(); ++i) { if (list->at(i).is_identical_to(map)) return; } list->Add(map); } void TypeFeedbackOracle::CollectKeyedReceiverTypes(unsigned ast_id, SmallMapList* types) { Handle<Object> object = GetInfo(ast_id); if (!object->IsCode()) return; Handle<Code> code = Handle<Code>::cast(object); if (code->kind() == Code::KEYED_LOAD_IC || code->kind() == Code::KEYED_STORE_IC) { AssertNoAllocation no_allocation; int mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT); for (RelocIterator it(*code, mask); !it.done(); it.next()) { RelocInfo* info = it.rinfo(); Object* object = info->target_object(); if (object->IsMap()) { Map* map = Map::cast(object); if (!CanRetainOtherContext(map, *global_context_)) { AddMapIfMissing(Handle<Map>(map), types); } } } } } byte TypeFeedbackOracle::ToBooleanTypes(unsigned ast_id) { Handle<Object> object = GetInfo(ast_id); return object->IsCode() ? Handle<Code>::cast(object)->to_boolean_state() : 0; } // Things are a bit tricky here: The iterator for the RelocInfos and the infos // themselves are not GC-safe, so we first get all infos, then we create the // dictionary (possibly triggering GC), and finally we relocate the collected // infos before we process them. void TypeFeedbackOracle::BuildDictionary(Handle<Code> code) { AssertNoAllocation no_allocation; ZoneList<RelocInfo> infos(16); HandleScope scope; GetRelocInfos(code, &infos); CreateDictionary(code, &infos); ProcessRelocInfos(&infos); // Allocate handle in the parent scope. dictionary_ = scope.CloseAndEscape(dictionary_); } void TypeFeedbackOracle::GetRelocInfos(Handle<Code> code, ZoneList<RelocInfo>* infos) { int mask = RelocInfo::ModeMask(RelocInfo::CODE_TARGET_WITH_ID); for (RelocIterator it(*code, mask); !it.done(); it.next()) { infos->Add(*it.rinfo()); } } void TypeFeedbackOracle::CreateDictionary(Handle<Code> code, ZoneList<RelocInfo>* infos) { DisableAssertNoAllocation allocation_allowed; byte* old_start = code->instruction_start(); dictionary_ = FACTORY->NewNumberDictionary(infos->length()); byte* new_start = code->instruction_start(); RelocateRelocInfos(infos, old_start, new_start); } void TypeFeedbackOracle::RelocateRelocInfos(ZoneList<RelocInfo>* infos, byte* old_start, byte
c++
code
20,000
4,362
/* * @Author: five-5 * @Description: Implementation set with bst * @Date: 2019-04-02 * @LastEditTime: 2019-04-02 */ #include "../Tree/Binary Search Tree/BSTRecur.hpp" #include "set.h" template <typename T> class BSTSet:public set<T> { public: BSTSet(){ bst = new BST<T>(); } void add(T e) override{ bst->Add(e); } void remove(T e) override{ bst->Remove(e); } bool contains(T e) override{ return bst->Contains(e); } int size() override{ return bst->size(); } bool empty() override{ return bst->empty(); } private: BST<T> *bst; };
c++
code
642
164
/** * \file * dnn/test/common/dct_ref.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "test/common/dct_ref.h" namespace megdnn { namespace test { struct FixCase { std::vector<int> mask_offset; std::vector<int> mask_val; }; using Param = DctChannelSelectForward::Param; static inline FixCase get_fix_mask(Param::FastImpl impl) { std::vector<int> fix_32_mask_offset{0, 16, 24, 32}; std::vector<int> fix_32_mask_val{0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 0, 1, 8, 16, 9, 2, 3, 10, 0, 1, 8, 16, 9, 2, 3, 10}; megdnn_assert(impl == Param::FastImpl::FIX_32_MASK, "only support gen FIX_32_MASK"); return {fix_32_mask_offset, fix_32_mask_val}; } CheckerHelper::TensorsConstriant gen_dct_constriant( const size_t /* n */, const size_t ic, const size_t ih, const size_t iw, const size_t oc, Param param) { auto constraint = [=](CheckerHelper::TensorValueArray& tensors_orig) { const size_t block = param.dct_block_size; const int block_c = param.format == Param::Format::NCHW4 ? 4 : 1; megdnn_assert(oc % block_c == 0, "oc mod block_c must == 0"); std::shared_ptr<DctTestcase> test_case_ptr = DctTestcase::make(); DctTestcase& test_case = *test_case_ptr.get(); UniformIntRNG rng(0, 255); UniformIntRNG mask_rng(0, 64 / block_c - 1); const size_t no_mask_oc = ic * block * block; megdnn_assert(ih % block == 0, "%zu mod %zu == 0", ih, block); megdnn_assert(iw % block == 0, "%zu mod %zu == 0", iw, block); TensorND mask_offset; TensorND mask_val; std::vector<int>& mask_offset_vec = test_case.mask_offset_vec; std::vector<int>& mask_val_vec = test_case.mask_val_vec; UniformIntRNG rng_oc(0, oc); if (param.fastImpl == Param::FastImpl::FIX_32_MASK) { auto fix_32_mask = get_fix_mask(Param::FastImpl::FIX_32_MASK); mask_offset_vec = fix_32_mask.mask_offset; mask_val_vec = fix_32_mask.mask_val; megdnn_assert(oc == 32, "oc must eq 32"); } else if (no_mask_oc > oc) { size_t remain_oc = oc; mask_offset_vec.resize(ic + 1); mask_val_vec.resize(oc); mask_offset_vec[0] = 0; for (size_t ic_idx = 0; ic_idx < ic; ++ic_idx) { size_t random_len = (int)rng_oc.gen_single_val() * block_c; size_t mask_len = (ic_idx == ic - 1) || (remain_oc == 0) ? remain_oc : random_len % remain_oc; megdnn_assert(mask_len % block_c == 0, "mask_len mod block_c == 0, but %zu mod %d ", mask_len, block_c); const size_t oc_idx = mask_offset_vec[ic_idx]; remain_oc -= mask_len; mask_offset_vec[ic_idx + 1] = oc_idx + mask_len; for (size_t mask_idx = 0; mask_idx < mask_len; ++mask_idx) { mask_val_vec[oc_idx + mask_idx] = (int)mask_rng.gen_single_val(); } } } mask_offset = TensorND(mask_offset_vec.data(), {{mask_offset_vec.size()}, dtype::Int32()}); mask_val = TensorND(mask_val_vec.data(), {{mask_val_vec.size()}, dtype::Int32()}); if (tensors_orig.size() > 1) { megdnn_assert(tensors_orig.size() == 4, "tensors_orig.size() == 4"); megdnn_assert(mask_offset_vec.size() >= 2, "mask_offset_vec.size() >= 2"); megdnn_assert(tensors_orig[1].layout == mask_offset.layout, "tensors_orig[1].layout == mask_offset.layout"); megdnn_assert(tensors_orig[2].layout == mask_val.layout, "tensors_orig[2].layout == mask_val.layout"); auto naive_handle = create_cpu_handle(2, false); megdnn_memcpy_D2D(naive_handle.get(), tensors_orig[1].raw_ptr, mask_offset.raw_ptr, mask_offset.layout.span().dist_byte()); megdnn_memcpy_D2D(naive_handle.get(), tensors_orig[2].raw_ptr, mask_val.raw_ptr, mask_val.layout.span().dist_byte()); } }; return constraint; } std::shared_ptr<DctTestcase> gen_dct_case(const size_t n, const size_t ic, const size_t ih, const size_t iw, const size_t oc, Param param, DType dst_dtype, bool correct_result) { const size_t block = param.dct_block_size; const int block_c = param.format == Param::Format::NCHW4 ? 4 : 1; megdnn_assert(oc % block_c == 0, "oc mod block_c must == 0"); std::shared_ptr<DctTestcase> test_case_ptr = DctTestcase::make(); DctTestcase& test_case = *test_case_ptr.get(); UniformIntRNG rng(0, 255); UniformIntRNG mask_rng(0, 64 / block_c - 1); const size_t input_elements = n * ic * ih * iw; const size_t no_mask_oc = ic * block * block; megdnn_assert(ih % block == 0, "%zu mod %zu == 0", ih, block); megdnn_assert(iw % block == 0, "%zu mod %zu == 0", iw, block); std::vector<uint8_t>& inp_vec = test_case.inp_vec; inp_vec.resize(input_elements); TensorShape input_shape{n, ic, ih, iw}; for (auto& elm : inp_vec) { elm = (uint8_t)rng.gen_single_val(); } auto src = TensorND(inp_vec.data(), {input_shape, dtype::Uint8()}); TensorND mask_offset; TensorND mask_val; std::vector<int>& mask_offset_vec = test_case.mask_offset_vec; std::vector<int>& mask_val_vec = test_case.mask_val_vec; UniformIntRNG rng_oc(0, oc); if (param.fastImpl == Param::FastImpl::FIX_32_MASK) { auto fix_32_mask = get_fix_mask(Param::FastImpl::FIX_32_MASK); mask_offset_vec = fix_32_mask.mask_offset; mask_val_vec = fix_32_mask.mask_val; megdnn_assert(oc == 32, "oc must eq 32"); } else if (no_mask_oc > oc) { size_t remain_oc = oc; mask_offset_vec.resize(ic + 1); mask_val_vec.resize(oc); mask_offset_vec[0] = 0; for (size_t ic_idx = 0; ic_idx < ic; ++ic_idx) { size_t random_len = (int)rng_oc.gen_single_val() * block_c; size_t mask_len = (ic_idx == ic - 1) || (remain_oc == 0) ? remain_oc : random_len % remain_oc; megdnn_assert(mask_len % block_c == 0, "mask_len mod block_c == 0, but %zu mod %d ", mask_len, block_c); const size_t oc_idx = mask_offset_vec[ic_idx]; remain_oc -= mask_len; mask_offset_vec[ic_idx + 1] = oc_idx + mask_len; for (size_t mask_idx = 0; mask_idx < mask_len; ++mask_idx) { mask_val_vec[oc_idx + mask_idx] = (int)mask_rng.gen_single_val(); } } } mask_offset = TensorND(mask_offset_vec.data(), {{mask_offset_vec.size()}, dtype::Int32()}); mask_val = TensorND(mask_val_vec.data(), {{mask_val_vec.size()}, dtype::Int32()}); if (mask_offset_vec.size() >= 2) { test_case.testcase_in = { src, mask_offset, mask_val, {nullptr, {{}, dst_dtype}}}; } else { test_case.testcase_in = {src, {}, {}, {nullptr, {{}, dst_dtype}}}; } auto naive_handle = create_cpu_handle(2, false); auto opr_naive = naive_handle->create_operator<DctChannelSelectForward>(); opr_naive->param() = param; using Proxy = OprProxy<DctChannelSelectForward>; Proxy naive_proxy; TensorLayout temp_dst_layout; temp_dst_layout.dtype = dst_dtype; TensorLayoutArray layouts{src.layout, mask_offset.layout, mask_val.layout, temp_dst_layout}; naive_proxy.deduce_layout(opr_naive.get(), layouts); const size_t output_elements = layouts[3].total_nr_elems(); std::vector<float>& output_vec = test_case.output_vec; output_vec.resize(output_elements); auto dst = TensorND(output_vec.data(), layouts[3]); DctTestcase::TensorValueArray testcase_naive; testcase_naive.emplace_back(test_case.testcase_in[0]); testcase_naive.emplace_back(test_case.testcase_in[1]); testcase_naive.emplace_back(test_case.testcase_in[2]); testcase_naive.emplace_back(dst); if (correct_result) { naive_proxy.exec(opr_naive.get(), testcase_naive); } test_case.testcase_out = {{}, {}, {}, dst}; return test_case_ptr; } } // namespace test } // namespace megdnn // vim: syntax=cpp.doxygen
c++
code
9,322
1,897
/** * @file rs_model.hpp * @author Ryan Curtin * * This is a model for range search. It is useful in that it provides an easy * way to serialize a model, abstracts away the different types of trees, and * also reflects the RangeSearch API and automatically directs to the right * tree types. */ #ifndef MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_HPP #define MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_HPP #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/cover_tree.hpp> #include <mlpack/core/tree/rectangle_tree.hpp> #include "range_search.hpp" namespace mlpack { namespace range { class RSModel { public: enum TreeTypes { KD_TREE, COVER_TREE, R_TREE, R_STAR_TREE, BALL_TREE, X_TREE, HILBERT_R_TREE, R_PLUS_TREE, R_PLUS_PLUS_TREE }; private: TreeTypes treeType; size_t leafSize; //! If true, we randomly project the data into a new basis before search. bool randomBasis; //! Random projection matrix. arma::mat q; //! The mostly-specified type of the range search model. template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> using RSType = RangeSearch<metric::EuclideanDistance, arma::mat, TreeType>; // Only one of these pointers will be non-NULL. //! kd-tree based range search object (NULL if not in use). RSType<tree::KDTree>* kdTreeRS; //! Cover tree based range search object (NULL if not in use). RSType<tree::StandardCoverTree>* coverTreeRS; //! R tree based range search object (NULL if not in use). RSType<tree::RTree>* rTreeRS; //! R* tree based range search object (NULL if not in use). RSType<tree::RStarTree>* rStarTreeRS; //! Ball tree based range search object (NULL if not in use). RSType<tree::BallTree>* ballTreeRS; //! X tree based range search object (NULL if not in use). RSType<tree::XTree>* xTreeRS; //! Hilbert R tree based range search object (NULL if not in use). RSType<tree::HilbertRTree>* hilbertRTreeRS; //! R+ tree based range search object (NULL if not in use). RSType<tree::RPlusTree>* rPlusTreeRS; //! R++ tree based range search object (NULL if not in use). RSType<tree::RPlusPlusTree>* rPlusPlusTreeRS; public: /** * Initialize the RSModel with the given type and whether or not a random * basis should be used. * * @param treeType Type of tree to use. * @param randomBasis Whether or not to use a random basis. */ RSModel(const TreeTypes treeType = TreeTypes::KD_TREE, const bool randomBasis = false); /** * Clean memory, if necessary. */ ~RSModel(); //! Serialize the range search model. template<typename Archive> void Serialize(Archive& ar, const unsigned int /* version */); //! Expose the dataset. const arma::mat& Dataset() const; //! Get whether the model is in single-tree search mode. bool SingleMode() const; //! Modify whether the model is in single-tree search mode. bool& SingleMode(); //! Get whether the model is in naive search mode. bool Naive() const; //! Modify whether the model is in naive search mode. bool& Naive(); //! Get the leaf size (applicable to everything but the cover tree). size_t LeafSize() const { return leafSize; } //! Modify the leaf size (applicable to everything but the cover tree). size_t& LeafSize() { return leafSize; } //! Get the type of tree. TreeTypes TreeType() const { return treeType; } //! Modify the type of tree (don't do this after the model has been built). TreeTypes& TreeType() { return treeType; } //! Get whether a random basis is used. bool RandomBasis() const { return randomBasis; } //! Modify whether a random basis is used (don't do this after the model has //! been built). bool& RandomBasis() { return randomBasis; } /** * Build the reference tree on the given dataset with the given parameters. * This takes possession of the reference set to avoid a copy. * * @param referenceSet Set of reference points. * @param leafSize Leaf size of tree (ignored for the cover tree). * @param naive Whether naive search should be used. * @param singleMode Whether single-tree search should be used. */ void BuildModel(arma::mat&& referenceSet, const size_t leafSize, const bool naive, const bool singleMode); /** * Perform range search. This takes possession of the query set, so the query * set will not be usable after the search. For more information on the * output format, see RangeSearch<>::Search(). * * @param querySet Set of query points. * @param range Range to search for. * @param neighbors Output: neighbors falling within the desired range. * @param distances Output: distances of neighbors. */ void Search(arma::mat&& querySet, const math::Range& range, std::vector<std::vector<size_t>>& neighbors, std::vector<std::vector<double>>& distances); /** * Perform monochromatic range search, with the reference set as the query * set. For more information on the output format, see * RangeSearch<>::Search(). * * @param range Range to search for. * @param neighbors Output: neighbors falling within the desired range. * @param distances Output: distances of neighbors. */ void Search(const math::Range& range, std::vector<std::vector<size_t>>& neighbors, std::vector<std::vector<double>>& distances); private: /** * Return a string representing the name of the tree. This is used for * logging output. */ std::string TreeName() const; /** * Clean up memory. */ void CleanMemory(); }; } // namespace range } // namespace mlpack // Include implementation (of Serialize() and inline functions). #include "rs_model_impl.hpp" #endif
c++
code
5,906
1,256
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<> struct char_traits<char16_t> // static constexpr bool eq(char_type c1, char_type c2); #include <string> #include <cassert> #include "test_macros.h" int main() { #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS #if TEST_STD_VER >= 11 assert(std::char_traits<char16_t>::eq(u'a', u'a')); assert(!std::char_traits<char16_t>::eq(u'a', u'A')); #endif #endif // _LIBCPP_HAS_NO_UNICODE_CHARS }
c++
code
798
219
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 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. * * Authors: Kevin Lim */ #ifndef __CPU_ACTIVITY_HH__ #define __CPU_ACTIVITY_HH__ #include "base/trace.hh" #include "cpu/timebuf.hh" /** * ActivityRecorder helper class that informs the CPU if it can switch * over to being idle or not. It works by having a time buffer as * long as any time buffer in the CPU, and the CPU and all of its * stages inform the ActivityRecorder when they write to any time * buffer. The ActivityRecorder marks a 1 in the "0" slot of the time * buffer any time a stage writes to a time buffer, and it advances * its time buffer at the same time as all other stages. The * ActivityRecorder also records if a stage has activity to do next * cycle. The recorder keeps a count of these two. Thus any time the * count is non-zero, there is either communication still in flight, * or activity that still must be done, meaning that the CPU can not * idle. If count is zero, then the CPU can safely idle as it has no * more outstanding work to do. */ class ActivityRecorder { public: ActivityRecorder(const std::string &name, int num_stages, int longest_latency, int count); ~ActivityRecorder(); /** Records that there is activity this cycle. */ void activity(); /** Advances the activity buffer, decrementing the activityCount * if active communication just left the time buffer, and * determining if there is no activity. */ void advance(); /** Marks a stage as active. */ void activateStage(const int idx); /** Deactivates a stage. */ void deactivateStage(const int idx); /** Returns how many things are active within the recorder. */ int getActivityCount() { return activityCount; } /** Sets the count to a starting value. Can be used to disable * the idling option. */ void setActivityCount(int count) { activityCount = count; } /** Returns if the CPU should be active. */ bool active() { return activityCount; } /** Clears the time buffer and the activity count. */ void reset(); /** Debug function to dump the contents of the time buffer. */ void dump(); /** Debug function to ensure that the activity count matches the * contents of the time buffer. */ void validate(); private: // provide name() for DPRINTF. std::string _name; const std::string &name() { return _name; } /** Time buffer that tracks if any cycles has active communication * in them. It should be as long as the longest communication * latency in the system. Each time any time buffer is written, * the activity buffer should also be written to. The * activityBuffer is advanced along with all the other time * buffers, so it should have a 1 somewhere in it only if there * is active communication in a time buffer. */ TimeBuffer<bool> activityBuffer; /** Longest latency time buffer in the CPU. */ int longestLatency; /** Tracks how many stages and cycles of time buffer have * activity. Stages increment this count when they switch to * active, and decrement it when they switch to * inactive. Whenever a cycle that previously had no information * is written in the time buffer, this is incremented. When a * cycle that had information exits the time buffer due to age, * this count is decremented. When the count is 0, there is no * activity in the CPU, and it can be descheduled. */ int activityCount; /** Number of stages that can be marked as active or inactive. */ int numStages; /** Records which stages are active/inactive. */ bool *stageActive; }; #endif // __CPU_ACTIVITY_HH__
c++
code
5,297
1,055
#include <Arduino.h> #include "AbstractSwitch.h" #define DEBOUNCE_TIME_IN_MILLIS 10 AbstractSwitch::AbstractSwitch(uint8_t pin) { this->pin = pin; this->state = STATE_OFF; this->firstTimestamp = 0; } void AbstractSwitch::init() { pinMode(pin, INPUT_PULLUP); digitalWrite(pin, HIGH); } void AbstractSwitch::loop() { int readPin = digitalRead(pin); switch (state) { case STATE_OFF: if (readPin == LOW) { state = STATE_FIRST_ON; firstTimestamp = millis(); } break; case STATE_FIRST_ON: if (millis() - firstTimestamp < DEBOUNCE_TIME_IN_MILLIS) { break; } if (readPin == LOW) { // STATE_ON detected state = STATE_ON; onSwitchOnInternal(); } else { state = STATE_OFF; } break; case STATE_ON: if (readPin == HIGH) { state = STATE_FIRST_OFF; firstTimestamp = millis(); } break; case STATE_FIRST_OFF: if (millis() - firstTimestamp < DEBOUNCE_TIME_IN_MILLIS) { break; } if (readPin == LOW) { state = STATE_ON; } else { // STATE_OFF detected state = STATE_OFF; onSwitchOffInternal(); } break; } } bool AbstractSwitch::isPressed() { if(state == STATE_ON) { return true; } return false; }
c++
code
1,571
255
#include "il2cpp-config.h" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Array.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Assembly.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\AssemblyName.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\CCW.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\CCWBase.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\COM.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\COMEntryPoints.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Class.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\ClassInlines.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\ComObjectBase.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Domain.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Enum.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Event.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Exception.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Field.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\GenericClass.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\GenericContainer.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\GlobalMetadata.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Image.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\InternalCalls.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\LastError.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Liveness.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\MarshalAlloc.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\MemoryInformation.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\MetadataAlloc.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\MetadataCache.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\MetadataLoader.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Method.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Module.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Monitor.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Object.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Parameter.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Path.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\PlatformInvoke.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Profiler.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Property.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\RCW.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Random.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Reflection.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Runtime.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\ScopedThreadAttacher.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\StackTrace.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\String.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Thread.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\ThreadPool.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\ThreadPoolMs.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\Type.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\VisualizerHelpers.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\WaitHandle.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\WeakReference.cpp" #include "C:\Program Files\Unity\Editor\Data\il2cpp\libil2cpp\vm\WindowsRuntime.cpp"
c++
code
4,120
413
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin developers // Copyright (c) 2014-2018 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2018 The MyPartyCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "accumulators.h" #include "addrman.h" #include "alert.h" #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" #include "init.h" #include "kernel.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeman.h" #include "merkleblock.h" #include "net.h" #include "obfuscation.h" #include "pow.h" #include "spork.h" #include "sporkdb.h" #include "swifttx.h" #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #include "utilmoneystr.h" #include "primitives/zerocoin.h" #include "libzerocoin/Denominations.h" #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> using namespace boost; using namespace std; using namespace libzerocoin; #if defined(NDEBUG) #error "MyPartyCoin cannot be compiled without assertions." #endif // 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4) #define SCRIPT_OFFSET 6 // For Script size (BIGNUM/Uint256 size) #define BIGNUM_SIZE 4 /** * Global state */ CCriticalSection cs_main; BlockMap mapBlockIndex; map<uint256, uint256> mapProofOfStake; set<pair<COutPoint, unsigned int> > setStakeSeen; map<unsigned int, unsigned int> mapHashedBlocks; CChain chainActive; CBlockIndex* pindexBestHeader = NULL; int64_t nTimeBestReceived = 0; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; bool fTxIndex = true; bool fIsBareMultisigStd = true; bool fCheckBlockIndex = false; bool fVerifyingBlocks = false; unsigned int nCoinCacheSize = 5000; bool fAlerts = DEFAULT_ALERTS; unsigned int nStakeMinAge = 2 * 60 * 60; int64_t nReserveBalance = 0; /** Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) * We are ~100 times smaller then bitcoin now (2015-06-23), set minRelayTxFee only 10 times higher * so it's still 10 times lower comparing to bitcoin. */ CFeeRate minRelayTxFee = CFeeRate(10000); CTxMemPool mempool(::minRelayTxFee); struct COrphanTx { CTransaction tx; NodeId fromPeer; }; map<uint256, COrphanTx> mapOrphanTransactions; map<uint256, set<uint256> > mapOrphanTransactionsByPrev; map<uint256, int64_t> mapRejectedBlocks; void EraseOrphansFor(NodeId peer); static void CheckBlockIndex(); /** Constant stuff for coinbase transactions we create: */ CScript COINBASE_FLAGS; const string strMessageMagic = "DarkNet Signed Message:\n"; // Internal stuff namespace { struct CBlockIndexWorkComparator { bool operator()(CBlockIndex* pa, CBlockIndex* pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; // Identical blocks. return false; } }; CBlockIndex* pindexBestInvalid; /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though. */ set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */ multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile; int nLastBlockFile = 0; /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. */ CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; /** * Sources of received blocks, to be able to send them reject messages or ban * them, if processing happens afterwards. Protected by cs_main. */ map<uint256, NodeId> mapBlockSource; /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { uint256 hash; CBlockIndex* pindex; //! Optional. int64_t nTime; //! Time of "getdata" request in microseconds. int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested. bool fValidatedHeaders; //! Whether this block has validated headers at the time of request. }; map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight; /** Number of blocks in flight with validated headers. */ int nQueuedValidatedHeaders = 0; /** Number of preferable block download peers. */ int nPreferredDownload = 0; /** Dirty block index entries. */ set<CBlockIndex*> setDirtyBlockIndex; /** Dirty block file entries. */ set<int> setDirtyFileInfo; } // anon namespace ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets namespace { struct CMainSignals { /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */ boost::signals2::signal<void(const CTransaction&, const CBlock*)> SyncTransaction; /** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */ // XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<void(const uint256&)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void(const CBlockLocator&)> SetBestChain; /** Notifies listeners about an inventory item being seen on the network. */ boost::signals2::signal<void(const uint256&)> Inventory; /** Tells listeners to broadcast their data. */ boost::signals2::signal<void()> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void(const CBlock&, const CValidationState&)> BlockChecked; } g_signals; } // anon namespace void RegisterValidationInterface(CValidationInterface* pwalletIn) { g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2)); // XX42 g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1)); g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1)); g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1)); g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1)); g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn)); g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2)); } void UnregisterValidationInterface(CValidationInterface* pwalletIn) { g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2)); g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn)); g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1)); g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1)); g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1)); // XX42 g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1)); g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2)); } void UnregisterAllValidationInterfaces() { g_signals.BlockChecked.disconnect_all_slots(); g_signals.Broadcast.disconnect_all_slots(); g_signals.Inventory.disconnect_all_slots(); g_signals.SetBestChain.disconnect_all_slots(); g_signals.UpdatedTransaction.disconnect_all_slots(); // XX42 g_signals.EraseTransaction.disconnect_all_slots(); g_signals.SyncTransaction.disconnect_all_slots(); } void SyncWithWallets(const CTransaction& tx, const CBlock* pblock) { g_signals.SyncTransaction(tx, pblock); } ////////////////////////////////////////////////////////////////////////////// // // Registration of network node signals. // namespace { struct CBlockReject { unsigned char chRejectCode; string strRejectReason; uint256 hashBlock; }; /** * Maintain validation-specific state about nodes, protected by cs_main, instead * by CNode's own locks. This simplifies asynchronous operation, where * processing of incoming data is done after the ProcessMessage call returns, * and we're no longer holding the node's locks. */ struct CNodeState { //! The peer's address CService address; //! Whether we have a fully established connection. bool fCurrentlyConnected; //! Accumulated misbehaviour score for this peer. int nMisbehavior; //! Whether this peer should be disconnected and banned (unless whitelisted). bool fShouldBan; //! String name of this peer (debugging/logging purposes). std::string name; //! List of asynchronously-determined block rejections to notify this peer about. std::vector<CBlockReject> rejects; //! The best known block we know this peer has announced. CBlockIndex* pindexBestKnownBlock; //! The hash of the last unknown block this peer has announced. uint256 hashLastUnknownBlock; //! The last full block we both have. CBlockIndex* pindexLastCommonBlock; //! Whether we've started headers synchronization with this peer. bool fSyncStarted; //! Since when we're stalling block download progress (in microseconds), or 0. int64_t nStallingSince; list<QueuedBlock> vBlocksInFlight; int nBlocksInFlight; //! Whether we consider this a preferred download peer. bool fPreferredDownload; CNodeState() { fCurrentlyConnected = false; nMisbehavior = 0; fShouldBan = false; pindexBestKnownBlock = NULL; hashLastUnknownBlock = uint256(0); pindexLastCommonBlock = NULL; fSyncStarted = false; nStallingSince = 0; nBlocksInFlight = 0; fPreferredDownload = false; } }; /** Map maintaining per-node state. Requires cs_main. */ map<NodeId, CNodeState> mapNodeState; // Requires cs_main. CNodeState* State(NodeId pnode) { map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); if (it == mapNodeState.end()) return NULL; return &it->second; } int GetHeight() { while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } return chainActive.Height(); } } void UpdatePreferredDownload(CNode* node, CNodeState* state) { nPreferredDownload -= state->fPreferredDownload; // Whether this node should be marked as a preferred download node. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; nPreferredDownload += state->fPreferredDownload; } void InitializeNode(NodeId nodeid, const CNode* pnode) { LOCK(cs_main); CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; state.name = pnode->addrName; state.address = pnode->addr; } void FinalizeNode(NodeId nodeid) { LOCK(cs_main); CNodeState* state = State(nodeid); if (state->fSyncStarted) nSyncStarted--; if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { AddressCurrentlyConnected(state->address); } BOOST_FOREACH (const QueuedBlock& entry, state->vBlocksInFlight) mapBlocksInFlight.erase(entry.hash); EraseOrphansFor(nodeid); nPreferredDownload -= state->fPreferredDownload; mapNodeState.erase(nodeid); } // Requires cs_main. void MarkBlockAsReceived(const uint256& hash) { map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end()) { CNodeState* state = State(itInFlight->second.first); nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; state->vBlocksInFlight.erase(itInFlight->second.second); state->nBlocksInFlight--; state->nStallingSince = 0; mapBlocksInFlight.erase(itInFlight); } } // Requires cs_main. void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex = NULL) { CNodeState* state = State(nodeid); assert(state != NULL); // Make sure it's not listed somewhere already. MarkBlockAsReceived(hash); QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL}; nQueuedValidatedHeaders += newentry.fValidatedHeaders; list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); state->nBlocksInFlight++; mapBlocksInFlight[hash] = std::make_pair(nodeid, it); } /** Check whether the last unknown block a peer advertized is not yet known. */ void ProcessBlockAvailability(NodeId nodeid) { CNodeState* state = State(nodeid); assert(state != NULL); if (state->hashLastUnknownBlock != 0) { BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) { if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = itOld->second; state->hashLastUnknownBlock = uint256(0); } } } /** Update tracking information about which blocks a peer is assumed to have. */ void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) { CNodeState* state = State(nodeid); assert(state != NULL); ProcessBlockAvailability(nodeid); BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { // An actually better block was announced. if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = it->second; } else { // An unknown block was announced; just assume that the latest one is the best one. state->hashLastUnknownBlock = hash; } } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-NULL. */ CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; } /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has * at most count entries. */ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) { if (count == 0) return; vBlocks.reserve(vBlocks.size() + count); CNodeState* state = State(nodeid); assert(state != NULL); // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { // This peer has nothing interesting. return; } if (state->pindexLastCommonBlock == NULL) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor // of their current tip anymore. Go back enough to fix that. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; std::vector<CBlockIndex*> vToFetch; CBlockIndex* pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; } // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the mean time, update // pindexLastCommonBlock as long as all ancestors are already downloaded. BOOST_FOREACH (CBlockIndex* pindex, vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; } if (pindex->nStatus & BLOCK_HAVE_DATA) { if (pindex->nChainTx) state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { // The block is not already downloaded, and not yet in flight. if (pindex->nHeight > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != nodeid) { // We aren't able to fetch anything, but we would be if the download window was one larger. nodeStaller = waitingfor; } return;
c++
code
19,985
3,981
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "operators/bloom_filter.h" #include <fstream> #include "gtest/gtest.h" #include "storage/utils/util.h" using namespace testing; class BloomFilterTestFixture : public testing::Test { protected: void SetUp() override {} }; TEST_F(BloomFilterTestFixture, Test1) { auto d = read_from_file("/Users/corrado/hustle/data/ssb-1/date.hsl"); auto col = d->get_column(0); BloomFilter b(col->length()); b.set_memory(10); // Build for (int i = 0; i < col->num_chunks(); i++) { auto chunk = std::static_pointer_cast<arrow::Int64Array>(col->chunk(i)); for (int j = 0; j < chunk->length(); j++) { auto val = chunk->Value(j); b.insert(val); } } // Probe for (int i = 0; i < col->num_chunks(); i++) { auto chunk = std::static_pointer_cast<arrow::Int64Array>(col->chunk(i)); for (int j = 0; j < chunk->length(); j++) { auto val = chunk->Value(j); b.probe(j); } b.update(); } std::cout << std::endl; std::cout << "hit rate = " << b.get_hit_rate() << std::endl; }
c++
code
1,843
455
/* Copyright 2021, The TensorFlow Federated Authors. 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 ==============================================================================*/ // This file contains the pybind11 defintions for exposing the C++ Executor // interface in Python. // // General principles: // - Python methods defined here (e.g. `.def_*()`) should not contain // "business logic". That should be implemented on the underlying C++ class. // The only logic that may exist here is parameter/result conversions (e.g. // `OwnedValueId` -> `ValueId`, etc). #include <cstdint> #include <limits> #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "grpcpp/grpcpp.h" #include "include/pybind11/detail/common.h" #include "include/pybind11/pybind11.h" #include "include/pybind11/stl.h" #include "pybind11_abseil/absl_casters.h" #include "pybind11_abseil/status_casters.h" #include "pybind11_protobuf/wrapped_proto_caster.h" #include "tensorflow_federated/cc/core/impl/executors/cardinalities.h" #include "tensorflow_federated/cc/core/impl/executors/composing_executor.h" #include "tensorflow_federated/cc/core/impl/executors/executor.h" #include "tensorflow_federated/cc/core/impl/executors/federating_executor.h" #include "tensorflow_federated/cc/core/impl/executors/reference_resolving_executor.h" #include "tensorflow_federated/cc/core/impl/executors/remote_executor.h" #include "tensorflow_federated/cc/core/impl/executors/tensorflow_executor.h" #include "tensorflow_federated/proto/v0/computation.pb.h" #include "tensorflow_federated/proto/v0/executor.pb.h" namespace tensorflow_federated { namespace py = ::pybind11; namespace { //////////////////////////////////////////////////////////////////////////////// // The Python module defintion `executor_bindings`. // // This will be used with `import executor_bindings` on the Python side. This // module should _not_ be directly imported into the public pip API. The methods // here will raise `NotOkStatus` errors from absl, which are not user friendly. //////////////////////////////////////////////////////////////////////////////// PYBIND11_MODULE(executor_bindings, m) { py::google::ImportStatusModule(); pybind11_protobuf::ImportWrappedProtoCasters(); using pybind11_protobuf::WithWrappedProtos; m.doc() = "Bindings for the C++ "; // Provide an `OwnedValueId` class to handle return values from the // `Executor` interface. // // Note: no `init<>()` method defined, this object is only constructor from // Executor instances. py::class_<OwnedValueId>(m, "OwnedValueId") .def_property_readonly("ref", &OwnedValueId::ref) .def("__str__", [](const OwnedValueId& self) { return absl::StrCat(self.ref()); }) .def("__repr__", [](const OwnedValueId& self) { return absl::StrCat("<OwnedValueId: ", self.ref(), ">"); }); // We provide ComposingChild as an opaque object so that they can be returned // from pybind functions. py::class_<ComposingChild>(m, "ComposingChild") .def("__repr__", [](const ComposingChild& self) { return absl::StrCat( "<ComposingChild with num clients: ", self.num_clients(), ">"); }); // Provide the `Executor` interface. // // A `dispose` method is purposely not exposed. Though `Executor::Dispose` // exists in C++, Python should call `Dispose` via the `OwnedValueId` // destructor during garbage collection. // // Note: no `init<>()` method defined, must be constructed useing the create_* // methods defined below. py::class_<Executor, // PyExecutor trampoline goes here when ready std::shared_ptr<Executor>>(m, "Executor") .def("create_value", WithWrappedProtos(&Executor::CreateValue), py::arg("value_pb"), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_struct", WithWrappedProtos(&Executor::CreateStruct), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_selection", WithWrappedProtos(&Executor::CreateSelection), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("create_call", WithWrappedProtos(&Executor::CreateCall), py::arg("function"), // Allow `argument` to be `None`. py::arg("argument").none(true), py::return_value_policy::move, py::call_guard<py::gil_scoped_release>()) .def("materialize", WithWrappedProtos([](Executor& e, const ValueId& value_id) -> absl::StatusOr<v0::Value> { // Construct a new `v0::Value` to write to and return it to // Python. v0::Value value_pb; absl::Status result = e.Materialize(value_id, &value_pb); if (!result.ok()) { return result; } return value_pb; }), py::call_guard<py::gil_scoped_release>()); // Executor construction methods. m.def("create_tensorflow_executor", &CreateTensorFlowExecutor, py::arg("max_concurrent_computation_calls") = py::none(), "Creates a TensorFlowExecutor."); m.def("create_reference_resolving_executor", &CreateReferenceResolvingExecutor, "Creates a ReferenceResolvingExecutor", py::arg("inner_executor")); m.def("create_federating_executor", &CreateFederatingExecutor, py::arg("inner_executor"), py::arg("cardinalities"), "Creates a FederatingExecutor."); m.def("create_composing_child", &ComposingChild::Make, py::arg("executor"), py::arg("cardinalities"), "Creates a ComposingExecutor."); m.def("create_composing_executor", &CreateComposingExecutor, py::arg("server"), py::arg("children"), "Creates a ComposingExecutor."); m.def("create_remote_executor", py::overload_cast<std::shared_ptr<grpc::ChannelInterface>, const CardinalityMap&>(&CreateRemoteExecutor), py::arg("channel"), py::arg("cardinalities"), "Creates a RemoteExecutor."); py::class_<grpc::ChannelInterface, std::shared_ptr<grpc::ChannelInterface>>( m, "GRPCChannelInterface"); m.def( "create_insecure_grpc_channel", [](const std::string& target) -> std::shared_ptr<grpc::ChannelInterface> { auto channel_options = grpc::ChannelArguments(); channel_options.SetMaxSendMessageSize( std::numeric_limits<int32_t>::max()); channel_options.SetMaxReceiveMessageSize( std::numeric_limits<int32_t>::max()); return grpc::CreateCustomChannel( target, grpc::InsecureChannelCredentials(), channel_options); }, pybind11::return_value_policy::take_ownership); } } // namespace } // namespace tensorflow_federated
c++
code
7,407
1,443
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <cmath> #include <cstddef> #include <ngraph/op/util/attr_types.hpp> #include <ngraph/shape.hpp> #include "ngraph/runtime/reference/autobroadcast_binop.hpp" namespace ngraph { namespace runtime { namespace reference { template <typename T> void prelu(const T* arg, const T* slope, T* out, const Shape& arg_shape, const Shape& slope_shape) { Shape slope_shape_tmp = slope_shape; const auto channel_dim_idx = arg_shape.size() > 1 ? 1 : 0; if (slope_shape.size() == 1 && arg_shape[channel_dim_idx] == slope_shape[0]) { Shape channel_slope_shape(arg_shape.size(), 1); channel_slope_shape[channel_dim_idx] = slope_shape[0]; std::swap(slope_shape_tmp, channel_slope_shape); } autobroadcast_binop(arg, slope, out, arg_shape, slope_shape_tmp, ngraph::op::AutoBroadcastType::NUMPY, [](T x, T y) -> T { return x < T(0) ? T(x * y) : x; }); } } // namespace reference } // namespace runtime } // namespace ngraph
c++
code
1,255
230
#include <iostream> #include <random> using namespace std; // Q値が入力される行列,経路のない項目は-1 double q[12][12] = { {-1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1}, { 0, -1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1}, {-1, 0, -1, 0, -1, -1, 0, -1, -1, -1, -1, -1}, {-1, -1, 0, -1, -1, -1, -1, 0, -1, -1, -1, -1}, { 0, -1, -1, -1, -1, 0, -1, -1, 0, -1, -1, -1}, {-1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1, -1}, {-1, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1}, {-1, -1, -1, 0, -1, -1, 0, -1, -1, -1, -1, 0}, {-1, -1, -1, -1, 0, -1, -1, -1, -1, 0, -1, -1}, {-1, -1, -1, -1, -1, 0, -1, -1, 0, -1, 0, -1}, {-1, -1, -1, -1, -1, -1, 0, -1, -1, 0, -1, 0}, {-1, -1, -1, -1, -1, -1, -1, 0, -1, -1, 0, -1} }; double a = 0.1; // 学習係数α double g = 0.9; // 割引率γ // Q値を初期化する void initialize() { random_device rnd; // 乱数生成器 mt19937 mt(rnd()); // メルセンヌ・ツイスタ生成器 uniform_real_distribution<> rand100(0, 99); // [0,99]の範囲の一様乱数(実数) // [0,99]の範囲の乱数を生成し,-1でない項目の初期値にする for (int i = 0; i < 12; ++i) for (int j = 0; j < 12; ++j) if (q[i][j] != -1) q[i][j] = rand100(mt); } // Q値を更新しながら10ステップ移動する void action() { int st = 0; // 状態s_t int st1 = 0; // 状態s_t+1 double max_st = 0; // 状態s_tからのQ値の最大値 double max_st1 = 0; // 状態s_t+1からのQ値の最大値 // 初期値0から10ステップ移動 for (int t = 0; t < 10; ++t) { // Q値が最大になる状態に移動する for (int i = 0; i < 12; ++i) { if (max_st < q[st][i]) { max_st = q[st][i]; st1 = i; } } // 状態s_t+1からのQ値の最大値を求める for (int i = 0; i < 12; ++i) if (max_st1 < q[st1][i]) max_st1 = q[st1][i]; // 更新式に従ってQ値を更新する,s_t+1がGoalのときだけ報酬は100 if (st1 == 11) q[st][st1] = q[st][st1] + a * (100 + g * max_st1 - q[st][st1]); else q[st][st1] = q[st][st1] + a * (g * max_st1 - q[st][st1]); // s_t+1に移動して同じ処理を繰り返す st = st1; // 各値を初期化する max_st = 0; max_st1 = 0; } } // 結果を出力する void print_q(void) { cout << endl; cout << " --" << (int)q[8][9] << "--> " << " --" << (int)q[9][10] << "--> " << " --" << (int)q[10][11] << "-->" << endl; cout << " <--" << (int)q[9][8] << "-- " << " <--" << (int)q[10][9] << "-- " << " <--" << (int)q[11][10] << "-- " << endl << endl; cout << (int)q[4][8] << "|" << (int)q[8][4] << " " << (int)q[5][9] << "|" << (int)q[9][5] << " " << (int)q[6][10] << "|" << (int)q[10][6] << " " << (int)q[7][11] << "|" << (int)q[11][7] << endl << endl; cout << " --" << (int)q[4][5] << "--> " << " --" << (int)q[5][6] << "--> " << " --" << (int)q[6][7] << "-->" << endl; cout << " <--" << (int)q[5][4] << "-- " << " <--" << (int)q[6][5] << "-- " << " <--" << (int)q[7][6] << "-- " << endl << endl; cout << (int)q[0][4] << "|" << (int)q[4][0] << " " << (int)q[1][5] << "|" << (int)q[5][1] << " " << (int)q[2][6] << "|" << (int)q[6][2] << " " << (int)q[3][7] << "|" << (int)q[7][3] << endl << endl; cout << " --" << (int)q[0][1] << "--> " << " --" << (int)q[1][2] << "--> " << " --" << (int)q[2][3] << "-->" << endl; cout << " <--" << (int)q[1][0] << "-- " << " <--" << (int)q[2][1] << "-- " << " <--" << (int)q[3][2] << "-- " << endl << endl; cout << "-------------------------------------------------" << endl; } // main関数 int main() { initialize(); print_q(); // 初期状態 for (int i = 0; i < 1000; ++i) action(); print_q(); // 1000行動後 for (int i = 0; i < 5000; ++i) action(); print_q(); // 10000行動後 }
c++
code
3,916
1,526
/***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <XnOS.h> //--------------------------------------------------------------------------- // Globals //--------------------------------------------------------------------------- static const XnUInt32 xnOSStrCRC32Table[0x100] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XN_C_API XnStatus xnOSStrPrefix(const XnChar* cpPrefixString, XnChar* cpDestString, const XnUInt32 nDestLength) { // Local function variables XnChar* cpTempBuffer = NULL; XnUInt32 nOutStringLength = 0; // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpPrefixString); XN_VALIDATE_INPUT_PTR(cpDestString); // Calculate the final string length nOutStringLength = strlen(cpPrefixString) + strlen(cpDestString); // Make sure the destination string can hold the required information if (nOutStringLength >= nDestLength) { return (XN_STATUS_INTERNAL_BUFFER_TOO_SMALL); } // Allocate the temp buffer XN_VALIDATE_CALLOC(cpTempBuffer, XnChar, nOutStringLength + sizeof(XnChar)); // Prefix the string strncat (cpTempBuffer, cpPrefixString, nOutStringLength); strncat (cpTempBuffer, cpDestString, nOutStringLength); // Copy the temp buffer into the output strncpy (cpDestString, cpTempBuffer, nOutStringLength); // Free the temporary buffer xnOSFree(cpTempBuffer); // All is good... return (XN_STATUS_OK); } XN_C_API XnStatus xnOSStrAppend(XnChar* cpDestString, const XnChar* cpSrcString, const XnUInt32 nDestLength) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpSrcString); XN_VALIDATE_INPUT_PTR(cpDestString); // Make sure the destination string can hold the required information if (strlen(cpSrcString) + strlen(cpDestString) >= nDestLength) { return (XN_STATUS_INTERNAL_BUFFER_TOO_SMALL); } // Prefix the string strncat (cpDestString, cpSrcString, nDestLength - strlen(cpDestString)); // All is good... return (XN_STATUS_OK); } XN_C_API XnStatus xnOSStrCopy(XnChar* cpDestString, const XnChar* cpSrcString, const XnUInt32 nDestLength) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpSrcString); XN_VALIDATE_INPUT_PTR(cpDestString); // Make sure the destination string can hold the required information if (strlen(cpSrcString) >= nDestLength) { return (XN_STATUS_INTERNAL_BUFFER_TOO_SMALL); } // Copy the string strncpy (cpDestString, cpSrcString, nDestLength); // All is good... return (XN_STATUS_OK); } XN_C_API XnUInt32 xnOSStrLen(const XnChar* cpString) { XN_VALIDATE_PTR(cpString, 0); return (XnUInt32)strlen(cpString); } XN_C_API XnStatus xnOSStrNCopy(XnChar* cpDestString, const XnChar* cpSrcString, const XnUInt32 nCopyLength, const XnUInt32 nDestLength) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpSrcString); XN_VALIDATE_INPUT_PTR(cpDestString); // Make sure the destination string can hold the required information if (nCopyLength >= nDestLength) { return (XN_STATUS_INTERNAL_BUFFER_TOO_SMALL); } // Copy the string strncpy (cpDestString, cpSrcString, nCopyLength); // All is good... return (XN_STATUS_OK); } XN_C_API XnStatus xnOSStrCRC32(const XnChar* cpString, XnUInt32* nCRC32) { // Local function variables XnUInt32 nTempCRC32 = 0xffffffff; XnUInt32 nStrLen = 0; XnUInt32 nIdx = 0; // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpString); XN_VALIDATE_OUTPUT_PTR(nCRC32); *nCRC32 = 0; nStrLen = strlen(cpString); for (nIdx = 0; nIdx < nStrLen; nIdx++) { nTempCRC32 = (nTempCRC32 >> 8) ^ xnOSStrCRC32Table[(nTempCRC32 & 0xFF) ^ *cpString++]; } *nCRC32 = nTempCRC32 ^ 0xffffffff; // All is good... return (XN_STATUS_OK); } XN_C_API XnStatus xnOSStrNCRC32(XnUChar* cpBuffer, XnUInt32 nBufferSize, XnUInt32* nCRC32) { // Local function variables XnUInt32 nTempCRC32 = 0xffffffff; XnUInt32 nIdx = 0; // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpBuffer); XN_VALIDATE_OUTPUT_PTR(nCRC32); *nCRC32 = 0; for (nIdx = 0; nIdx < nBufferSize; nIdx++) { nTempCRC32 = (nTempCRC32 >> 8) ^ xnOSStrCRC32Table[(nTempCRC32 & 0xFF) ^ *cpBuffer++]; } *nCRC32 = nTempCRC32 ^ 0xffffffff; // All is good... return (XN_STATUS_OK); } XN_C_API XnStatus xnOSStrFormatV(XnChar* cpDestString, const XnUInt32 nDestLength, XnUInt32* pnCharsWritten, const XnChar* cpFormat, va_list args) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpDestString); XN_VALIDATE_INPUT_PTR(cpFormat); XN_VALIDATE_OUTPUT_PTR(pnCharsWritten); *pnCharsWritten = 0; XnInt32 nRes = vsprintf(cpDestString, cpFormat, args); // nRes is the number of bytes written, not including NULL termination if ((nRes == -1) || // string was truncated (nRes == nDestLength && cpDestString[nRes] != '\0')) // no space for the NULL termination { return (XN_STATUS_INTERNAL_BUFFER_TOO_SMALL); } // return byte count (string length) *pnCharsWritten = nRes; // All is good... return (XN_STATUS_OK); } XN_C_API void xnOSItoA(XnInt32 nValue, XnChar* cpStr, XnInt32 nBase) { _itoa(nValue, cpStr, nBase); } XN_C_API XnInt32 xnOSStrCmp(const XnChar* cpFirstString, const XnChar* cpSecondString) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpFirstString); XN_VALIDATE_INPUT_PTR(cpSecondString); return strcmp(cpFirstString, cpSecondString); } XN_C_API XnInt32 xnOSStrCaseCmp(const XnChar* cpFirstString, const XnChar* cpSecondString) { // Validate the input/output pointers (to make sure none of them is NULL) XN_VALIDATE_INPUT_PTR(cpFirstString); XN_VALIDATE_INPUT_PTR(cpSecondString); return _stricmp(cpFirstString, cpSecondString); }
c++
code
11,132
2,095
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, 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 "yb/rpc/rpc_context.h" #include <ostream> #include <sstream> #include <boost/core/null_deleter.hpp> #include "yb/rpc/connection.h" #include "yb/rpc/inbound_call.h" #include "yb/rpc/local_call.h" #include "yb/rpc/outbound_call.h" #include "yb/rpc/service_if.h" #include "yb/rpc/reactor.h" #include "yb/rpc/yb_rpc.h" #include "yb/util/hdr_histogram.h" #include "yb/util/metrics.h" #include "yb/util/trace.h" #include "yb/util/debug/trace_event.h" #include "yb/util/jsonwriter.h" #include "yb/util/pb_util.h" using google::protobuf::Message; DECLARE_int32(rpc_max_message_size); namespace yb { namespace rpc { using std::shared_ptr; namespace { // Wrapper for a protobuf message which lazily converts to JSON when // the trace buffer is dumped. This pushes the work of stringification // to the trace dumping process. class PbTracer : public debug::ConvertableToTraceFormat { public: enum { kMaxFieldLengthToTrace = 100 }; explicit PbTracer(const Message& msg) : msg_(msg.New()) { msg_->CopyFrom(msg); } void AppendAsTraceFormat(std::string* out) const override { pb_util::TruncateFields(msg_.get(), kMaxFieldLengthToTrace); std::stringstream ss; JsonWriter jw(&ss, JsonWriter::COMPACT); jw.Protobuf(*msg_); out->append(ss.str()); } private: const gscoped_ptr<Message> msg_; }; scoped_refptr<debug::ConvertableToTraceFormat> TracePb(const Message& msg) { return make_scoped_refptr(new PbTracer(msg)); } } // anonymous namespace RpcContext::~RpcContext() { if (call_ && !responded_) { LOG(DFATAL) << "RpcContext is destroyed, but response has not been sent, for call: " << call_->ToString(); } } RpcContext::RpcContext(std::shared_ptr<YBInboundCall> call, std::shared_ptr<google::protobuf::Message> request_pb, std::shared_ptr<google::protobuf::Message> response_pb, RpcMethodMetrics metrics) : call_(std::move(call)), request_pb_(request_pb), response_pb_(std::move(response_pb)), metrics_(metrics) { const Status s = call_->ParseParam(request_pb.get()); if (PREDICT_FALSE(!s.ok())) { RespondRpcFailure(ErrorStatusPB::ERROR_INVALID_REQUEST, s); return; } TRACE_EVENT_ASYNC_BEGIN2("rpc_call", "RPC", this, "call", call_->ToString(), "request", TracePb(*request_pb_)); } RpcContext::RpcContext(std::shared_ptr<LocalYBInboundCall> call, RpcMethodMetrics metrics) : call_(call), request_pb_(call->request(), boost::null_deleter()), response_pb_(call->response(), boost::null_deleter()), metrics_(metrics) { TRACE_EVENT_ASYNC_BEGIN2("rpc_call", "RPC", this, "call", call_->ToString(), "request", TracePb(*request_pb_)); } void RpcContext::RespondSuccess() { if (response_pb_->ByteSize() > FLAGS_rpc_max_message_size) { RespondFailure(STATUS_FORMAT(InvalidArgument, "RPC message too long: $0 vs $1", response_pb_->ByteSize(), FLAGS_rpc_max_message_size)); return; } call_->RecordHandlingCompleted(metrics_.handler_latency); TRACE_EVENT_ASYNC_END2("rpc_call", "RPC", this, "response", TracePb(*response_pb_), "trace", trace()->DumpToString(true)); call_->RespondSuccess(*response_pb_); responded_ = true; } void RpcContext::RespondFailure(const Status &status) { call_->RecordHandlingCompleted(metrics_.handler_latency); TRACE_EVENT_ASYNC_END2("rpc_call", "RPC", this, "status", status.ToString(), "trace", trace()->DumpToString(true)); call_->RespondFailure(ErrorStatusPB::ERROR_APPLICATION, status); responded_ = true; } void RpcContext::RespondRpcFailure(ErrorStatusPB_RpcErrorCodePB err, const Status& status) { call_->RecordHandlingCompleted(metrics_.handler_latency); TRACE_EVENT_ASYNC_END2("rpc_call", "RPC", this, "status", status.ToString(), "trace", trace()->DumpToString(true)); call_->RespondFailure(err, status); responded_ = true; } void RpcContext::RespondApplicationError(int error_ext_id, const std::string& message, const Message& app_error_pb) { call_->RecordHandlingCompleted(metrics_.handler_latency); TRACE_EVENT_ASYNC_END2("rpc_call", "RPC", this, "response", TracePb(app_error_pb), "trace", trace()->DumpToString(true)); call_->RespondApplicationError(error_ext_id, message, app_error_pb); responded_ = true; } size_t RpcContext::AddRpcSidecar(const Slice& car) { return call_->AddRpcSidecar(car); } void RpcContext::ResetRpcSidecars() { call_->ResetRpcSidecars(); } void RpcContext::ReserveSidecarSpace(size_t space) { call_->ReserveSidecarSpace(space); } const Endpoint& RpcContext::remote_address() const { return call_->remote_address(); } const Endpoint& RpcContext::local_address() const { return call_->local_address(); } std::string RpcContext::requestor_string() const { return yb::ToString(call_->remote_address()); } CoarseTimePoint RpcContext::GetClientDeadline() const { return call_->GetClientDeadline(); } Trace* RpcContext::trace() { return call_->trace(); } void RpcContext::Panic(const char* filepath, int line_number, const string& message) { // Use the LogMessage class directly so that the log messages appear to come from // the line of code which caused the panic, not this code. #define MY_ERROR google::LogMessage(filepath, line_number, google::GLOG_ERROR).stream() #define MY_FATAL google::LogMessageFatal(filepath, line_number).stream() MY_ERROR << "Panic handling " << call_->ToString() << ": " << message; MY_ERROR << "Request:\n" << request_pb_->DebugString(); Trace* t = trace(); if (t) { MY_ERROR << "RPC trace:"; t->Dump(&MY_ERROR, true); } MY_FATAL << "Exiting due to panic."; #undef MY_ERROR #undef MY_FATAL } void RpcContext::CloseConnection() { auto connection = call_->connection(); connection->reactor()->ScheduleReactorFunctor([connection](Reactor*) { connection->Close(); }, SOURCE_LOCATION()); } std::string RpcContext::ToString() const { return call_->ToString(); } void PanicRpc(RpcContext* context, const char* file, int line_number, const std::string& message) { if (context) { context->Panic(file, line_number, message); } else { google::LogMessage(file, line_number, google::GLOG_FATAL).stream() << message; } } } // namespace rpc } // namespace yb
c++
code
8,166
1,719
// // StreamCopierTest.cpp // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "StreamCopierTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/StreamCopier.h" #include <sstream> using Poco::StreamCopier; StreamCopierTest::StreamCopierTest(const std::string& name): CppUnit::TestCase(name) { } StreamCopierTest::~StreamCopierTest() { } void StreamCopierTest::testBufferedCopy() { { std::string src; for (int i = 0; i < 255; ++i) src += char(i); std::istringstream istr(src); std::ostringstream ostr; std::streamsize n = StreamCopier::copyStream(istr, ostr); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; std::streamsize n = StreamCopier::copyStream(istr, ostr, 100); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; std::streamsize n = StreamCopier::copyStream(istr, ostr, 128); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; std::streamsize n = StreamCopier::copyStream(istr, ostr, 512); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } } void StreamCopierTest::testUnbufferedCopy() { std::string src; for (int i = 0; i < 255; ++i) src += char(i); std::istringstream istr(src); std::ostringstream ostr; std::streamsize n = StreamCopier::copyStreamUnbuffered(istr, ostr); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } void StreamCopierTest::testCopyToString() { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::string dest; std::streamsize n = StreamCopier::copyToString(istr, dest, 100); assertTrue (src == dest); assertTrue (n == src.size()); } #if defined(POCO_HAVE_INT64) void StreamCopierTest::testBufferedCopy64() { { std::string src; for (int i = 0; i < 255; ++i) src += char(i); std::istringstream istr(src); std::ostringstream ostr; Poco::UInt64 n = StreamCopier::copyStream64(istr, ostr); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; Poco::UInt64 n = StreamCopier::copyStream64(istr, ostr, 100); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; Poco::UInt64 n = StreamCopier::copyStream64(istr, ostr, 128); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::ostringstream ostr; Poco::UInt64 n = StreamCopier::copyStream64(istr, ostr, 512); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } } void StreamCopierTest::testUnbufferedCopy64() { std::string src; for (int i = 0; i < 255; ++i) src += char(i); std::istringstream istr(src); std::ostringstream ostr; Poco::UInt64 n = StreamCopier::copyStreamUnbuffered64(istr, ostr); assertTrue (ostr.str() == src); assertTrue (n == src.size()); } void StreamCopierTest::testCopyToString64() { std::string src; for (int i = 0; i < 512; ++i) src += char(i % 256); std::istringstream istr(src); std::string dest; Poco::UInt64 n = StreamCopier::copyToString64(istr, dest, 100); assertTrue (src == dest); assertTrue (n == src.size()); } #endif void StreamCopierTest::setUp() { } void StreamCopierTest::tearDown() { } CppUnit::Test* StreamCopierTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamCopierTest"); CppUnit_addTest(pSuite, StreamCopierTest, testBufferedCopy); CppUnit_addTest(pSuite, StreamCopierTest, testUnbufferedCopy); CppUnit_addTest(pSuite, StreamCopierTest, testCopyToString); #if defined(POCO_HAVE_INT64) CppUnit_addTest(pSuite, StreamCopierTest, testBufferedCopy64); CppUnit_addTest(pSuite, StreamCopierTest, testUnbufferedCopy64); CppUnit_addTest(pSuite, StreamCopierTest, testCopyToString64); #endif return pSuite; }
c++
code
4,568
1,314
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPDFCatalog.h" #include "SkPDFTypes.h" #include "SkStream.h" #ifdef SK_BUILD_FOR_WIN #define SNPRINTF _snprintf #else #define SNPRINTF snprintf #endif //////////////////////////////////////////////////////////////////////////////// SkPDFObjRef::SkPDFObjRef(SkPDFObject* obj) : fObj(obj) { SkSafeRef(obj); } SkPDFObjRef::~SkPDFObjRef() {} void SkPDFObjRef::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { stream->writeDecAsText(catalog->getObjectNumber(fObj.get())); stream->writeText(" 0 R"); // Generation number is always 0. } void SkPDFObjRef::addResources(SkTSet<SkPDFObject*>* resourceSet, SkPDFCatalog* catalog) const { SkPDFObject* obj = catalog->getSubstituteObject(fObj); SkASSERT(obj); if (resourceSet->add(obj)) { obj->addResources(resourceSet, catalog); } } //////////////////////////////////////////////////////////////////////////////// SkPDFInt::SkPDFInt(int32_t value) : fValue(value) {} SkPDFInt::~SkPDFInt() {} void SkPDFInt::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { stream->writeDecAsText(fValue); } //////////////////////////////////////////////////////////////////////////////// SkPDFBool::SkPDFBool(bool value) : fValue(value) {} SkPDFBool::~SkPDFBool() {} void SkPDFBool::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { if (fValue) { stream->writeText("true"); } else { stream->writeText("false"); } } //////////////////////////////////////////////////////////////////////////////// SkPDFScalar::SkPDFScalar(SkScalar value) : fValue(value) {} SkPDFScalar::~SkPDFScalar() {} void SkPDFScalar::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { Append(fValue, stream); } // static void SkPDFScalar::Append(SkScalar value, SkWStream* stream) { // The range of reals in PDF/A is the same as SkFixed: +/- 32,767 and // +/- 1/65,536 (though integers can range from 2^31 - 1 to -2^31). // When using floats that are outside the whole value range, we can use // integers instead. #if !defined(SK_ALLOW_LARGE_PDF_SCALARS) if (value > 32767 || value < -32767) { stream->writeDecAsText(SkScalarRoundToInt(value)); return; } char buffer[SkStrAppendScalar_MaxSize]; char* end = SkStrAppendFixed(buffer, SkScalarToFixed(value)); stream->write(buffer, end - buffer); return; #endif // !SK_ALLOW_LARGE_PDF_SCALARS #if defined(SK_ALLOW_LARGE_PDF_SCALARS) // Floats have 24bits of significance, so anything outside that range is // no more precise than an int. (Plus PDF doesn't support scientific // notation, so this clamps to SK_Max/MinS32). if (value > (1 << 24) || value < -(1 << 24)) { stream->writeDecAsText(value); return; } // Continue to enforce the PDF limits for small floats. if (value < 1.0f/65536 && value > -1.0f/65536) { stream->writeDecAsText(0); return; } // SkStrAppendFloat might still use scientific notation, so use snprintf // directly.. static const int kFloat_MaxSize = 19; char buffer[kFloat_MaxSize]; int len = SNPRINTF(buffer, kFloat_MaxSize, "%#.8f", value); // %f always prints trailing 0s, so strip them. for (; buffer[len - 1] == '0' && len > 0; len--) { buffer[len - 1] = '\0'; } if (buffer[len - 1] == '.') { buffer[len - 1] = '\0'; } stream->writeText(buffer); return; #endif // SK_ALLOW_LARGE_PDF_SCALARS } //////////////////////////////////////////////////////////////////////////////// SkPDFString::SkPDFString(const char value[]) : fValue(FormatString(value, strlen(value))) { } SkPDFString::SkPDFString(const SkString& value) : fValue(FormatString(value.c_str(), value.size())) { } SkPDFString::SkPDFString(const uint16_t* value, size_t len, bool wideChars) : fValue(FormatString(value, len, wideChars)) { } SkPDFString::~SkPDFString() {} void SkPDFString::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { stream->write(fValue.c_str(), fValue.size()); } // static SkString SkPDFString::FormatString(const char* input, size_t len) { return DoFormatString(input, len, false, false); } SkString SkPDFString::FormatString(const uint16_t* input, size_t len, bool wideChars) { return DoFormatString(input, len, true, wideChars); } // static SkString SkPDFString::DoFormatString(const void* input, size_t len, bool wideInput, bool wideOutput) { SkASSERT(len <= kMaxLen); const uint16_t* win = (const uint16_t*) input; const char* cin = (const char*) input; if (wideOutput) { SkASSERT(wideInput); SkString result; result.append("<"); for (size_t i = 0; i < len; i++) { result.appendHex(win[i], 4); } result.append(">"); return result; } // 7-bit clean is a heuristic to decide what string format to use; // a 7-bit clean string should require little escaping. bool sevenBitClean = true; for (size_t i = 0; i < len; i++) { SkASSERT(!wideInput || !(win[i] & ~0xFF)); char val = wideInput ? win[i] : cin[i]; if (val > '~' || val < ' ') { sevenBitClean = false; break; } } SkString result; if (sevenBitClean) { result.append("("); for (size_t i = 0; i < len; i++) { SkASSERT(!wideInput || !(win[i] & ~0xFF)); char val = wideInput ? win[i] : cin[i]; if (val == '\\' || val == '(' || val == ')') { result.append("\\"); } result.append(&val, 1); } result.append(")"); } else { result.append("<"); for (size_t i = 0; i < len; i++) { SkASSERT(!wideInput || !(win[i] & ~0xFF)); unsigned char val = wideInput ? win[i] : cin[i]; result.appendHex(val, 2); } result.append(">"); } return result; } //////////////////////////////////////////////////////////////////////////////// SkPDFName::SkPDFName(const char name[]) : fValue(FormatName(SkString(name))) {} SkPDFName::SkPDFName(const SkString& name) : fValue(FormatName(name)) {} SkPDFName::~SkPDFName() {} bool SkPDFName::operator==(const SkPDFName& b) const { return fValue == b.fValue; } void SkPDFName::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { stream->write(fValue.c_str(), fValue.size()); } // static SkString SkPDFName::FormatName(const SkString& input) { SkASSERT(input.size() <= kMaxLen); // TODO(vandebo) If more escaping is needed, improve the linear scan. static const char escaped[] = "#/%()<>[]{}"; SkString result("/"); for (size_t i = 0; i < input.size(); i++) { if (input[i] & 0x80 || input[i] < '!' || strchr(escaped, input[i])) { result.append("#"); // Mask with 0xFF to avoid sign extension. i.e. #FFFFFF81 result.appendHex(input[i] & 0xFF, 2); } else { result.append(input.c_str() + i, 1); } } return result; } //////////////////////////////////////////////////////////////////////////////// SkPDFArray::SkPDFArray() {} SkPDFArray::~SkPDFArray() { fValue.unrefAll(); } void SkPDFArray::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { stream->writeText("["); for (int i = 0; i < fValue.count(); i++) { catalog->getSubstituteObject(fValue[i])->emitObject(stream, catalog); if (i + 1 < fValue.count()) { stream->writeText(" "); } } stream->writeText("]"); } void SkPDFArray::addResources(SkTSet<SkPDFObject*>* resourceSet, SkPDFCatalog* catalog) const { for (int i = 0; i < fValue.count(); i++) { catalog->getSubstituteObject(fValue[i]) ->addResources(resourceSet, catalog); } } void SkPDFArray::reserve(int length) { SkASSERT(length <= kMaxLen); fValue.setReserve(length); } SkPDFObject* SkPDFArray::setAt(int offset, SkPDFObject* value) { SkASSERT(offset < fValue.count()); value->ref(); fValue[offset]->unref(); fValue[offset] = value; return value; } SkPDFObject* SkPDFArray::append(SkPDFObject* value) { SkASSERT(fValue.count() < kMaxLen); value->ref(); fValue.push(value); return value; } void SkPDFArray::appendInt(int32_t value) { SkASSERT(fValue.count() < kMaxLen); fValue.push(new SkPDFInt(value)); } void SkPDFArray::appendScalar(SkScalar value) { SkASSERT(fValue.count() < kMaxLen); fValue.push(new SkPDFScalar(value)); } void SkPDFArray::appendName(const char name[]) { SkASSERT(fValue.count() < kMaxLen); fValue.push(new SkPDFName(name)); } /////////////////////////////////////////////////////////////////////////////// SkPDFDict::SkPDFDict() {} SkPDFDict::SkPDFDict(const char type[]) { insertName("Type", type); } SkPDFDict::~SkPDFDict() { clear(); } int SkPDFDict::size() const { SkAutoMutexAcquire lock(fMutex); return fValue.count(); } void SkPDFDict::emitObject(SkWStream* stream, SkPDFCatalog* catalog) { SkAutoMutexAcquire lock(fMutex); // If another thread triggers a // resize while this thread is in // the for-loop, we can be left // with a bad fValue[i] reference. stream->writeText("<<"); for (int i = 0; i < fValue.count(); i++) { SkASSERT(fValue[i].key); SkASSERT(fValue[i].value); fValue[i].key->emitObject(stream, catalog); stream->writeText(" "); catalog->getSubstituteObject(fValue[i].value) ->emitObject(stream, catalog); stream->writeText("\n"); } stream->writeText(">>"); } void SkPDFDict::addResources(SkTSet<SkPDFObject*>* resourceSet, SkPDFCatalog* catalog) const { for (int i = 0; i < fValue.count(); i++) { SkASSERT(fValue[i].key); SkASSERT(fValue[i].value); fValue[i].key->addResources(resourceSet, catalog); catalog->getSubstituteObject(fValue[i].value) ->addResources(resourceSet, catalog); } } SkPDFObject* SkPDFDict::append(SkPDFName* key, SkPDFObject* value) { SkASSERT(key); SkASSERT(value); SkAutoMutexAcquire lock(fMutex); // If the SkTDArray resizes while // two threads access array, one // is left with a bad pointer. *(fValue.append()) = Rec(key, value); return value; } SkPDFObject* SkPDFDict::insert(SkPDFName* key, SkPDFObject* value) { return this->append(SkRef(key), SkRef(value)); } SkPDFObject* SkPDFDict::insert(const char key[], SkPDFObject* value) { return this->append(new SkPDFName(key), SkRef(value)); } void SkPDFDict::insertInt(const char key[], int32_t value) { (void)this->append(new SkPDFName(key), new SkPDFInt(value)); } void SkPDFDict::insertScalar(const char key[], SkScalar value) { (void)this->append(new SkPDFName(key), new SkPDFScalar(value)); } void SkPDFDict::insertName(const char key[], const char name[]) { (void)this->append(new SkPDFName(key), new SkPDFName(name)); } void SkPDFDict::clear() { SkAutoMutexAcquire lock(fMutex); for (int i = 0; i < fValue.count(); i++) { SkASSERT(fValue[i].key); SkASSERT(fValue[i].value); fValue[i].key->unref(); fValue[i].value->unref(); } fValue.reset(); } void SkPDFDict::remove(const char key[]) { SkASSERT(key); SkPDFName name(key); SkAutoMutexAcquire lock(fMutex); for (int i = 0; i < fValue.count(); i++) { SkASSERT(fValue[i].key); if (*(fValue[i].key) == name) { fValue[i].key->unref(); SkASSERT(fValue[i].value); fValue[i].value->unref(); fValue.removeShuffle(i); return; } } } void SkPDFDict::mergeFrom(const SkPDFDict& other) { SkAutoMutexAcquire lockOther(other.fMutex); SkTDArray<Rec> copy(other.fValue); lockOther.release(); // Do not hold both mutexes at once. SkAutoMutexAcquire lock(fMutex); for (int i = 0; i < copy.count(); i++) { *(fValue.append()) = Rec(SkRef(copy[i].key), SkRef(copy[i].value)); } }
c++
code
12,568
2,994
//===- Relocations.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains platform-independent functions to process relocations. // I'll describe the overview of this file here. // // Simple relocations are easy to handle for the linker. For example, // for R_X86_64_PC64 relocs, the linker just has to fix up locations // with the relative offsets to the target symbols. It would just be // reading records from relocation sections and applying them to output. // // But not all relocations are that easy to handle. For example, for // R_386_GOTOFF relocs, the linker has to create new GOT entries for // symbols if they don't exist, and fix up locations with GOT entry // offsets from the beginning of GOT section. So there is more than // fixing addresses in relocation processing. // // ELF defines a large number of complex relocations. // // The functions in this file analyze relocations and do whatever needs // to be done. It includes, but not limited to, the following. // // - create GOT/PLT entries // - create new relocations in .dynsym to let the dynamic linker resolve // them at runtime (since ELF supports dynamic linking, not all // relocations can be resolved at link-time) // - create COPY relocs and reserve space in .bss // - replace expensive relocs (in terms of runtime cost) with cheap ones // - error out infeasible combinations such as PIC and non-relative relocs // // Note that the functions in this file don't actually apply relocations // because it doesn't know about the output file nor the output file buffer. // It instead stores Relocation objects to InputSection's Relocations // vector to let it apply later in InputSection::writeTo. // //===----------------------------------------------------------------------===// #include "Relocations.h" #include "Config.h" #include "LinkerScript.h" #include "OutputSections.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Target.h" #include "Thunks.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Memory.h" #include "lld/Common/Strings.h" #include "llvm/ADT/SmallSet.h" #include "llvm/Demangle/Demangle.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support::endian; namespace lld { namespace elf { static Optional<std::string> getLinkerScriptLocation(const Symbol &sym) { for (BaseCommand *base : script->sectionCommands) if (auto *cmd = dyn_cast<SymbolAssignment>(base)) if (cmd->sym == &sym) return cmd->location; return None; } // Construct a message in the following format. // // >>> defined in /home/alice/src/foo.o // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12) // >>> /home/alice/src/bar.o:(.text+0x1) static std::string getLocation(InputSectionBase &s, const Symbol &sym, uint64_t off) { std::string msg = "\n>>> defined in "; if (sym.file) msg += toString(sym.file); else if (Optional<std::string> loc = getLinkerScriptLocation(sym)) msg += *loc; msg += "\n>>> referenced by "; std::string src = s.getSrcMsg(sym, off); if (!src.empty()) msg += src + "\n>>> "; return msg + s.getObjMsg(off); } namespace { // Build a bitmask with one bit set for each RelExpr. // // Constexpr function arguments can't be used in static asserts, so we // use template arguments to build the mask. // But function template partial specializations don't exist (needed // for base case of the recursion), so we need a dummy struct. template <RelExpr... Exprs> struct RelExprMaskBuilder { static inline uint64_t build() { return 0; } }; // Specialization for recursive case. template <RelExpr Head, RelExpr... Tail> struct RelExprMaskBuilder<Head, Tail...> { static inline uint64_t build() { static_assert(0 <= Head && Head < 64, "RelExpr is too large for 64-bit mask!"); return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build(); } }; } // namespace // Return true if `Expr` is one of `Exprs`. // There are fewer than 64 RelExpr's, so we can represent any set of // RelExpr's as a constant bit mask and test for membership with a // couple cheap bitwise operations. template <RelExpr... Exprs> bool oneof(RelExpr expr) { assert(0 <= expr && (int)expr < 64 && "RelExpr is too large for 64-bit mask!"); return (uint64_t(1) << expr) & RelExprMaskBuilder<Exprs...>::build(); } // This function is similar to the `handleTlsRelocation`. MIPS does not // support any relaxations for TLS relocations so by factoring out MIPS // handling in to the separate function we can simplify the code and do not // pollute other `handleTlsRelocation` by MIPS `ifs` statements. // Mips has a custom MipsGotSection that handles the writing of GOT entries // without dynamic relocations. static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym, InputSectionBase &c, uint64_t offset, int64_t addend, RelExpr expr) { if (expr == R_MIPS_TLSLD) { in.mipsGot->addTlsIndex(*c.file); c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } if (expr == R_MIPS_TLSGD) { in.mipsGot->addDynTlsEntry(*c.file, sym); c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } return 0; } // Notes about General Dynamic and Local Dynamic TLS models below. They may // require the generation of a pair of GOT entries that have associated dynamic // relocations. The pair of GOT entries created are of the form GOT[e0] Module // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of // symbol in TLS block. // // Returns the number of relocations processed. template <class ELFT> static unsigned handleTlsRelocation(RelType type, Symbol &sym, InputSectionBase &c, typename ELFT::uint offset, int64_t addend, RelExpr expr) { if (!sym.isTls()) return 0; if (config->emachine == EM_MIPS) return handleMipsTlsRelocation(type, sym, c, offset, addend, expr); if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC>( expr) && config->shared) { if (in.got->addDynTlsEntry(sym)) { uint64_t off = in.got->getGlobalDynOffset(sym); mainPart->relaDyn->addReloc( {target->tlsDescRel, in.got, off, !sym.isPreemptible, &sym, 0}); } if (expr != R_TLSDESC_CALL) c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } bool canRelax = config->emachine != EM_ARM && config->emachine != EM_HEXAGON && config->emachine != EM_RISCV; // If we are producing an executable and the symbol is non-preemptable, it // must be defined and the code sequence can be relaxed to use Local-Exec. // // ARM and RISC-V do not support any relaxations for TLS relocations, however, // we can omit the DTPMOD dynamic relocations and resolve them at link time // because them are always 1. This may be necessary for static linking as // DTPMOD may not be expected at load time. bool isLocalInExecutable = !sym.isPreemptible && !config->shared; // Local Dynamic is for access to module local TLS variables, while still // being suitable for being dynamically loaded via dlopen. GOT[e0] is the // module index, with a special value of 0 for the current module. GOT[e1] is // unused. There only needs to be one module index entry. if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>( expr)) { // Local-Dynamic relocs can be relaxed to Local-Exec. if (canRelax && !config->shared) { c.relocations.push_back( {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type, offset, addend, &sym}); return target->getTlsGdRelaxSkip(type); } if (expr == R_TLSLD_HINT) return 1; if (in.got->addTlsIndex()) { if (isLocalInExecutable) in.got->relocations.push_back( {R_ADDEND, target->symbolicRel, in.got->getTlsIndexOff(), 1, &sym}); else mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got, in.got->getTlsIndexOff(), nullptr); } c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } // Local-Dynamic relocs can be relaxed to Local-Exec. if (expr == R_DTPREL && !config->shared) { c.relocations.push_back( {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type, offset, addend, &sym}); return 1; } // Local-Dynamic sequence where offset of tls variable relative to dynamic // thread pointer is stored in the got. This cannot be relaxed to Local-Exec. if (expr == R_TLSLD_GOT_OFF) { if (!sym.isInGot()) { in.got->addEntry(sym); uint64_t off = sym.getGotOffset(); in.got->relocations.push_back( {R_ABS, target->tlsOffsetRel, off, 0, &sym}); } c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) { if (!canRelax || config->shared) { if (in.got->addDynTlsEntry(sym)) { uint64_t off = in.got->getGlobalDynOffset(sym); if (isLocalInExecutable) // Write one to the GOT slot. in.got->relocations.push_back( {R_ADDEND, target->symbolicRel, off, 1, &sym}); else mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got, off, &sym); // If the symbol is preemptible we need the dynamic linker to write // the offset too. uint64_t offsetOff = off + config->wordsize; if (sym.isPreemptible) mainPart->relaDyn->addReloc(target->tlsOffsetRel, in.got, offsetOff, &sym); else in.got->relocations.push_back( {R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym}); } c.relocations.push_back({expr, type, offset, addend, &sym}); return 1; } // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec // depending on the symbol being locally defined or not. if (sym.isPreemptible) { c.relocations.push_back( {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_IE), type, offset, addend, &sym}); if (!sym.isInGot()) { in.got->addEntry(sym); mainPart->relaDyn->addReloc(target->tlsGotRel, in.got, sym.getGotOffset(), &sym); } } else { c.relocations.push_back( {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_LE), type, offset, addend, &sym}); } return target->getTlsGdRelaxSkip(type); } // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally // defined. if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF, R_TLSIE_HINT>(expr) && canRelax && isLocalInExecutable) { c.relocations.push_back({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym}); return 1; } if (expr == R_TLSIE_HINT) return 1; return 0; } static RelType getMipsPairType(RelType type, bool isLocal) { switch (type) { case R_MIPS_HI16: return R_MIPS_LO16; case R_MIPS_GOT16: // In case of global symbol, the R_MIPS_GOT16 relocation does not // have a pair. Each global symbol has a unique entry in the GOT // and a corresponding instruction with help of the R_MIPS_GOT16 // relocation loads an address of the symbol. In case of local // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold // the high 16 bits of the symbol's value. A paired R_MIPS_LO16 // relocations handle low 16 bits of the address. That allows // to allocate only one GOT entry for every 64 KBytes of local data. return isLocal ? R_MIPS_LO16 : R_MIPS_NONE; case R_MICROMIPS_GOT16: return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE; case R_MIPS_PCHI16: return R_MIPS_PCLO16; case R_MICROMIPS_HI16: return R_MICROMIPS_LO16; default: return R_MIPS_NONE; } } // True if non-preemptable symbol always has the same value regardless of where // the DSO is loaded. static bool isAbsolute(const Symbol &sym) { if (sym.isUndefWeak()) return true; if (const auto *dr = dyn_cast<Defined>(&sym)) return dr->section == nullptr; // Absolute symbol. return false; } static bool isAbsoluteValue(const Symbol &sym) { return isAbsolute(sym) || sym.isTls(); } // Returns true if Expr refers a PLT entry. static bool needsPlt(RelExpr expr) { return oneof<R_PLT_PC, R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PLT>(expr); } // Returns true if Expr refers a GOT entry. Note that this function // returns false for TLS variables even though they need GOT, because // TLS variables uses GOT differently than the regular variables. static bool needsGot(RelExpr expr) { return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT>( expr); } // True if this expression is of the form Sym - X, where X is a position in the // file (PC, or GOT for example). static bool isRelExpr(RelExpr expr) { return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL, R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC, R_RISCV_PC_INDIRECT>(expr); } // Returns true if a given relocation can be computed at link-time. // // For instance, we know the offset from a relocation to its target at // link-time if the relocation is PC-relative and refers a // non-interposable function in the same executable. This function // will return true for such relocation. // // If this function returns false, that means we need to emit a // dynamic relocation so that the relocation will be fixed at load-time. static bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym, InputSectionBase &s, uint64_t relOff) { // These expressions always compute a constant if (oneof<R_DTPREL, R_GOTPLT, R_GOT_OFF, R_TLSLD_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, R_MIPS_TLSGD, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC, R_PLT_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC, R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PPC64_RELAX_TOC, R_RISCV_ADD, R_TLSDESC_CALL, R_TLSDESC_PC, R_AARCH64_TLSDESC_PAGE, R_TLSLD_HINT, R_TLSIE_HINT>( e)) return true; // These never do, except if the entire file is position dependent or if // only the low bits are used. if (e == R_GOT || e == R_PLT || e == R_TLSDESC) return target->usesOnlyLowPageBits(type) || !config->isPic; if (sym.isPreemptible) return false; if (!config->isPic) return true; // The size of a non preemptible symbol is a constant. if (e == R_SIZE) return true; // For the target and the relocation, we want to know if they are // absolute or relative. bool absVal = isAbsoluteValue(sym); bool relE = isRelExpr(e); if (absVal && !relE) return true; if (!absVal && relE) return true; if (!absVal && !relE) return target->usesOnlyLowPageBits(type); assert(absVal && relE); // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol // in PIC mode. This is a little strange, but it allows us to link function // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers). // Normally such a call will be guarded with a comparison, which will load a // zero from the GOT. if (sym.isUndefWeak()) return true; // We set the final symbols values for linker script defined symbols later. // They always can be computed as a link time constant. if (sym.scriptDefined) return true; error("relocation " + toString(type) + " cannot refer to absolute symbol: " + toString(sym) + getLocation(s, sym, relOff)); return true; } static RelExpr toPlt(RelExpr expr) { switch (expr) { case R_PPC64_CALL: return R_PPC64_CALL_PLT; case R_PC: return R_PLT_PC; case R_ABS: return R_PLT; default: return expr; } } static RelExpr fromPlt(RelExpr expr) { // We decided not to use a plt. Optimize a reference to the plt to a // reference to the symbol itself. switch (expr) { case R_PLT_PC: case R_PPC32_PLTREL: return R_PC; case R_PPC64_CALL_PLT: return R_PPC64_CALL; case R_PLT: return R_ABS; default: return expr; } } // Returns true if a given shared symbol is in a read-only segment in a DSO. template <class ELFT> static bool isReadOnly(SharedSymbol &ss) { using Elf_Phdr = typename ELFT::Phdr; // Determine if the symbol is read-only by scanning the DSO's program headers. const SharedFile &file = ss.getFile(); for (const Elf_Phdr &phdr : check(file.template getObj<ELFT>().program_headers())) if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) && !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr && ss.value < phdr.p_vaddr + phdr.p_memsz) return true; return false; } // Returns symbols at the same offset as a given symbol, including SS itself. // // If two or more symbols are at the same offset, and at least one of // them are copied by a copy relocation, all of them need to be copied. // Otherwise, they would refer to different places at runtime. template <class ELFT> static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) { using Elf_Sym = typename ELFT::Sym; SharedFile &file = ss.getFile(); SmallSet<SharedSymbol *, 4> ret; for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) { if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS || s.getType() == STT_TLS || s.st_value != ss.value) continue; StringRef name = check(s.getName(file.getStringTable())); Symbol *sym = symtab->find(name); if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym)) ret.insert(alias); } return ret; } // When a symbol is copy relocated or we create a canonical plt entry, it is // effectively a defined symbol. In the case of copy relocation the symbol is // in .bss and in the case of a canonical plt entry it is in .plt. This function // replaces the existing symbol with a Defined pointing to the appropriate // location. static void replaceWithDefined(Symbol &sym, SectionBase *sec, uint64_t value, uint64_t size) { Symbol old = sym; sym.replace(Defined{sym.file, sym.getName(), sym.binding, sym.stOther, sym.type, value, size, sec}); sym.pltIndex = old.pltIndex; sym.gotIndex = old.gotIndex; sym.verdefIndex = old.verdefIndex; sym.exportDynamic = true; sym.isUsedInRegularObj = true; } // Reserve space in .bss or .bss.rel.ro for copy relocation. // // The copy relocation is pretty much a hack. If you use a copy relocation // in your program, not only the symbol name but the symbol's size, RW/RO // bit and alignment become part of the ABI. In addition to that, if the // symbol has aliases, the aliases become part of the ABI. That's subtle, // but if you violate that implicit ABI, that can cause very counter- // intuitive consequences. // // So, what is the copy relocation? It's for linking non-position // independent code to DSOs. In an ideal world, all references to dat
c++
code
20,000
4,293
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // ospray #include "Camera.h" #include "camera/Camera_ispc.h" #include "common/Util.h" namespace ospray { static FactoryMap<Camera> g_cameraMap; Camera::Camera() { managedObjectType = OSP_CAMERA; } Camera::~Camera() { if (embreeGeometry) rtcReleaseGeometry(embreeGeometry); } Camera *Camera::createInstance(const char *type) { return createInstanceHelper(type, g_cameraMap[type]); } void Camera::registerType(const char *type, FactoryFcn<Camera> f) { g_cameraMap[type] = f; } std::string Camera::toString() const { return "ospray::Camera"; } box3f Camera::projectBox(const box3f &) const { return box3f(vec3f(0.f), vec3f(1.f)); } void Camera::commit() { motionTransform.readParams(*this); // "parse" the general expected parameters pos = getParam<vec3f>("position", vec3f(0.f)); dir = getParam<vec3f>("direction", vec3f(0.f, 0.f, 1.f)); up = getParam<vec3f>("up", vec3f(0.f, 1.f, 0.f)); nearClip = std::max(getParam<float>("nearClip", 1e-6f), 0.f); imageStart = getParam<vec2f>("imageStart", vec2f(0.f)); imageEnd = getParam<vec2f>("imageEnd", vec2f(1.f)); shutter = getParam<range1f>("shutter", range1f(0.5f, 0.5f)); clamp(shutter.lower); clamp(shutter.upper); if (shutter.lower > shutter.upper) shutter.lower = shutter.upper; shutterType = (OSPShutterType)getParam<uint8_t>("shutterType", OSP_SHUTTER_GLOBAL); rollingShutterDuration = clamp( getParam<float>("rollingShutterDuration", 0.0f), 0.0f, shutter.size()); if (motionTransform.motionBlur || motionTransform.quaternion) { // create dummy RTCGeometry for transform interpolation or conversion if (!embreeGeometry) embreeGeometry = rtcNewGeometry(embreeDevice, RTC_GEOMETRY_TYPE_INSTANCE); motionTransform.setEmbreeTransform(embreeGeometry); if (shutter.lower == shutter.upper || !motionTransform.motionBlur) { // directly interpolate to single shutter time rtcGetGeometryTransform(embreeGeometry, shutter.lower, RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR, &motionTransform.transform); motionTransform.motionBlur = false; } } if (!motionTransform.motionBlur) { if (embreeGeometry) { rtcReleaseGeometry(embreeGeometry); embreeGeometry = nullptr; } // apply transform right away pos = xfmPoint(motionTransform.transform, pos); dir = normalize(xfmVector(motionTransform.transform, dir)); up = normalize(xfmVector(motionTransform.transform, up)); } if (shutterType != OSP_SHUTTER_GLOBAL) { // rolling shutter shutter.upper -= rollingShutterDuration; if (shutterType == OSP_SHUTTER_ROLLING_LEFT || shutterType == OSP_SHUTTER_ROLLING_DOWN) std::swap(shutter.lower, shutter.upper); } ispc::Camera_set(getIE(), nearClip, (const ispc::vec2f &)imageStart, (const ispc::vec2f &)imageEnd, (const ispc::box1f &)shutter, shutterType == OSP_SHUTTER_GLOBAL, rollingShutterDuration, shutterType == OSP_SHUTTER_ROLLING_RIGHT || shutterType == OSP_SHUTTER_ROLLING_LEFT, motionTransform.motionBlur, embreeGeometry); } void Camera::setDevice(RTCDevice device) { embreeDevice = device; } OSPTYPEFOR_DEFINITION(Camera *); } // namespace ospray
c++
code
3,338
693
#include "trafficgraphwidget.h" #include "clientmodel.h" #include <QPainter> #include <QPainterPath> #include <QColor> #include <QTimer> #include <cmath> #define DESIRED_SAMPLES 600 #define XMARGIN 10 #define YMARGIN 10 TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) : QWidget(parent), timer(0), fMax(0.0f), nMinutes(0), vSamplesIn(), vSamplesOut(), nLastBytesRx(0), nLastBytesTx(0), clientModel(0) { timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(updateRates())); } void TrafficGraphWidget::setClientModel(ClientModel *model) { clientModel = model; if(model) { nLastBytesRx = model->getTotalBytesRx(); nLastBytesTx = model->getTotalBytesTx(); } } void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples) { int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2; int sampleCount = samples.size(), x = XMARGIN + w, y, i; if(sampleCount > 0) { path.moveTo(x, YMARGIN + h); for(i = 0; i < sampleCount; ++i) { x = XMARGIN + w - w * i / DESIRED_SAMPLES; y = YMARGIN + h - (int)(h * samples.at(i) / fMax); path.lineTo(x, y); } path.lineTo(x, YMARGIN + h); } } void TrafficGraphWidget::paintEvent(QPaintEvent *) { int i, h, yy, base; float y, val; QPainter painter(this); painter.fillRect(rect(), Qt::black); if(fMax <= 0.0f) return; QColor axisCol(Qt::gray); h = height() - YMARGIN * 2; painter.setPen(axisCol); painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h); /* Order of magnitude */ base = floor(log10(fMax)); val = pow(10.0f, base); const QString units = tr("Kb/s"); /* Draw lines */ painter.setPen(axisCol); painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units)); for(y = val; y < fMax; y += val) { yy = YMARGIN + h - h * y / fMax; painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy); } /* If 3 or less lines drawn, break them up at the next lower order of magnitude */ if(fMax / val <= 3.0f) { axisCol = axisCol.darker(); val = pow(10.0f, base - 1); painter.setPen(axisCol); painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units)); for(y = val, i = 1; y < fMax; y += val, i++) { /* Don't overwrite lines drawn above */ if(!(i % 10)) continue; yy = YMARGIN + h - h * y / fMax; painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy); } } if(!vSamplesIn.empty()) { QPainterPath p; paintPath(p, vSamplesIn); painter.fillPath(p, QColor(0, 255, 0, 128)); painter.setPen(Qt::green); painter.drawPath(p); } if(!vSamplesOut.empty()) { QPainterPath p; paintPath(p, vSamplesOut); painter.fillPath(p, QColor(255, 0, 0, 128)); painter.setPen(Qt::red); painter.drawPath(p); } } void TrafficGraphWidget::updateRates() { if(!clientModel) return; quint64 bytesRx = clientModel->getTotalBytesRx(); quint64 bytesTx = clientModel->getTotalBytesTx(); float rateRx = (bytesRx - nLastBytesRx) / 1024.0f * 1000 / timer->interval(); float rateTx = (bytesTx - nLastBytesTx) / 1024.0f * 1000 / timer->interval(); vSamplesIn.push_front(rateRx); vSamplesOut.push_front(rateTx); nLastBytesRx = bytesRx; nLastBytesTx = bytesTx; while(vSamplesIn.size() > DESIRED_SAMPLES) vSamplesIn.pop_back(); while(vSamplesOut.size() > DESIRED_SAMPLES) vSamplesOut.pop_back(); float tmax = 0.0f; foreach(float f, vSamplesIn) { if(f > tmax) tmax = f; } foreach(float f, vSamplesOut) { if(f > tmax) tmax = f; } fMax = tmax; update(); } void TrafficGraphWidget::setGraphRange(int nMinutes) { timer->stop(); timer->setInterval(nMinutes * 60 * 1000 / DESIRED_SAMPLES); clear(); } void TrafficGraphWidget::clear() { timer->stop(); vSamplesOut.clear(); vSamplesIn.clear(); fMax = 0.0f; if(clientModel) { nLastBytesRx = clientModel->getTotalBytesRx(); nLastBytesTx = clientModel->getTotalBytesTx(); } timer->start(); }
c++
code
4,345
1,112
/* * Copyright (c) 2018, 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. */ #include "gtest/gtest.h" #include "LoRaPHY.h" #include "LoRaWANTimer_stub.h" class my_LoRaPHY : public LoRaPHY { public: my_LoRaPHY() { phy_params.adr_ack_delay = 1; } virtual ~my_LoRaPHY() { } loraphy_params_t &get_phy_params() { return phy_params; } }; class my_radio : public LoRaRadio { public: virtual void init_radio(radio_events_t *events) { }; virtual void radio_reset() { }; virtual void sleep(void) { }; virtual void standby(void) { }; virtual void set_rx_config(radio_modems_t modem, uint32_t bandwidth, uint32_t datarate, uint8_t coderate, uint32_t bandwidth_afc, uint16_t preamble_len, uint16_t symb_timeout, bool fix_len, uint8_t payload_len, bool crc_on, bool freq_hop_on, uint8_t hop_period, bool iq_inverted, bool rx_continuous) { }; virtual void set_tx_config(radio_modems_t modem, int8_t power, uint32_t fdev, uint32_t bandwidth, uint32_t datarate, uint8_t coderate, uint16_t preamble_len, bool fix_len, bool crc_on, bool freq_hop_on, uint8_t hop_period, bool iq_inverted, uint32_t timeout) { }; virtual void send(uint8_t *buffer, uint8_t size) { }; virtual void receive(void) { }; virtual void set_channel(uint32_t freq) { }; virtual uint32_t random(void) { }; virtual uint8_t get_status(void) { return uint8_value; }; virtual void set_max_payload_length(radio_modems_t modem, uint8_t max) { }; virtual void set_public_network(bool enable) { }; virtual uint32_t time_on_air(radio_modems_t modem, uint8_t pkt_len) { }; virtual bool perform_carrier_sense(radio_modems_t modem, uint32_t freq, int16_t rssi_threshold, uint32_t max_carrier_sense_time) { return bool_value; }; virtual void start_cad(void) { }; virtual bool check_rf_frequency(uint32_t frequency) { return bool_value; }; virtual void lock(void) { }; virtual void unlock(void) { }; bool bool_value; uint8_t uint8_value; }; class Test_LoRaPHY : public testing::Test { protected: my_LoRaPHY *object; virtual void SetUp() { object = new my_LoRaPHY(); memset(&object->get_phy_params(), 0, sizeof(object->get_phy_params())); } virtual void TearDown() { delete object; } }; TEST_F(Test_LoRaPHY, initialize) { object->initialize(NULL); } TEST_F(Test_LoRaPHY, set_radio_instance) { my_radio radio; object->set_radio_instance(radio); } TEST_F(Test_LoRaPHY, put_radio_to_sleep) { my_radio radio; object->set_radio_instance(radio); object->put_radio_to_sleep(); } TEST_F(Test_LoRaPHY, put_radio_to_standby) { my_radio radio; object->set_radio_instance(radio); object->put_radio_to_standby(); } TEST_F(Test_LoRaPHY, handle_receive) { my_radio radio; object->set_radio_instance(radio); object->handle_receive(); } TEST_F(Test_LoRaPHY, handle_send) { my_radio radio; object->set_radio_instance(radio); object->handle_send(NULL, 0); } TEST_F(Test_LoRaPHY, setup_public_network_mode) { my_radio radio; channel_params_t p; object->get_phy_params().channels.channel_list = &p; object->set_radio_instance(radio); object->setup_public_network_mode(false); } TEST_F(Test_LoRaPHY, get_radio_rng) { my_radio radio; object->set_radio_instance(radio); EXPECT_TRUE(0 != object->get_radio_rng()); } TEST_F(Test_LoRaPHY, calculate_backoff) { channel_params_t p[1]; p[0].band = 0; p[0].dr_range.fields.min = DR_0; p[0].dr_range.fields.max = DR_5; object->get_phy_params().channels.channel_list = p; band_t b[1]; b[0].duty_cycle = 0; b[0].higher_band_freq = 8689000; b[0].lower_band_freq = 8687000; b[0].max_tx_pwr = 20; b[0].last_join_tx_time = 0; b[0].last_tx_time = 0; b[0].off_time = 0; object->get_phy_params().bands.table = b; object->calculate_backoff(false, false, false, 0, 10, 12); object->calculate_backoff(false, true, false, 0, 3600000 + 10, 12); object->calculate_backoff(false, false, true, 0, 3600000 + 36000000 + 10, 12); } TEST_F(Test_LoRaPHY, mask_bit_test) { uint16_t buf; buf = 0x08; EXPECT_TRUE(!object->mask_bit_test(&buf, 0)); } TEST_F(Test_LoRaPHY, mask_bit_set) { uint16_t buf; object->mask_bit_set(&buf, 3); } TEST_F(Test_LoRaPHY, mask_bit_clear) { uint16_t buf; object->mask_bit_clear(&buf, 0); } TEST_F(Test_LoRaPHY, request_new_channel) { band_t b; object->get_phy_params().bands.size = 1; b.higher_band_freq = 8689000; b.lower_band_freq = 8678000; b.duty_cycle = 0; b.last_join_tx_time = 0; b.last_tx_time = 0; b.max_tx_pwr = 20; b.off_time = 0; object->get_phy_params().bands.table = &b; channel_params_t p; //First 3 channels are set to be default p.band = 0; p.dr_range.fields.min = DR_0; p.dr_range.fields.max = DR_5; p.frequency = 8687000; p.rx1_frequency = 0; uint16_t dflt_msk = 0x07; object->get_phy_params().channels.default_mask = &dflt_msk; object->get_phy_params().channels.channel_list = &p; object->get_phy_params().custom_channelplans_supported = true; //Default channel, PARAMETER invalid EXPECT_TRUE(0 == object->request_new_channel(0, &p)); //Freq & DR invalid p.frequency = 12345; p.dr_range.fields.max = 12; object->get_phy_params().max_channel_cnt = 16; object->get_phy_params().min_tx_datarate = DR_0; object->get_phy_params().max_tx_datarate = DR_5; // Frequency and DR are invalid - LORAWAN_STATUS_FREQ_AND_DR_INVALID EXPECT_TRUE(0 == object->request_new_channel(0, &p)); //Freq invalid p.frequency = 12345; p.dr_range.fields.max = DR_5; object->get_phy_params().default_channel_cnt = 3; EXPECT_TRUE(2 == object->request_new_channel(0, &p)); //DR invalid p.frequency = 8687000; p.dr_range.fields.max = 12; p.dr_range.fields.min = 1; EXPECT_TRUE(1 == object->request_new_channel(0, &p)); //STATUS_OK p.dr_range.fields.max = DR_5; p.dr_range.fields.min = DR_0; uint16_t ch_msk = 0x08; object->get_phy_params().channels.mask = &ch_msk; EXPECT_TRUE(3 == object->request_new_channel(0, &p)); } TEST_F(Test_LoRaPHY, set_last_tx_done) { channel_params_t p[1]; p[0].band = 0; object->get_phy_params().channels.channel_list = p; band_t b[1]; object->get_phy_params().bands.table = b; object->set_last_tx_done(0, false, 0); object->set_last_tx_done(0, true, 0); } TEST_F(Test_LoRaPHY, restore_default_channels) { channel_params_t p[1]; p[0].band = 0; object->get_phy_params().channels.channel_list = p; uint16_t m, dm; object->get_phy_params().channels.mask_size = 1; object->get_phy_params().channels.default_mask = &dm; object->get_phy_params().channels.mask = &m; object->restore_default_channels(); } TEST_F(Test_LoRaPHY, apply_cf_list) { uint8_t list[16]; memset(list, 0, 16); object->apply_cf_list(list, 0); object->get_phy_params().cflist_supported = true; object->apply_cf_list(list, 0); object->get_phy_params().default_channel_cnt = 1; object->get_phy_params().cflist_channel_cnt = 0; object->get_phy_params().max_channel_cnt = 3; uint16_t def_mask = 0x01; channel_params_t p[16]; memset(p, 0, 16); //one default channel p[0].band = 0; p[0].dr_range.fields.min = DR_0; p[0].dr_range.fields.min = DR_5; p[0].frequency = 8687000; object->get_phy_params().channels.default_mask = &def_mask; object->get_phy_params().channels.mask = &def_mask; object->get_phy_params().channels.channel_list = p; object->apply_cf_list(list, 16); list[1] = 15; object->get_phy_params().cflist_channel_cnt = 1; object->apply_cf_list(list, 16); } TEST_F(Test_LoRaPHY, get_next_ADR) { int8_t i = 0; int8_t j = 0; uint32_t ctr = 0; object->get_phy_params().min_tx_datarate = 0; EXPECT_TRUE(!object->get_next_ADR(false, i, j, ctr)); i = 1; object->get_phy_params().adr_ack_limit = 3; EXPECT_TRUE(!object->get_next_ADR(false, i, j, ctr)); object->get_phy_params().adr_ack_limit = 3; ctr = 4; object->get_phy_params().max_tx_power = 2; object->get_phy_params().adr_ack_delay = 1; EXPECT_TRUE(object->get_next_ADR(true, i, j, ctr)); ctr = 5; object->get_phy_params().adr_ack_delay = 2; EXPECT_TRUE(!object->get_next_ADR(true, i, j, ctr)); } TEST_F(Test_LoRaPHY, rx_config) { my_radio radio; radio.uint8_value = RF_IDLE; radio.bool_value = true; object->set_radio_instance(radio); uint8_t list; object->get_phy_params().datarates.table = &list; uint8_t list2; object->get_phy_params().payloads_with_repeater.table = &list2; rx_config_params_t p; memset(&p, 0, sizeof(rx_config_params_t)); p.datarate = 0; p.rx_slot = RX_SLOT_WIN_1; channel_params_t pp[1]; object->get_phy_params().channels.channel_list = pp; pp[0].rx1_frequency = 2; p.channel = 0; uint8_t tab[8]; object->get_phy_params().payloads.table = tab; object->get_phy_params().payloads_with_repeater.table = tab; EXPECT_TRUE(object->rx_config(&p)); p.datarate = DR_7; p.is_repeater_supported = true; object->get_phy_params().fsk_supported = true; EXPECT_TRUE(object->rx_config(&p)); } TEST_F(Test_LoRaPHY, compute_rx_win_params) { uint32_t list[1]; list[0] = 125000; object->get_phy_params().bandwidths.table = list; uint8_t list2[1]; list2[0] = 12; object->get_phy_params().datarates.table = &list2; channel_params_t ch_lst[16]; memset(ch_lst, 0, sizeof(channel_params_t) * 16); ch_lst[0].band = 0; ch_lst[0].dr_range.fields.min = DR_0; ch_lst[0].dr_range.fields.max = DR_5; ch_lst[0].frequency = 8687000; object->get_phy_params().channels.channel_list = ch_lst; object->get_phy_params().channels.channel_list_size = 16; rx_config_params_t p; memset(&p, 0, sizeof(rx_config_params_t)); p.frequency = 8687000; object->compute_rx_win_params(0, 0, 0, &p); p.datarate = 0; list[0] = 125000; object->compute_rx_win_params(0, 0, 0, &p); list[0] = 250000; object->compute_rx_win_params(0, 0, 0, &p); list[0] = 500000; object->get_phy_params().fsk_supported = true; object->get_phy_params().max_rx_datarate = 0; object->compute_rx_win_params(0, 0, 0, &p); } TEST_F(Test_LoRaPHY, tx_config) { band_t b; memset(&b, 0, sizeof(band_t)); object->get_phy_params().bands.table = &b; channel_params_t pp; memset(&pp, 0, sizeof(channel_params_t)); pp.band = 0; object->get_phy_params().channels.channel_list = &pp; uint32_t list[1]; list[0] = 125000; object->get_phy_params().bandwidths.table = &list; uint8_t list2[1]; list2[0] = 12; object->get_phy_params().datarates.table = &list2; my_radio radio; object->set_radio_instance(radio); tx_config_params_t p; memset(&p, 0, sizeof(tx_config_params_t)); p.channel = 0; int8_t i = 20; lorawan_time_t t = 36; object->tx_config(&p, &i, &t); p.datarate = 8; object->get_phy_params().max_tx_datarate = 8; object->tx_config(&p, &i, &t); } TEST_F(Test_LoRaPHY, link_ADR_request) { adr_req_params_t p; memset(&p, 0, sizeof(adr_req_params_t)); uint8_t b[100]; memset(b, 0, 100); p.payload = b; b[0] = 0x03; b[1] = 1; b[2] = 0; b[3] = 0; b[4] = 1 << 4; b[5] = 0x03; b[6] = 1; b[7] = 1; b[8] = 1; b[9] = 6 << 4; b[10] = 0x03; b[11] = 1; b[12] = 0xff; b[13] = 0xff; b[14] = 0; b[15] = 0; p.payload_size = 16; int8_t i = 0, j = 0; uint8_t k = 0, l = 0; uint8_t t[5] = {12, 11, 10, 9, 8}; t[0] = 0; object->get_phy_params().datarates.size = 5; object->get_phy_params().datarates.table = t; //Test without ADR payload does not make sense here. object->get_phy_params().max_channel_cnt = 16; channel_params_t li[16]; memset(li, 0, sizeof(channel_params_t) * 16); object->get_phy_params().channels.channel_list = li; li[0].frequency = 0; li[1].frequency = 5; EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); t[0] = 3; //verify adr with p.adr_enabled = false EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); p.current_nb_trans = 0; EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); p.adr_enabled = true; li[0].dr_range.value = 0xff; object->get_phy_params().min_tx_datarate = DR_3; object->get_phy_params().max_tx_datarate = DR_8; //verify adr with status != 0 EXPECT_TRUE(0 == object->link_ADR_request(&p, &i, &j, &k, &l)); object->get_phy_params().max_tx_power = 2; object->get_phy_params().min_tx_power = 6; //verify adr with status != 0 EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); object->get_phy_params().min_tx_datarate = DR_0; li[0].dr_range.value = 0xf0; EXPECT_TRUE(6 == object->link_ADR_request(&p, &i, &j, &k, &l)); li[1].dr_range.fields.min = DR_0; li[1].dr_range.fields.max = DR_13; b[4] = 6 << 4; p.payload_size = 5; EXPECT_TRUE(7 == object->link_ADR_request(&p, &i, &j, &k, &l)); uint16_t mask[2]; object->get_phy_params().channels.mask = mask; object->get_phy_params().channels.mask_size = 2; EXPECT_TRUE(7 == object->link_ADR_request(&p, &i, &j, &k, &l)); li[0].dr_range.value = 0xff; object->get_phy_params().max_channel_cnt = 0; EXPECT_TRUE(5 == object->link_ADR_request(&p, &i, &j, &k, &l)); b[0] = 0x03; b[1] = 1; b[2] = 0; b[3] = 0; b[4] = 0; t[0] = 0; object->get_phy_params().datarates.size = 1; object->get_phy_params().datarates.table = t; //Test without ADR payload does not make sense here. object->get_phy_params().max_channel_cnt = 2; li[0].frequency = 0; li[1].frequency = 5; EXPECT_TRUE(4 == object->link_ADR_request(&p, &i, &j, &k, &l)); } TEST_F(Test_LoRaPHY, accept_rx_param_setup_req) { my_radio radio; radio.bool_value = true; object->set_radio_instance(radio); rx_param_setup_req_t req; req.datarate = DR_0; req.dr_offset = 0; req.frequency = 8678000; band_t band[1]; memset(band, 0, sizeof(band_t)); band[0].higher_band_freq = 8688000; band[0].lower_band_freq = 8666000; object->get_phy_params().bands.size = 1; object->get_phy_params().bands.table = band; EXPECT_TRUE(0x07 == object->accept_rx_param_setup_req(&req)); } TEST_F(Test_LoRaPHY, accept_tx_param_setup_req) { my_radio radio; object->set_radio_instance(radio); object->get_phy_params().accept_tx_param_setup_req = true; EXPECT_TRUE(object->accept_tx_param_setup_req(0, 0)); } TEST_F(Test_LoRaPHY, dl_channel_request) { EXPECT_TRUE(0 == object->dl_channel_request(0, 0)); object->get_phy_params().dl_channel_req_supported = true; object->get_phy_params().bands.size = 1; band_t t[1]; memset(t, 0, sizeof(band_t)); t[0].higher_band_freq = 8688000; t[0].lower_band_freq = 8668000; object->get_phy_params().bands.size = 1; object->get_phy_params().bands.table = t; channel_params_t p[16]; memset(p, 0, sizeof(channel_params_t) * 16); object->get_phy_params().channels.channel_list_size = 16; object->get_phy_params().channels.channel_list = p; p[0].frequency = 0; EXPECT_TRUE(0 == object->dl_channel_request(0, 1)); t[0].higher_band_freq = 19; t[0].lower_band_freq = 0; p[0].frequency = 1; EXPECT_TRUE(3 == object->dl_channel_request(0, 1)); } TEST_F(Test_LoRaPHY, get_alternate_DR) { EXPECT_TRUE(0 == object->get_alternate_DR(0)); object->get_phy_params().default_max_datarate = 5; object->get_phy_params().min_tx_datarate = 4; EXPECT_TRUE(5 == object->get_alternate_DR(1)); object->get_phy_params().default_max_datarate = 6; object->get_phy_params().min_tx_datarate = 4; EXPECT_TRUE(5 == object->get_alternate_DR(2)); } TEST_F(Test_LoRaPHY, set_next_channel) { channel_selection_params_t p; memset(&p, 0, sizeof(channel_selection_params_t)); band_t band[1]; memset(band, 0, sizeof(band_t)); band[0].higher_band_freq = 8687000; object->get_phy_params().bands.size = 1; object->get_phy_params().bands.table = band; uint8_t ch = 5; lorawan_time_t t1 = 16; lorawan_time_t t2 = 32; p.aggregate_timeoff = 10000; EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&p, &ch, &t1, &t2)); uint16_t list[129]; memset(list, 0, sizeof(list)); list[4] = 1; list[128] = 1; object->get_phy_params().channels.mask = list; object->get_phy_params().channels.default_mask = list; object->get_phy_params().channels.mask_size = 1; p.aggregate_timeoff = 10000; EXPECT_TRUE(LORAWAN_STATUS_DUTYCYCLE_RESTRICTED == object->set_next_channel(&p, &ch, &t1, &t2)); LoRaWANTimer_stub::time_value = 20000; EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); p.joined = false; p.dc_enabled = false; band_t b[4]; ch = 5; t1 = 16; t2 = 32; memset(b, 0, sizeof(band_t) * 4); object->get_phy_params().bands.size = 2; object->get_phy_params().bands.table = &b; b[0].off_time = 0; b[1].off_time = 9999999; memset(list, 0, 129); list[4] = 0; object->get_phy_params().channels.mask = list; object->get_phy_params().channels.default_mask = list; object->get_phy_params().channels.mask_size = 128; p.current_datarate = DR_1; object->get_phy_params().max_channel_cnt = 4; EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); p.dc_enabled = true; EXPECT_TRUE(LORAWAN_STATUS_NO_CHANNEL_FOUND == object->set_next_channel(&p, &ch, &t1, &t2)); list[4] = 1; p.joined = true; p.dc_enabled = false; channel_params_t l[4]; l[0].dr_range.value = 0xff; l[1].dr_range.value = 0xff; l[2].dr_range.value = 0xf0; l[3].dr_range.value = 0xf0; l[2].band = 2; l[3].band = 3; object->get_phy_params().channels.channel_list = l; list[0] = 0xFF; b[2].off_time = 9999999; b[3].off_time = 0; EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&p, &ch, &t1, &t2)); b[0].off_time = 10000; LoRaWANTimer_stub::time_value = 2000; p.aggregate_timeoff = 1000; p.dc_enabled = true; EXPECT_TRUE(LORAWAN_STATUS_OK == object->set_next_channel(&p, &ch, &t1, &t2)); } TEST_F(Test_LoRaPHY, add_channel) { uint16_t list[16]; object->get_phy_params().channels.mask =
c++
code
20,000
4,815
#pragma once #pragma clang diagnostic push #pragma ide diagnostic ignored "bugprone-sizeof-expression" #pragma ide diagnostic ignored "cert-err58-cpp" #pragma ide diagnostic ignored "readability-const-return-type" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/typedefs.h" #include "custom-types/shared/register.hpp" #include "custom-types/shared/macros.hpp" #include "HMUI/ViewController.hpp" #include "UnityEngine/UI/Toggle.hpp" #include "CustomTypes/Components/Settings/IncrementSetting.hpp" #include "modloader.hpp" #include "Config.hpp" DECLARE_CLASS_CODEGEN(ParticleTuner, PTModSettingsViewController, HMUI::ViewController, DECLARE_INSTANCE_FIELD_DEFAULT(QuestUI::IncrementSetting*, sparklesMultInc, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(QuestUI::IncrementSetting*, explosionsMultInc, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(QuestUI::IncrementSetting*, lifetimeMultInc, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(QuestUI::IncrementSetting*, particleOpacityInc, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(UnityEngine::UI::Toggle*, reduceCoreParticlesToggle, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(UnityEngine::UI::Toggle*, reduceClashParticlesToggle, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(UnityEngine::UI::Toggle*, reduceDustParticlesToggle, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(UnityEngine::UI::Toggle*, rainbowParticlesToggle, nullptr); // DECLARE_INSTANCE_FIELD(UnityEngine::UI::Toggle*, boostSaturationToggle); DECLARE_INSTANCE_FIELD_DEFAULT(Il2CppObject*, dustPSAgent, nullptr); DECLARE_OVERRIDE_METHOD(void, DidActivate, il2cpp_utils::FindMethodUnsafe("HMUI", "ViewController", "DidActivate", 3), bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling); DECLARE_OVERRIDE_METHOD(void, DidDeactivate, il2cpp_utils::FindMethodUnsafe("HMUI", "ViewController", "DidDeactivate", 2), bool removedFromHierarchy, bool screenSystemDisabling); DECLARE_INSTANCE_METHOD(void, UpdateUIComponents); ) DECLARE_CLASS_CODEGEN(ParticleTuner, PTPresetData, Il2CppObject, DECLARE_INSTANCE_FIELD_DEFAULT(PTModSettingsViewController*, parent, nullptr); DECLARE_INSTANCE_FIELD_DEFAULT(int, preset, 0); ) #pragma clang diagnostic pop
c++
code
2,304
342
// Copyright (c) 2017, Baidu.com, Inc. 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 "exec/plain_text_line_reader.h" #include <gtest/gtest.h> #include "exec/local_file_reader.h" #include "exec/decompressor.h" #include "util/runtime_profile.h" namespace palo { class PlainTextLineReaderTest : public testing::Test { public: PlainTextLineReaderTest() : _profile(&_obj_pool, "TestProfile") { } protected: virtual void SetUp() { } virtual void TearDown() { } private: ObjectPool _obj_pool; RuntimeProfile _profile; }; TEST_F(PlainTextLineReaderTest, lz4_normal_use) { LocalFileReader file_reader( "./be/test/exec/test_data/plain_text_line_reader/test_file.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, -1, '\n'); const uint8_t* ptr; size_t size; bool eof; // 1,2 st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(3, size); ASSERT_FALSE(eof); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(0, size); ASSERT_FALSE(eof); // 1,2,3,4 st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(7, size); ASSERT_FALSE(eof); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_TRUE(eof); } TEST_F(PlainTextLineReaderTest, lz4_test_limit) { LocalFileReader file_reader("./be/test/exec/test_data/plain_text_line_reader/limit.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, 8, '\n'); const uint8_t* ptr; size_t size; bool eof; st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(5, size); ASSERT_FALSE(eof); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); ASSERT_EQ(0, size); st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(5, size); ASSERT_FALSE(eof); LOG(INFO) << std::string((const char*)ptr, size); st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); } TEST_F(PlainTextLineReaderTest, lz4_test_limit2) { LocalFileReader file_reader("./be/test/exec/test_data/plain_text_line_reader/limit.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, 6, '\n'); const uint8_t* ptr; size_t size; bool eof; st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(5, size); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); } TEST_F(PlainTextLineReaderTest, lz4_test_limit3) { LocalFileReader file_reader("./be/test/exec/test_data/plain_text_line_reader/limit.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, 7, '\n'); const uint8_t* ptr; size_t size; bool eof; st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(5, size); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); ASSERT_EQ(0, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); } TEST_F(PlainTextLineReaderTest, lz4_test_limit4) { LocalFileReader file_reader("./be/test/exec/test_data/plain_text_line_reader/limit.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, 7, '\n'); const uint8_t* ptr; size_t size; bool eof; st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_EQ(5, size); LOG(INFO) << std::string((const char*)ptr, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); ASSERT_FALSE(eof); ASSERT_EQ(0, size); // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); } TEST_F(PlainTextLineReaderTest, lz4_test_limit5) { LocalFileReader file_reader("./be/test/exec/test_data/plain_text_line_reader/limit.csv.lz4", 0); auto st = file_reader.open(); ASSERT_TRUE(st.ok()); Decompressor* decompressor; st = Decompressor::create_decompressor(CompressType::LZ4FRAME, &decompressor); ASSERT_TRUE(st.ok()); PlainTextLineReader line_reader(&_profile, &file_reader, decompressor, 0, '\n'); const uint8_t* ptr; size_t size; bool eof; // Empty st = line_reader.read_line(&ptr, &size, &eof); ASSERT_TRUE(st.ok()); } } // end namespace palo int main(int argc, char** argv) { // std::string conffile = std::string(getenv("PALO_HOME")) + "/conf/be.conf"; // if (!palo::config::init(conffile.c_str(), false)) { // fprintf(stderr, "error read config file. \n"); // return -1; // } // palo::init_glog("be-test"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
c++
code
7,083
1,655
#pragma once // Original author: Marcel Campen #include <typed-geometry/types/color.hh> #include <vector> namespace LayoutEmbedding { class HaltonColorGenerator { public: explicit HaltonColorGenerator(int _skip = 250); tg::color3 generate_next_color(); std::vector<tg::color3> generate_next_colors(int _n); private: double halton(int _index); double random_interval(int _index, double _min, double _max); tg::color3 hsl2rgb(double _h, double _sl, double _l); int current[3]; // current Halton index int bases[3]; // Halton prime bases double inverse_bases[3]; }; }
c++
code
608
127
//======================================================================= // Copyright (c) 2014-2018 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifdef ETL_CUDA #include "etl/impl/cublas/cuda.hpp" #endif namespace etl { #ifdef ETL_CUDA /*! * \brief GPU memory allocator. * * All GPU memory allocations should be made through this helper. */ struct gpu_memory_allocator { private: /*! * \brief Allocate GPU memory of the given size * \param size The memory size * \return The allocated GPU memory */ template <typename T> static T* base_allocate(size_t size) { T* memory = nullptr; auto cuda_status = cudaMalloc(&memory, size * sizeof(T)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << size * sizeof(T) << "B" << std::endl; exit(EXIT_FAILURE); } inc_counter("gpu:allocate"); return memory; } /*! * \brief Release memory allocated by this allocator * \param gpu_memory The GPU memory allocated * \param size The size of the allocated GPU memory */ static void base_release(const void* gpu_memory) { //Note: the const_cast is only here to allow compilation cuda_check(cudaFree((const_cast<void*>(gpu_memory)))); inc_counter("gpu:release"); } #ifndef ETL_GPU_POOL public: /*! * \brief Allocate GPU memory of the given size * \param size The memory size * \return The allocated GPU memory */ template <typename T> static T* allocate(size_t size) { return base_allocate<T>(size); } /*! * \brief Release memory allocated by this allocator * \param gpu_memory The GPU memory allocated * \param size The size of the allocated GPU memory */ static void release(const void* gpu_memory, size_t size) { base_release(gpu_memory); cpp_unused(size); } /*! * \brief Release all memory acquired by the allocator. * * This has no effect if the allocator does not use a memory * pool. */ static void clear() { // This allocator does not store memory } #else // ETL_GPU_POOL #ifdef ETL_GPU_POOL_SIZE static constexpr size_t entries = ETL_GPU_POOL_SIZE; ///< The entries limit of the pool #else #ifdef ETL_GPU_POOL_LIMIT static constexpr size_t entries = 256; ///< The entries limit of the pool #else static constexpr size_t entries = 64; ///< The entries limit of the pool #endif #endif #ifdef ETL_GPU_POOL_LIMIT static constexpr size_t limit = ETL_GPU_POOL_LIMIT; ///< The size limit of the pool #else static constexpr size_t limit = 1024 * 1024 * 1024; ///< The size limit of the pool #endif /*! * \brief An entry in the mini-pool */ struct mini_pool_entry { size_t size = 0; ///< The size, in bytes, of the memory void* memory = nullptr; ///< Pointer to the memory, if any }; /*! * \brief A very simple implementation for a GPU memory pool of * fixed-size * * Although it's quite simple, it should help in most cases * where the same operations are done several times, as in * Machine Learning. In that case, even a very simple pool like * this may greatly reduce the overhead of memory allocation. */ struct mini_pool { std::array<mini_pool_entry, entries> cache; ///< The cache of GPU memory addresses }; /*! * \brief Return a reference to the GPU pool * \return a reference to the GPU pool */ static mini_pool& get_pool() { static mini_pool pool; return pool; } /*! * \brief Return a reference to the GPU pool size * \return a reference to the GPU pool size */ static size_t& get_pool_size() { static size_t pool_size = 0; return pool_size; } /*! * \brief Return the lock for the pool * \return a reference to the pool lock */ static std::mutex& get_lock() { static std::mutex lock; return lock; } public: /*! * \brief Allocate GPU memory of the given size * \param size The memory size * \return The allocated GPU memory */ template <typename T> static T* allocate(size_t size) { const auto real_size = size * sizeof(T); // Try to get memory from the pool { std::lock_guard<std::mutex> l(get_lock()); if (get_pool_size()) { for (auto& slot : get_pool().cache) { if (slot.memory && slot.size == real_size) { auto memory = slot.memory; slot.memory = nullptr; get_pool_size() -= size; return static_cast<T*>(memory); } } } } // If a memory block is not found, allocate new memory return base_allocate<T>(size); } /*! * \brief Release memory allocated by this allocator * \param gpu_memory The GPU memory allocated * \param size The size of the allocated GPU memory */ template <typename T> static void release(const T* gpu_memory, size_t size) { // Try to get an empty slot { std::lock_guard<std::mutex> l(get_lock()); if (get_pool_size() + size < limit) { for (auto& slot : get_pool().cache) { if (!slot.memory) { slot.memory = const_cast<void*>(static_cast<const void*>(gpu_memory)); slot.size = size * sizeof(T); get_pool_size() += size; return; } } } } // If the cache is pool, release the memory base_release(gpu_memory); } /*! * \brief Release all memory acquired by the allocator. * * This has no effect if the allocator does not use a memory * pool. */ static void clear() { std::lock_guard<std::mutex> l(get_lock()); // Release each used slots // and clear them for (auto& slot : get_pool().cache) { if (slot.memory) { base_release(slot.memory); slot.memory = nullptr; slot.size = 0; } } get_pool_size() = 0; } #endif }; /*! * \brief GPU memory handler. * * This handler is responsible for allocating the memory and keeping CPU and GPU * memory consistency. */ template <typename T> struct gpu_memory_handler { private: mutable T* gpu_memory_ = nullptr; ///< The GPU memory pointer mutable size_t gpu_memory_size = 0; ///< The GPU memory size mutable bool cpu_up_to_date = true; ///< Is the CPU memory up to date mutable bool gpu_up_to_date = false; ///< Is the GPU memory up to date public: gpu_memory_handler() = default; /*! * \brief Copy construct a gpu_memory_handler * \param the gpu_memory_handler to copy from */ gpu_memory_handler(const gpu_memory_handler& rhs) : gpu_memory_size(rhs.gpu_memory_size), cpu_up_to_date(rhs.cpu_up_to_date), gpu_up_to_date(rhs.gpu_up_to_date) { if (rhs.gpu_up_to_date) { gpu_allocate_impl(gpu_memory_size); gpu_copy_from(rhs.gpu_memory_, gpu_memory_size); // The CPU status can be erased by gpu_copy_from if (rhs.cpu_up_to_date) { validate_cpu(); } } else { gpu_memory_ = nullptr; } cpp_assert(rhs.is_cpu_up_to_date() == this->is_cpu_up_to_date(), "gpu_memory_handler(&) must preserve CPU status"); cpp_assert(rhs.is_gpu_up_to_date() == this->is_gpu_up_to_date(), "gpu_memory_handler(&) must preserve GPU status"); } /*! * \brief Move construct a gpu_memory_handler */ gpu_memory_handler(gpu_memory_handler&& rhs) noexcept : gpu_memory_(rhs.gpu_memory_), gpu_memory_size(rhs.gpu_memory_size), cpu_up_to_date(rhs.cpu_up_to_date), gpu_up_to_date(rhs.gpu_up_to_date) { rhs.gpu_memory_ = nullptr; rhs.gpu_memory_size = 0; } /*! * \brief Copy assign a gpu_memory_handler * \param the gpu_memory_handler to copy from * \return a reference to this object */ gpu_memory_handler& operator=(const gpu_memory_handler& rhs) { if (this != &rhs) { // Release the previous memory, if any if (gpu_memory_) { gpu_memory_allocator::release(gpu_memory_, gpu_memory_size); gpu_memory_ = nullptr; } // Copy the size from rhs gpu_memory_size = rhs.gpu_memory_size; // Copy the contents of rhs if (rhs.gpu_up_to_date) { gpu_allocate_impl(gpu_memory_size); gpu_copy_from(rhs.gpu_memory_, gpu_memory_size); } else { gpu_memory_ = nullptr; } // Copy the status (at the end, otherwise gpu_copy_from will screw them) cpu_up_to_date = rhs.cpu_up_to_date; gpu_up_to_date = rhs.gpu_up_to_date; } return *this; } /*! * \brief Move assign a gpu_memory_handler */ gpu_memory_handler& operator=(gpu_memory_handler&& rhs) noexcept { if (this != &rhs) { // Release the previous memory, if any if (gpu_memory_) { gpu_memory_allocator::release(gpu_memory_, gpu_memory_size); gpu_memory_ = nullptr; } // Steal the values and contents from rhs gpu_memory_ = rhs.gpu_memory_; gpu_memory_size = rhs.gpu_memory_size; cpu_up_to_date = rhs.cpu_up_to_date; gpu_up_to_date = rhs.gpu_up_to_date; // Make sure rhs does not have point to the memory rhs.gpu_memory_ = nullptr; rhs.gpu_memory_size = 0; } return *this; } /*! * \brief Destroys the GPU memory handler. This effectively * releases any memory allocated. */ ~gpu_memory_handler() { if (gpu_memory_) { gpu_memory_allocator::release(gpu_memory_, gpu_memory_size); } } /*! * \brief Indicates if the CPU memory is up to date. * \return true if the CPU memory is up to date, false otherwise. */ bool is_cpu_up_to_date() const noexcept { return cpu_up_to_date; } /*! * \brief Indicates if the GPU memory is up to date. * \return true if the GPU memory is up to date, false otherwise. */ bool is_gpu_up_to_date() const noexcept { return gpu_up_to_date; } /*! * \brief Return GPU memory of this expression, if any. * \return a pointer to the GPU memory or nullptr if not allocated in GPU. */ T* gpu_memory() const noexcept { return gpu_memory_; } /*! * \brief Evict the expression from GPU. */ void gpu_evict() const noexcept { if (gpu_memory_) { gpu_memory_allocator::release(gpu_memory_, gpu_memory_size); gpu_memory_ = nullptr; gpu_memory_size = 0; } invalidate_gpu(); } /*! * \brief Invalidates the CPU memory */ void invalidate_cpu() const noexcept { cpu_up_to_date = false; cpp_assert(gpu_up_to_date, "Cannot invalidate the CPU if the GPU is not up to date"); } /*! * \brief Invalidates the GPU memory */ void invalidate_gpu() const noexcept { gpu_up_to_date = false; cpp_assert(cpu_up_to_date, "Cannot invalidate the GPU if the CPU is not up to date"); } /*! * \brief Validates the CPU memory */ void validate_cpu() const noexcept { cpu_up_to_date = true; } /*! * \brief Validates the GPU memory */ void validate_gpu() const noexcept { gpu_up_to_date = true; } /*! * \brief Ensures that the GPU memory is allocated and that the GPU memory * is up to date (to undefined value). * \param etl_size The size of the memory */ void ensure_gpu_allocated(size_t etl_size) const { if (!is_gpu_allocated()) { gpu_allocate_impl(etl_size); } } /*! * \brief Allocate memory on the GPU for the expression and copy the values into the GPU. * \param cpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void ensure_gpu_up_to_date(const T* cpu_memory, size_t etl_size) const { // Make sure there is some memory allocate if (!is_gpu_allocated()) { gpu_allocate_impl(etl_size); } if (!gpu_up_to_date) { cpu_to_gpu(cpu_memory, etl_size); } } /*! * \brief Copy back from the GPU to the expression memory if * necessary. * \param cpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void ensure_cpu_up_to_date(const T* cpu_memory, size_t etl_size) const { if (!cpu_up_to_date) { gpu_to_cpu(cpu_memory, etl_size); } } /*! * \brief Copy from GPU to GPU * \param gpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void gpu_copy_from(const T* gpu_memory, size_t etl_size) const { cpp_assert(is_gpu_allocated(), "GPU must be allocated before copy"); cpp_assert(gpu_memory, "Cannot copy from invalid memory"); cpp_assert(etl_size, "Cannot copy with a size of zero"); cuda_check(cudaMemcpy(const_cast<std::remove_const_t<T>*>(gpu_memory_), const_cast<std::remove_const_t<T>*>(gpu_memory), etl_size * sizeof(T), cudaMemcpyDeviceToDevice)); gpu_up_to_date = true; cpu_up_to_date = false; } private: /*! * \brief Allocate memory on the GPU for the expression */ void gpu_allocate_impl(size_t etl_size) const { cpp_assert(!is_gpu_allocated(), "Trying to allocate already allocated GPU gpu_memory_"); gpu_memory_ = gpu_memory_allocator::allocate<T>(etl_size); gpu_memory_size = etl_size; } /*! * \brief Copy back from the CPU to the GPU */ void cpu_to_gpu(const T* cpu_memory, size_t etl_size) const { cpp_assert(is_gpu_allocated(), "Cannot copy to unallocated GPU memory"); cpp_assert(!gpu_up_to_date, "Copy must only be done if necessary"); cpp_assert(cpu_up_to_date, "Copy from invalid memory!"); cpp_assert(cpu_memory, "cpu_memory is nullptr in entry to cpu_to_gpu"); cpp_assert(gpu_memory_, "gpu_memory_ is nullptr in entry to cpu_to_gpu"); cuda_check(cudaMemcpy(const_cast<std::remove_const_t<T>*>(gpu_memory_), const_cast<std::remove_const_t<T>*>(cpu_memory), etl_size * sizeof(T), cudaMemcpyHostToDevice)); gpu_up_to_date = true; inc_counter("gpu:cpu_to_gpu"); } /*! * \brief Copy back from the GPU to the expression memory. */ void gpu_to_cpu(const T* cpu_memory, size_t etl_size) const { cpp_assert(is_gpu_allocated(), "Cannot copy from unallocated GPU memory()"); cpp_assert(gpu_up_to_date, "Cannot copy from invalid memory"); cpp_assert(!cpu_up_to_date, "Copy done without reason"); cpp_assert(cpu_memory, "cpu_memory is nullptr in entry to gpu_to_cpu"); cpp_assert(gpu_memory_, "gpu_memory_ is nullptr in entry to gpu_to_cpu"); cuda_check(cudaMemcpy(const_cast<std::remove_const_t<T>*>(cpu_memory), const_cast<std::remove_const_t<T>*>(gpu_memory_), etl_size * sizeof(T), cudaMemcpyDeviceToHost)); cpu_up_to_date = true; inc_counter("gpu:gpu_to_cpu"); } /*! * \brief Indicates if the expression is allocated in GPU. * \return true if the expression is allocated in GPU, false otherwise */ bool is_gpu_allocated() const noexcept { return gpu_memory_; } }; #else template <typename T> struct gpu_memory_handler { /*! * \brief Return GPU memory of this expression, if any. * \return a pointer to the GPU memory or nullptr if not allocated in GPU. */ T* gpu_memory() const noexcept { return nullptr; } /*! * \brief Indicates if the CPU memory is up to date. * \return true if the CPU memory is up to date, false otherwise. */ bool is_cpu_up_to_date() const noexcept { return true; } /*! * \brief Indicates if the GPU memory is up to date. * \return true if the GPU memory is up to date, false otherwise. */ bool is_gpu_up_to_date() const noexcept { return false; } /*! * \brief Evict the expression from GPU. */ void gpu_evict() const noexcept {} /*! * \brief Invalidates the CPU memory */ void invalidate_cpu() const noexcept {} /*! * \brief Invalidates the GPU memory */ void invalidate_gpu() const noexcept {} /*! * \brief Validates the CPU memory */ void validate_cpu() const noexcept {} /*! * \brief Validates the GPU memory */ void validate_gpu() const noexcept {} /*! * \brief Ensures that the GPU memory is allocated and that the GPU memory * is up to date (to undefined value). * \param etl_size The size of the memory */ void ensure_gpu_allocated(size_t etl_size) const { cpp_unused(etl_size); } /*! * \brief Allocate memory on the GPU for the expression and copy the values into the GPU. * \param cpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void ensure_gpu_up_to_date(const T* cpu_memory, size_t etl_size) const { cpp_unused(cpu_memory); cpp_unused(etl_size); } /*! * \brief Copy back from the GPU to the expression memory if * necessary. * \param cpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void ensure_cpu_up_to_date(const T* cpu_memory, size_t etl_size) const { cpp_unused(cpu_memory); cpp_unused(etl_size); } /*! * \brief Copy from GPU to GPU * \param gpu_memory Pointer to CPU memory * \param etl_size The size of the memory */ void gpu_copy_from(const T* gpu_memory, size_t etl_size) const { cpp_unused(gpu_memory); cpp_unused(etl_size); } }; #endif } //end of namespace etl #ifdef ETL_CUDA #include "etl/impl/cublas/cuda_memory.hpp" #endif
c++
code
19,141
3,494
// Copyright (c) 2012-2015 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 "key.h" #include "keystore.h" #include "main.h" #include "policy/policy.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "test/test_lunar.h" #ifdef ENABLE_WALLET #include "wallet/wallet_ismine.h" #endif #include <vector> #include <boost/test/unit_test.hpp> using namespace std; // Helpers: static std::vector<unsigned char> Serialize(const CScript& s) { std::vector<unsigned char> sSerialized(s.begin(), s.end()); return sSerialized; } static bool Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict, ScriptError& err) { // Create dummy to/from transactions: CMutableTransaction txFrom; txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = scriptPubKey; CMutableTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = scriptSig; txTo.vout[0].nValue = 1; return VerifyScript(scriptSig, scriptPubKey, fStrict ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, MutableTransactionSignatureChecker(&txTo, 0), &err); } BOOST_FIXTURE_TEST_SUITE(script_P2SH_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sign) { LOCK(cs_main); // Pay-to-script-hash looks like this: // scriptSig: <sig> <sig...> <serialized_script> // scriptPubKey: HASH160 <hash> EQUAL // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } // 8 Scripts: checking all combinations of // different keys, straight/P2SH, pubkey/pubkeyhash CScript standardScripts[4]; standardScripts[0] << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; standardScripts[1] = GetScriptForDestination(key[1].GetPubKey().GetID()); standardScripts[2] << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG; standardScripts[3] = GetScriptForDestination(key[2].GetPubKey().GetID()); CScript evalScripts[4]; for (int i = 0; i < 4; i++) { keystore.AddCScript(standardScripts[i]); evalScripts[i] = GetScriptForDestination(CScriptID(standardScripts[i])); } CMutableTransaction txFrom; // Funding transaction: string reason; txFrom.vout.resize(8); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = evalScripts[i]; txFrom.vout[i].nValue = COIN; txFrom.vout[i+4].scriptPubKey = standardScripts[i]; txFrom.vout[i+4].nValue = COIN; } BOOST_CHECK(IsStandardTx(txFrom, reason)); CMutableTransaction txTo[8]; // Spending transactions for (int i = 0; i < 8; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; #ifdef ENABLE_WALLET BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); #endif } for (int i = 0; i < 8; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } // All of the above should be OK, and the txTos have valid signatures // Check to make sure signature verification fails if we use the wrong ScriptSig: for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { CScript sigSave = txTo[i].vin[0].scriptSig; txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig; bool sigOK = CScriptCheck(CCoins(txFrom, 0), txTo[i], 0, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, false)(); if (i == j) BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j)); else BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j)); txTo[i].vin[0].scriptSig = sigSave; } } BOOST_AUTO_TEST_CASE(norecurse) { ScriptError err; // Make sure only the outer pay-to-script-hash does the // extra-validation thing: CScript invalidAsScript; invalidAsScript << OP_INVALIDOPCODE << OP_INVALIDOPCODE; CScript p2sh = GetScriptForDestination(CScriptID(invalidAsScript)); CScript scriptSig; scriptSig << Serialize(invalidAsScript); // Should not verify, because it will try to execute OP_INVALIDOPCODE BOOST_CHECK(!Verify(scriptSig, p2sh, true, err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_BAD_OPCODE, ScriptErrorString(err)); // Try to recur, and verification should succeed because // the inner HASH160 <> EQUAL should only check the hash: CScript p2sh2 = GetScriptForDestination(CScriptID(p2sh)); CScript scriptSig2; scriptSig2 << Serialize(invalidAsScript) << Serialize(p2sh); BOOST_CHECK(Verify(scriptSig2, p2sh2, true, err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(set) { LOCK(cs_main); // Test the CScript::Set* methods CBasicKeyStore keystore; CKey key[4]; std::vector<CPubKey> keys; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keys.push_back(key[i].GetPubKey()); } CScript inner[4]; inner[0] = GetScriptForDestination(key[0].GetPubKey().GetID()); inner[1] = GetScriptForMultisig(2, std::vector<CPubKey>(keys.begin(), keys.begin()+2)); inner[2] = GetScriptForMultisig(1, std::vector<CPubKey>(keys.begin(), keys.begin()+2)); inner[3] = GetScriptForMultisig(2, std::vector<CPubKey>(keys.begin(), keys.begin()+3)); CScript outer[4]; for (int i = 0; i < 4; i++) { outer[i] = GetScriptForDestination(CScriptID(inner[i])); keystore.AddCScript(inner[i]); } CMutableTransaction txFrom; // Funding transaction: string reason; txFrom.vout.resize(4); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = outer[i]; txFrom.vout[i].nValue = CENT; } BOOST_CHECK(IsStandardTx(txFrom, reason)); CMutableTransaction txTo[4]; // Spending transactions for (int i = 0; i < 4; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1*CENT; txTo[i].vout[0].scriptPubKey = inner[i]; #ifdef ENABLE_WALLET BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); #endif } for (int i = 0; i < 4; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); BOOST_CHECK_MESSAGE(IsStandardTx(txTo[i], reason), strprintf("txTo[%d].IsStandard", i)); } } BOOST_AUTO_TEST_CASE(is) { // Test CScript::IsPayToScriptHash() uint160 dummy; CScript p2sh; p2sh << OP_HASH160 << ToByteVector(dummy) << OP_EQUAL; BOOST_CHECK(p2sh.IsPayToScriptHash()); // Not considered pay-to-script-hash if using one of the OP_PUSHDATA opcodes: static const unsigned char direct[] = { OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL }; BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToScriptHash()); static const unsigned char pushdata1[] = { OP_HASH160, OP_PUSHDATA1, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL }; BOOST_CHECK(!CScript(pushdata1, pushdata1+sizeof(pushdata1)).IsPayToScriptHash()); static const unsigned char pushdata2[] = { OP_HASH160, OP_PUSHDATA2, 20,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL }; BOOST_CHECK(!CScript(pushdata2, pushdata2+sizeof(pushdata2)).IsPayToScriptHash()); static const unsigned char pushdata4[] = { OP_HASH160, OP_PUSHDATA4, 20,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL }; BOOST_CHECK(!CScript(pushdata4, pushdata4+sizeof(pushdata4)).IsPayToScriptHash()); CScript not_p2sh; BOOST_CHECK(!not_p2sh.IsPayToScriptHash()); not_p2sh.clear(); not_p2sh << OP_HASH160 << ToByteVector(dummy) << ToByteVector(dummy) << OP_EQUAL; BOOST_CHECK(!not_p2sh.IsPayToScriptHash()); not_p2sh.clear(); not_p2sh << OP_NOP << ToByteVector(dummy) << OP_EQUAL; BOOST_CHECK(!not_p2sh.IsPayToScriptHash()); not_p2sh.clear(); not_p2sh << OP_HASH160 << ToByteVector(dummy) << OP_CHECKSIG; BOOST_CHECK(!not_p2sh.IsPayToScriptHash()); } BOOST_AUTO_TEST_CASE(switchover) { // Test switch over code CScript notValid; ScriptError err; notValid << OP_11 << OP_12 << OP_EQUALVERIFY; CScript scriptSig; scriptSig << Serialize(notValid); CScript fund = GetScriptForDestination(CScriptID(notValid)); // Validation should succeed under old rules (hash is correct): BOOST_CHECK(Verify(scriptSig, fund, false, err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); // Fail under new: BOOST_CHECK(!Verify(scriptSig, fund, true, err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EQUALVERIFY, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(AreInputsStandard) { LOCK(cs_main); CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); CBasicKeyStore keystore; CKey key[6]; vector<CPubKey> keys; for (int i = 0; i < 6; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } for (int i = 0; i < 3; i++) keys.push_back(key[i].GetPubKey()); CMutableTransaction txFrom; txFrom.vout.resize(7); // First three are standard: CScript pay1 = GetScriptForDestination(key[0].GetPubKey().GetID()); keystore.AddCScript(pay1); CScript pay1of3 = GetScriptForMultisig(1, keys); txFrom.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(pay1)); // P2SH (OP_CHECKSIG) txFrom.vout[0].nValue = 1000; txFrom.vout[1].scriptPubKey = pay1; // ordinary OP_CHECKSIG txFrom.vout[1].nValue = 2000; txFrom.vout[2].scriptPubKey = pay1of3; // ordinary OP_CHECKMULTISIG txFrom.vout[2].nValue = 3000; // vout[3] is complicated 1-of-3 AND 2-of-3 // ... that is OK if wrapped in P2SH: CScript oneAndTwo; oneAndTwo << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()); oneAndTwo << OP_3 << OP_CHECKMULTISIGVERIFY; oneAndTwo << OP_2 << ToByteVector(key[3].GetPubKey()) << ToByteVector(key[4].GetPubKey()) << ToByteVector(key[5].GetPubKey()); oneAndTwo << OP_3 << OP_CHECKMULTISIG; keystore.AddCScript(oneAndTwo); txFrom.vout[3].scriptPubKey = GetScriptForDestination(CScriptID(oneAndTwo)); txFrom.vout[3].nValue = 4000; // vout[4] is max sigops: CScript fifteenSigops; fifteenSigops << OP_1; for (unsigned i = 0; i < MAX_P2SH_SIGOPS; i++) fifteenSigops << ToByteVector(key[i%3].GetPubKey()); fifteenSigops << OP_15 << OP_CHECKMULTISIG; keystore.AddCScript(fifteenSigops); txFrom.vout[4].scriptPubKey = GetScriptForDestination(CScriptID(fifteenSigops)); txFrom.vout[4].nValue = 5000; // vout[5/6] are non-standard because they exceed MAX_P2SH_SIGOPS CScript sixteenSigops; sixteenSigops << OP_16 << OP_CHECKMULTISIG; keystore.AddCScript(sixteenSigops); txFrom.vout[5].scriptPubKey = GetScriptForDestination(CScriptID(fifteenSigops)); txFrom.vout[5].nValue = 5000; CScript twentySigops; twentySigops << OP_CHECKMULTISIG; keystore.AddCScript(twentySigops); txFrom.vout[6].scriptPubKey = GetScriptForDestination(CScriptID(twentySigops)); txFrom.vout[6].nValue = 6000; coins.ModifyCoins(txFrom.GetHash())->FromTx(txFrom, 0); CMutableTransaction txTo; txTo.vout.resize(1); txTo.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID()); txTo.vin.resize(5); for (int i = 0; i < 5; i++) { txTo.vin[i].prevout.n = i; txTo.vin[i].prevout.hash = txFrom.GetHash(); } BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 0)); BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 1)); BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 2)); // SignSignature doesn't know how to sign these. We're // not testing validating signatures, so just create // dummy signatures that DO include the correct P2SH scripts: txTo.vin[3].scriptSig << OP_11 << OP_11 << vector<unsigned char>(oneAndTwo.begin(), oneAndTwo.end()); txTo.vin[4].scriptSig << vector<unsigned char>(fifteenSigops.begin(), fifteenSigops.end()); BOOST_CHECK(::AreInputsStandard(txTo, coins)); // 22 P2SH sigops for all inputs (1 for vin[0], 6 for vin[3], 15 for vin[4] BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txTo, coins), 22U); CMutableTransaction txToNonStd1; txToNonStd1.vout.resize(1); txToNonStd1.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID()); txToNonStd1.vout[0].nValue = 1000; txToNonStd1.vin.resize(1); txToNonStd1.vin[0].prevout.n = 5; txToNonStd1.vin[0].prevout.hash = txFrom.GetHash(); txToNonStd1.vin[0].scriptSig << vector<unsigned char>(sixteenSigops.begin(), sixteenSigops.end()); BOOST_CHECK(!::AreInputsStandard(txToNonStd1, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd1, coins), 16U); CMutableTransaction txToNonStd2; txToNonStd2.vout.resize(1); txToNonStd2.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID()); txToNonStd2.vout[0].nValue = 1000; txToNonStd2.vin.resize(1); txToNonStd2.vin[0].prevout.n = 6; txToNonStd2.vin[0].prevout.hash = txFrom.GetHash(); txToNonStd2.vin[0].scriptSig << vector<unsigned char>(twentySigops.begin(), twentySigops.end()); BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U); } BOOST_AUTO_TEST_SUITE_END()
c++
code
14,104
3,536
#include "selfdrive/boardd/panda.h" #include <unistd.h> #include <cassert> #include <stdexcept> #include <vector> #include "cereal/messaging/messaging.h" #include "selfdrive/common/gpio.h" #include "selfdrive/common/swaglog.h" #include "selfdrive/common/util.h" Panda::Panda(std::string serial) { // init libusb ssize_t num_devices; libusb_device **dev_list = NULL; int err = libusb_init(&ctx); if (err != 0) { goto fail; } #if LIBUSB_API_VERSION >= 0x01000106 libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); #else libusb_set_debug(ctx, 3); #endif // connect by serial num_devices = libusb_get_device_list(ctx, &dev_list); if (num_devices < 0) { goto fail; } for (size_t i = 0; i < num_devices; ++i) { libusb_device_descriptor desc; libusb_get_device_descriptor(dev_list[i], &desc); if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { libusb_open(dev_list[i], &dev_handle); if (dev_handle == NULL) { goto fail; } unsigned char desc_serial[25]; int ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, sizeof(desc_serial)); if (ret < 0) { goto fail; } if (serial.empty() || serial.compare(reinterpret_cast<const char*>(desc_serial)) == 0) { break; } libusb_close(dev_handle); dev_handle = NULL; } } libusb_free_device_list(dev_list, 1); if (libusb_kernel_driver_active(dev_handle, 0) == 1) { libusb_detach_kernel_driver(dev_handle, 0); } err = libusb_set_configuration(dev_handle, 1); if (err != 0) { goto fail; } err = libusb_claim_interface(dev_handle, 0); if (err != 0) { goto fail; } hw_type = get_hw_type(); assert((hw_type != cereal::PandaState::PandaType::WHITE_PANDA) && (hw_type != cereal::PandaState::PandaType::GREY_PANDA)); has_rtc = (hw_type == cereal::PandaState::PandaType::UNO) || (hw_type == cereal::PandaState::PandaType::DOS); return; fail: cleanup(); if (dev_list != NULL) { libusb_free_device_list(dev_list, 1); } throw std::runtime_error("Error connecting to panda"); } Panda::~Panda() { std::lock_guard lk(usb_lock); cleanup(); connected = false; } void Panda::cleanup() { if (dev_handle) { libusb_release_interface(dev_handle, 0); libusb_close(dev_handle); } if (ctx) { libusb_exit(ctx); } } void Panda::handle_usb_issue(int err, const char func[]) { LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); if (err == LIBUSB_ERROR_NO_DEVICE) { LOGE("lost connection"); connected = false; } // TODO: check other errors, is simply retrying okay? } int Panda::usb_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { int err; const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; if (!connected) { return LIBUSB_ERROR_NO_DEVICE; } std::lock_guard lk(usb_lock); do { err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); if (err < 0) handle_usb_issue(err, __func__); } while (err < 0 && connected); return err; } int Panda::usb_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { int err; const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; if (!connected) { return LIBUSB_ERROR_NO_DEVICE; } std::lock_guard lk(usb_lock); do { err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); if (err < 0) handle_usb_issue(err, __func__); } while (err < 0 && connected); return err; } int Panda::usb_bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { int err; int transferred = 0; if (!connected) { return 0; } std::lock_guard lk(usb_lock); do { // Try sending can messages. If the receive buffer on the panda is full it will NAK // and libusb will try again. After 5ms, it will time out. We will drop the messages. err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); if (err == LIBUSB_ERROR_TIMEOUT) { LOGW("Transmit buffer full"); break; } else if (err != 0 || length != transferred) { handle_usb_issue(err, __func__); } } while(err != 0 && connected); return transferred; } int Panda::usb_bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { int err; int transferred = 0; if (!connected) { return 0; } std::lock_guard lk(usb_lock); do { err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); if (err == LIBUSB_ERROR_TIMEOUT) { break; // timeout is okay to exit, recv still happened } else if (err == LIBUSB_ERROR_OVERFLOW) { comms_healthy = false; LOGE_100("overflow got 0x%x", transferred); } else if (err != 0) { handle_usb_issue(err, __func__); } } while(err != 0 && connected); return transferred; } void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, int safety_param) { usb_write(0xdc, (uint16_t)safety_model, safety_param); } void Panda::set_unsafe_mode(uint16_t unsafe_mode) { usb_write(0xdf, unsafe_mode, 0); } cereal::PandaState::PandaType Panda::get_hw_type() { unsigned char hw_query[1] = {0}; usb_read(0xc1, 0, 0, hw_query, 1); return (cereal::PandaState::PandaType)(hw_query[0]); } void Panda::set_rtc(struct tm sys_time) { // tm struct has year defined as years since 1900 usb_write(0xa1, (uint16_t)(1900 + sys_time.tm_year), 0); usb_write(0xa2, (uint16_t)(1 + sys_time.tm_mon), 0); usb_write(0xa3, (uint16_t)sys_time.tm_mday, 0); // usb_write(0xa4, (uint16_t)(1 + sys_time.tm_wday), 0); usb_write(0xa5, (uint16_t)sys_time.tm_hour, 0); usb_write(0xa6, (uint16_t)sys_time.tm_min, 0); usb_write(0xa7, (uint16_t)sys_time.tm_sec, 0); } struct tm Panda::get_rtc() { struct __attribute__((packed)) timestamp_t { uint16_t year; // Starts at 0 uint8_t month; uint8_t day; uint8_t weekday; uint8_t hour; uint8_t minute; uint8_t second; } rtc_time = {0}; usb_read(0xa0, 0, 0, (unsigned char*)&rtc_time, sizeof(rtc_time)); struct tm new_time = { 0 }; new_time.tm_year = rtc_time.year - 1900; // tm struct has year defined as years since 1900 new_time.tm_mon = rtc_time.month - 1; new_time.tm_mday = rtc_time.day; new_time.tm_hour = rtc_time.hour; new_time.tm_min = rtc_time.minute; new_time.tm_sec = rtc_time.second; return new_time; } void Panda::set_fan_speed(uint16_t fan_speed) { usb_write(0xb1, fan_speed, 0); } uint16_t Panda::get_fan_speed() { uint16_t fan_speed_rpm = 0; usb_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); return fan_speed_rpm; } void Panda::set_ir_pwr(uint16_t ir_pwr) { usb_write(0xb0, ir_pwr, 0); } health_t Panda::get_state() { health_t health {0}; usb_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); return health; } void Panda::set_loopback(bool loopback) { usb_write(0xe5, loopback, 0); } std::optional<std::vector<uint8_t>> Panda::get_firmware_version() { std::vector<uint8_t> fw_sig_buf(128); int read_1 = usb_read(0xd3, 0, 0, &fw_sig_buf[0], 64); int read_2 = usb_read(0xd4, 0, 0, &fw_sig_buf[64], 64); return ((read_1 == 64) && (read_2 == 64)) ? std::make_optional(fw_sig_buf) : std::nullopt; } std::optional<std::string> Panda::get_serial() { char serial_buf[17] = {'\0'}; int err = usb_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); return err >= 0 ? std::make_optional(serial_buf) : std::nullopt; } void Panda::set_power_saving(bool power_saving) { usb_write(0xe7, power_saving, 0); } void Panda::set_usb_power_mode(cereal::PandaState::UsbPowerMode power_mode) { usb_write(0xe6, (uint16_t)power_mode, 0); } void Panda::send_heartbeat() { usb_write(0xf3, 1, 0); } void Panda::can_send(capnp::List<cereal::CanData>::Reader can_data_list) { static std::vector<uint32_t> send; const int msg_count = can_data_list.size(); send.resize(msg_count*0x10); for (int i = 0; i < msg_count; i++) { auto cmsg = can_data_list[i]; if (cmsg.getAddress() >= 0x800) { // extended send[i*4] = (cmsg.getAddress() << 3) | 5; } else { // normal send[i*4] = (cmsg.getAddress() << 21) | 1; } auto can_data = cmsg.getDat(); assert(can_data.size() <= 8); send[i*4+1] = can_data.size() | (cmsg.getSrc() << 4); memcpy(&send[i*4+2], can_data.begin(), can_data.size()); } usb_bulk_write(3, (unsigned char*)send.data(), send.size(), 5); } int Panda::can_receive(kj::Array<capnp::word>& out_buf) { uint32_t data[RECV_SIZE/4]; int recv = usb_bulk_read(0x81, (unsigned char*)data, RECV_SIZE); // Not sure if this can happen if (recv < 0) recv = 0; if (recv == RECV_SIZE) { LOGW("Receive buffer full"); } size_t num_msg = recv / 0x10; MessageBuilder msg; auto evt = msg.initEvent(); evt.setValid(comms_healthy); // populate message auto canData = evt.initCan(num_msg); for (int i = 0; i < num_msg; i++) { if (data[i*4] & 4) { // extended canData[i].setAddress(data[i*4] >> 3); //printf("got extended: %x\n", data[i*4] >> 3); } else { // normal canData[i].setAddress(data[i*4] >> 21); } canData[i].setBusTime(data[i*4+1] >> 16); int len = data[i*4+1]&0xF; canData[i].setDat(kj::arrayPtr((uint8_t*)&data[i*4+2], len)); canData[i].setSrc((data[i*4+1] >> 4) & 0xff); } out_buf = capnp::messageToFlatArray(msg); return recv; }
c++
code
9,761
2,469
#include "gtest/gtest.h" #include "array_types/arrays_mapping/ArraysMapping.h" namespace array_types { namespace arrays_mapping { class ArraysMappingTest : public ::testing::Test { protected: static const size_t fixedArrayLength = 5; }; TEST_F(ArraysMappingTest, unsignedIntegerArrays) { ArraysMapping arraysMapping; arraysMapping.setUint8Array(zserio::UInt8Array(fixedArrayLength)); arraysMapping.setUint16Array(zserio::UInt16Array(fixedArrayLength)); arraysMapping.setUint32Array(zserio::UInt32Array(fixedArrayLength)); arraysMapping.setUint64Array(zserio::UInt64Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, signedIntegerArrays) { ArraysMapping arraysMapping; arraysMapping.setInt8Array(zserio::Int8Array(fixedArrayLength)); arraysMapping.setInt16Array(zserio::Int16Array(fixedArrayLength)); arraysMapping.setInt32Array(zserio::Int32Array(fixedArrayLength)); arraysMapping.setInt64Array(zserio::Int64Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, unsignedBitfieldArrays) { ArraysMapping arraysMapping; arraysMapping.setBitfield8Array(zserio::UInt8Array(fixedArrayLength)); arraysMapping.setBitfield16Array(zserio::UInt16Array(fixedArrayLength)); arraysMapping.setBitfield32Array(zserio::UInt32Array(fixedArrayLength)); arraysMapping.setBitfield63Array(zserio::UInt64Array(fixedArrayLength)); arraysMapping.setVariableBitfieldLongArray(zserio::UInt64Array(fixedArrayLength)); arraysMapping.setVariableBitfieldIntArray(zserio::UInt32Array(fixedArrayLength)); arraysMapping.setVariableBitfieldShortArray(zserio::UInt16Array(fixedArrayLength)); arraysMapping.setVariableBitfieldByteArray(zserio::UInt8Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, signedBitfieldArrays) { ArraysMapping arraysMapping; arraysMapping.setIntfield8Array(zserio::Int8Array(fixedArrayLength)); arraysMapping.setIntfield16Array(zserio::Int16Array(fixedArrayLength)); arraysMapping.setIntfield32Array(zserio::Int32Array(fixedArrayLength)); arraysMapping.setIntfield64Array(zserio::Int64Array(fixedArrayLength)); arraysMapping.setVariableIntfieldLongArray(zserio::Int64Array(fixedArrayLength)); arraysMapping.setVariableIntfieldIntArray(zserio::Int32Array(fixedArrayLength)); arraysMapping.setVariableIntfieldShortArray(zserio::Int16Array(fixedArrayLength)); arraysMapping.setVariableIntfieldByteArray(zserio::Int8Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, float16Array) { ArraysMapping arraysMapping; arraysMapping.setFloat16Array(zserio::FloatArray(fixedArrayLength)); } TEST_F(ArraysMappingTest, variableUnsignedIntegerArrays) { ArraysMapping arraysMapping; arraysMapping.setVaruint16Array(zserio::VarUInt16Array(fixedArrayLength)); arraysMapping.setVaruint32Array(zserio::VarUInt32Array(fixedArrayLength)); arraysMapping.setVaruint64Array(zserio::VarUInt64Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, variableSignedIntegerArrays) { ArraysMapping arraysMapping; arraysMapping.setVarint16Array(zserio::VarInt16Array(fixedArrayLength)); arraysMapping.setVarint32Array(zserio::VarInt32Array(fixedArrayLength)); arraysMapping.setVarint64Array(zserio::VarInt64Array(fixedArrayLength)); } TEST_F(ArraysMappingTest, boolArray) { ArraysMapping arraysMapping; arraysMapping.setBoolArray(zserio::BoolArray(fixedArrayLength)); } TEST_F(ArraysMappingTest, stringArrays) { ArraysMapping arraysMapping; arraysMapping.setStringArray(zserio::StringArray(fixedArrayLength)); } TEST_F(ArraysMappingTest, compoundArray) { ArraysMapping arraysMapping; arraysMapping.setCompoundArray(zserio::ObjectArray<TestStructure>(fixedArrayLength)); } TEST_F(ArraysMappingTest, enumArray) { ArraysMapping arraysMapping; arraysMapping.setEnumArray(zserio::ObjectArray<TestEnum>(fixedArrayLength)); } } // namespace arrays_mapping } // namespace array_types
c++
code
3,950
628
class Solution { public: void dfs(int i, int j, bool & ok, vector<vector<int>>& grid1, vector<vector<int>>& grid2) { if (grid2[i][j] == 0) return; if (grid1[i][j] == 0) ok = false; grid2[i][j] = 0; int n = grid1.size(); int m = grid1[0].size(); if (i > 0) dfs(i-1, j, ok, grid1, grid2); if (i < n-1) dfs(i+1, j, ok, grid1, grid2); if (j > 0) dfs(i, j-1, ok, grid1, grid2); if (j < m-1) dfs(i, j+1, ok, grid1, grid2); } int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) { int count = 0; int n = grid1.size(); int m = grid1[0].size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid2[i][j] == 1) { bool ok = true; dfs(i, j, ok, grid1, grid2); if (ok) { ++count; } } } } return count; } };
c++
code
1,124
320
/** * @file * @brief Simple reading of an init file and system variables * @detailed read_init_file is the main function, but read_option_line does * most of the work though. Read through read_init_file to get an overview of * how Crawl loads options. This file also contains a large number of utility * functions for setting particular options and converting between human * readable strings and internal values. (E.g. str_to_enemy_hp_colour, * _weapon_to_str). There is also some code dealing with sorting menus. **/ #include "AppHdr.h" #include "initfile.h" #include "json.h" #include "json-wrapper.h" #include <algorithm> #include <cinttypes> #include <cctype> #include <cstdio> #include <cstdlib> #include <iomanip> #include <set> #include <string> #include "ability.h" #include "branch-data-json.h" #include "chardump.h" #include "clua.h" #include "colour.h" #include "defines.h" #include "delay.h" #include "describe.h" #include "directn.h" #include "dlua.h" #include "end.h" #include "errors.h" #include "files.h" #include "game-options.h" #include "ghost.h" #include "invent.h" #include "item-prop.h" #include "items.h" #include "jobs.h" #include "kills.h" #include "libutil.h" #include "macro.h" #include "mapdef.h" #include "message.h" #include "mon-util.h" #include "monster.h" #include "newgame.h" #include "options.h" #include "playable.h" #include "player.h" #include "prompt.h" #include "slot-select-mode.h" #include "species.h" #include "spl-util.h" #include "stash.h" #include "state.h" #include "stringutil.h" #include "syscalls.h" #include "tags.h" #include "tag-version.h" #include "throw.h" #include "travel.h" #include "unwind.h" #include "version.h" #include "viewchar.h" #include "view.h" #include "wizard-option-type.h" #ifdef USE_TILE #include "tilepick.h" #include "rltiles/tiledef-player.h" #endif #include "tiles-build-specific.h" // For finding the executable's path #ifdef TARGET_OS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shlwapi.h> #include <shlobj.h> #elif defined(TARGET_OS_MACOSX) extern char **NXArgv; #ifndef DATA_DIR_PATH #include <unistd.h> #endif #elif defined(UNIX) || defined(TARGET_COMPILER_MINGW) #include <unistd.h> #endif const string game_options::interrupt_prefix = "interrupt_"; system_environment SysEnv; game_options Options; static string _get_save_path(string subdir); static string _supported_language_listing(); static bool _first_less(const pair<int, int> &l, const pair<int, int> &r) { return l.first < r.first; } static bool _first_greater(const pair<int, int> &l, const pair<int, int> &r) { return l.first > r.first; } const vector<GameOption*> game_options::build_options_list() { #ifndef DEBUG const bool USING_TOUCH = #if defined(TOUCH_UI) true; #else false; #endif #endif const bool USING_DGL = #if defined(DGAMELAUNCH) true; #else false; #endif const bool USING_UNIX = #if defined(UNIX) true; #else false; #endif #ifdef USE_TILE const bool USING_WEB_TILES = #if defined(USE_TILE_WEB) true; #else false; #endif #endif #define SIMPLE_NAME(_opt) _opt, {#_opt} vector<GameOption*> options = { new BoolGameOption(SIMPLE_NAME(autopickup_starting_ammo), true), new BoolGameOption(SIMPLE_NAME(easy_door), true), new BoolGameOption(SIMPLE_NAME(default_show_all_skills), false), new BoolGameOption(SIMPLE_NAME(read_persist_options), false), new BoolGameOption(SIMPLE_NAME(auto_switch), false), new BoolGameOption(SIMPLE_NAME(suppress_startup_errors), false), new BoolGameOption(SIMPLE_NAME(simple_targeting), false), new BoolGameOption(easy_quit_item_prompts, { "easy_quit_item_prompts", "easy_quit_item_lists" }, true), new BoolGameOption(easy_unequip, { "easy_unequip", "easy_armour", "easy_armor" }, true), new BoolGameOption(SIMPLE_NAME(equip_unequip), false), new BoolGameOption(SIMPLE_NAME(jewellery_prompt), false), new BoolGameOption(SIMPLE_NAME(easy_door), true), new BoolGameOption(SIMPLE_NAME(warn_hatches), false), new BoolGameOption(SIMPLE_NAME(enable_recast_spell), true), new BoolGameOption(SIMPLE_NAME(auto_hide_spells), false), new BoolGameOption(SIMPLE_NAME(blink_brightens_background), false), new BoolGameOption(SIMPLE_NAME(bold_brightens_foreground), false), new BoolGameOption(SIMPLE_NAME(best_effort_brighten_background), false), #ifdef TARGET_OS_MACOSX new BoolGameOption(SIMPLE_NAME(best_effort_brighten_foreground), false), new BoolGameOption(SIMPLE_NAME(allow_extended_colours), true), #else new BoolGameOption(SIMPLE_NAME(best_effort_brighten_foreground), true), new BoolGameOption(SIMPLE_NAME(allow_extended_colours), false), #endif new BoolGameOption(SIMPLE_NAME(regex_search), false), new BoolGameOption(SIMPLE_NAME(autopickup_search), false), new BoolGameOption(SIMPLE_NAME(show_newturn_mark), true), new BoolGameOption(SIMPLE_NAME(show_game_time), true), new BoolGameOption(SIMPLE_NAME(equip_bar), false), new BoolGameOption(SIMPLE_NAME(animate_equip_bar), false), new BoolGameOption(SIMPLE_NAME(mouse_input), false), new BoolGameOption(SIMPLE_NAME(mlist_allow_alternate_layout), false), new BoolGameOption(SIMPLE_NAME(monster_item_view_coordinates), false), new ListGameOption<text_pattern>(SIMPLE_NAME(monster_item_view_features)), new BoolGameOption(SIMPLE_NAME(messages_at_top), false), new BoolGameOption(SIMPLE_NAME(msg_condense_repeats), true), new BoolGameOption(SIMPLE_NAME(msg_condense_short), true), new BoolGameOption(SIMPLE_NAME(view_lock_x), true), new BoolGameOption(SIMPLE_NAME(view_lock_y), true), new BoolGameOption(SIMPLE_NAME(centre_on_scroll), false), new BoolGameOption(SIMPLE_NAME(symmetric_scroll), true), new BoolGameOption(SIMPLE_NAME(always_show_exclusions), true), new BoolGameOption(SIMPLE_NAME(note_all_skill_levels), false), new BoolGameOption(SIMPLE_NAME(note_skill_max), true), new BoolGameOption(SIMPLE_NAME(note_xom_effects), true), new BoolGameOption(SIMPLE_NAME(note_chat_messages), false), new BoolGameOption(SIMPLE_NAME(note_dgl_messages), true), new BoolGameOption(SIMPLE_NAME(clear_messages), false), #ifdef DEBUG new BoolGameOption(SIMPLE_NAME(show_more), false), #else new BoolGameOption(SIMPLE_NAME(show_more), !USING_TOUCH), #endif new BoolGameOption(SIMPLE_NAME(small_more), false), new BoolGameOption(SIMPLE_NAME(pickup_thrown), true), new BoolGameOption(SIMPLE_NAME(show_travel_trail), USING_DGL), new BoolGameOption(SIMPLE_NAME(use_fake_cursor), USING_UNIX ), new BoolGameOption(SIMPLE_NAME(use_fake_player_cursor), true), new BoolGameOption(SIMPLE_NAME(show_player_species), false), new BoolGameOption(SIMPLE_NAME(use_modifier_prefix_keys), true), new BoolGameOption(SIMPLE_NAME(ability_menu), true), new BoolGameOption(SIMPLE_NAME(easy_floor_use), true), new BoolGameOption(SIMPLE_NAME(bad_item_prompt), true), new BoolGameOption(SIMPLE_NAME(dos_use_background_intensity), true), new BoolGameOption(SIMPLE_NAME(explore_greedy), true), new BoolGameOption(SIMPLE_NAME(explore_auto_rest), true), new BoolGameOption(SIMPLE_NAME(travel_key_stop), true), new BoolGameOption(SIMPLE_NAME(travel_one_unsafe_move), false), new BoolGameOption(SIMPLE_NAME(dump_on_save), true), new BoolGameOption(SIMPLE_NAME(rest_wait_both), false), new BoolGameOption(SIMPLE_NAME(rest_wait_ancestor), false), new BoolGameOption(SIMPLE_NAME(cloud_status), !is_tiles()), new BoolGameOption(SIMPLE_NAME(always_show_zot), false), new BoolGameOption(SIMPLE_NAME(darken_beyond_range), true), new BoolGameOption(SIMPLE_NAME(arena_dump_msgs), false), new BoolGameOption(SIMPLE_NAME(arena_dump_msgs_all), false), new BoolGameOption(SIMPLE_NAME(arena_list_eq), false), new BoolGameOption(SIMPLE_NAME(default_manual_training), false), new BoolGameOption(SIMPLE_NAME(one_SDL_sound_channel), false), new BoolGameOption(SIMPLE_NAME(sounds_on), true), new BoolGameOption(SIMPLE_NAME(launcher_autoquiver), true), new ColourGameOption(SIMPLE_NAME(tc_reachable), BLUE), new ColourGameOption(SIMPLE_NAME(tc_excluded), LIGHTMAGENTA), new ColourGameOption(SIMPLE_NAME(tc_exclude_circle), RED), new ColourGameOption(SIMPLE_NAME(tc_forbidden), LIGHTCYAN), new ColourGameOption(SIMPLE_NAME(tc_dangerous), CYAN), new ColourGameOption(SIMPLE_NAME(tc_disconnected), DARKGREY), // [ds] Default to jazzy colours. new ColourGameOption(SIMPLE_NAME(detected_item_colour), GREEN), new ColourGameOption(SIMPLE_NAME(detected_monster_colour), LIGHTRED), new ColourGameOption(SIMPLE_NAME(remembered_monster_colour), DARKGREY), new ColourGameOption(SIMPLE_NAME(status_caption_colour), BROWN), new ColourGameOption(SIMPLE_NAME(background_colour), BLACK), new ColourGameOption(SIMPLE_NAME(foreground_colour), LIGHTGREY), new CursesGameOption(SIMPLE_NAME(friend_brand), CHATTR_HILITE | (GREEN << 8)), new CursesGameOption(SIMPLE_NAME(neutral_brand), CHATTR_HILITE | (LIGHTGREY << 8)), new CursesGameOption(SIMPLE_NAME(stab_brand), CHATTR_HILITE | (BLUE << 8)), new CursesGameOption(SIMPLE_NAME(may_stab_brand), CHATTR_HILITE | (YELLOW << 8)), new CursesGameOption(SIMPLE_NAME(feature_item_brand), CHATTR_REVERSE), new CursesGameOption(SIMPLE_NAME(trap_item_brand), CHATTR_REVERSE), new CursesGameOption(SIMPLE_NAME(heap_brand), CHATTR_REVERSE), new IntGameOption(SIMPLE_NAME(note_hp_percent), 5, 0, 100), new IntGameOption(SIMPLE_NAME(hp_warning), 30, 0, 100), new IntGameOption(magic_point_warning, {"mp_warning"}, 0, 0, 100), new IntGameOption(SIMPLE_NAME(autofight_warning), 0, 0, 1000), // These need to be odd, hence allow +1. new IntGameOption(SIMPLE_NAME(view_max_width), max(VIEW_BASE_WIDTH, VIEW_MIN_WIDTH), VIEW_MIN_WIDTH, GXM + 1), new IntGameOption(SIMPLE_NAME(view_max_height), max(21, VIEW_MIN_HEIGHT), VIEW_MIN_HEIGHT, GYM + 1), new IntGameOption(SIMPLE_NAME(mlist_min_height), 4, 0), new IntGameOption(SIMPLE_NAME(msg_min_height), max(7, MSG_MIN_HEIGHT), MSG_MIN_HEIGHT), new IntGameOption(SIMPLE_NAME(msg_max_height), max(10, MSG_MIN_HEIGHT), MSG_MIN_HEIGHT), new IntGameOption(SIMPLE_NAME(msg_webtiles_height), -1), new IntGameOption(SIMPLE_NAME(rest_wait_percent), 100, 0, 100), new IntGameOption(SIMPLE_NAME(pickup_menu_limit), 1), new IntGameOption(SIMPLE_NAME(view_delay), DEFAULT_VIEW_DELAY, 0), new IntGameOption(SIMPLE_NAME(fail_severity_to_confirm), 3, -1, 5), new IntGameOption(SIMPLE_NAME(fail_severity_to_quiver), 3, -1, 5), new IntGameOption(SIMPLE_NAME(travel_delay), USING_DGL ? -1 : 20, -1, 2000), new IntGameOption(SIMPLE_NAME(rest_delay), USING_DGL ? -1 : 0, -1, 2000), new IntGameOption(SIMPLE_NAME(explore_delay), -1, -1, 2000), new IntGameOption(SIMPLE_NAME(explore_item_greed), 10, -1000, 1000), new IntGameOption(SIMPLE_NAME(explore_wall_bias), 0, 0, 1000), new IntGameOption(SIMPLE_NAME(scroll_margin_x), 2, 0), new IntGameOption(SIMPLE_NAME(scroll_margin_y), 2, 0), new IntGameOption(SIMPLE_NAME(item_stack_summary_minimum), 4), new IntGameOption(SIMPLE_NAME(level_map_cursor_step), 7, 1, 50), new IntGameOption(SIMPLE_NAME(dump_item_origin_price), -1, -1), new IntGameOption(SIMPLE_NAME(dump_message_count), 40), new ListGameOption<text_pattern>(SIMPLE_NAME(confirm_action)), new ListGameOption<text_pattern>(SIMPLE_NAME(drop_filter)), new ListGameOption<text_pattern>(SIMPLE_NAME(note_monsters)), new ListGameOption<text_pattern>(SIMPLE_NAME(note_messages)), new ListGameOption<text_pattern>(SIMPLE_NAME(note_items)), new ListGameOption<text_pattern>(SIMPLE_NAME(auto_exclude)), new ListGameOption<text_pattern>(SIMPLE_NAME(explore_stop_pickup_ignore)), new ColourThresholdOption(hp_colour, {"hp_colour", "hp_color"}, "50:yellow, 25:red", _first_greater), new ColourThresholdOption(mp_colour, {"mp_colour", "mp_color"}, "50:yellow, 25:red", _first_greater), new ColourThresholdOption(stat_colour, {"stat_colour", "stat_color"}, "3:red", _first_less), new StringGameOption(SIMPLE_NAME(sound_file_path), ""), new MultipleChoiceGameOption<travel_open_doors_type>( SIMPLE_NAME(travel_open_doors), travel_open_doors_type::open, {{"avoid", travel_open_doors_type::avoid}, {"approach", travel_open_doors_type::approach}, {"open", travel_open_doors_type::open}, {"false", travel_open_doors_type::_false}, {"true", travel_open_doors_type::_true}}), #ifdef DGL_SIMPLE_MESSAGING new BoolGameOption(SIMPLE_NAME(messaging), false), #endif #ifndef DGAMELAUNCH new BoolGameOption(SIMPLE_NAME(name_bypasses_menu), true), new BoolGameOption(SIMPLE_NAME(restart_after_save), true), new BoolGameOption(SIMPLE_NAME(newgame_after_quit), false), new StringGameOption(SIMPLE_NAME(map_file_name), ""), new StringGameOption(SIMPLE_NAME(morgue_dir), _get_save_path("morgue/")), #endif #ifdef USE_TILE new BoolGameOption(SIMPLE_NAME(tile_skip_title), false), new BoolGameOption(SIMPLE_NAME(tile_menu_icons), true), new BoolGameOption(SIMPLE_NAME(tile_filter_scaling), false), new BoolGameOption(SIMPLE_NAME(tile_force_overlay), false), new TileColGameOption(SIMPLE_NAME(tile_overlay_col), "#646464"), new IntGameOption(SIMPLE_NAME(tile_overlay_alpha_percent), 40, 0, 100), new BoolGameOption(SIMPLE_NAME(tile_show_minihealthbar), true), new BoolGameOption(SIMPLE_NAME(tile_show_minimagicbar), true), new BoolGameOption(SIMPLE_NAME(tile_show_demon_tier), false), new StringGameOption(SIMPLE_NAME(tile_show_threat_levels), ""), new StringGameOption(SIMPLE_NAME(tile_show_items), "!?/=([)}:|"), // disabled by default due to performance issues new BoolGameOption(SIMPLE_NAME(tile_water_anim), !USING_WEB_TILES), new BoolGameOption(SIMPLE_NAME(tile_misc_anim), true), new IntGameOption(SIMPLE_NAME(tile_font_crt_size), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_font_msg_size), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_font_stat_size), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_font_tip_size), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_font_lbl_size), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_cell_pixels), 32, 1, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_map_pixels), 0, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_tooltip_ms), 500, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_update_rate), 1000, 50, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_runrest_rate), 100, 0, INT_MAX), // minimap colours new TileColGameOption(SIMPLE_NAME(tile_branchstairs_col), "#ff7788"), new TileColGameOption(SIMPLE_NAME(tile_deep_water_col), "#001122"), new TileColGameOption(SIMPLE_NAME(tile_door_col), "#775544"), new TileColGameOption(SIMPLE_NAME(tile_downstairs_col), "#ff00ff"), new TileColGameOption(SIMPLE_NAME(tile_excl_centre_col), "#552266"), new TileColGameOption(SIMPLE_NAME(tile_excluded_col), "#552266"), new TileColGameOption(SIMPLE_NAME(tile_explore_horizon_col), "#6B301B"), new TileColGameOption(SIMPLE_NAME(tile_feature_col), "#997700"), new TileColGameOption(SIMPLE_NAME(tile_floor_col), "#333333"), new TileColGameOption(SIMPLE_NAME(tile_item_col), "#005544"), new TileColGameOption(SIMPLE_NAME(tile_lava_col), "#552211"), new TileColGameOption(SIMPLE_NAME(tile_mapped_floor_col), "#222266"), new TileColGameOption(SIMPLE_NAME(tile_mapped_wall_col), "#444499"), new TileColGameOption(SIMPLE_NAME(tile_monster_col), "#660000"), new TileColGameOption(SIMPLE_NAME(tile_plant_col), "#446633"), new TileColGameOption(SIMPLE_NAME(tile_player_col), "white"), new TileColGameOption(SIMPLE_NAME(tile_portal_col), "#ffdd00"), new TileColGameOption(SIMPLE_NAME(tile_trap_col), "#aa6644"), new TileColGameOption(SIMPLE_NAME(tile_unseen_col), "black"), new TileColGameOption(SIMPLE_NAME(tile_upstairs_col), "cyan"), new TileColGameOption(SIMPLE_NAME(tile_transporter_col), "#0000ff"), new TileColGameOption(SIMPLE_NAME(tile_transporter_landing_col), "#5200aa"), new TileColGameOption(SIMPLE_NAME(tile_wall_col), "#666666"), new TileColGameOption(SIMPLE_NAME(tile_water_col), "#114455"), new TileColGameOption(SIMPLE_NAME(tile_window_col), "#558855"), new ListGameOption<string>(SIMPLE_NAME(tile_layout_priority), #ifdef TOUCH_UI split_string(",", "minimap, command, inventory, " "command2, spell, ability, monster")), #else split_string(",", "minimap, inventory, command, " "spell, ability, monster")), #endif #endif #ifdef USE_TILE_LOCAL new IntGameOption(SIMPLE_NAME(game_scale), 1, 1, 8), new IntGameOption(SIMPLE_NAME(tile_key_repeat_delay), 200, 0, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_window_width), -90, INT_MIN, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_window_height), -90, INT_MIN, INT_MAX), new IntGameOption(SIMPLE_NAME(tile_window_ratio), 1618, INT_MIN, INT_MAX), new StringGameOption(SIMPLE_NAME(tile_font_crt_file), MONOSPACED_FONT), new StringGameOption(SIMPLE_NAME(tile_font_msg_file), MONOSPACED_FONT), new StringGameOption(SIMPLE_NAME(tile_font_stat_file), MONOSPACED_FONT), new StringGameOption(SIMPLE_NAME(tile_font_tip_file), MONOSPACED_FONT), new StringGameOption(SIMPLE_NAME(tile_font_lbl_file), PROPORTIONAL_FONT), new BoolGameOption(SIMPLE_NAME(tile_single_column_menus), true), new IntGameOption(SIMPLE_NAME(tile_number_ratio_pixels), 32, 0, INT_MAX), #endif #ifdef USE_TILE_WEB new BoolGameOption(SIMPLE_NAME(tile_realtime_anim), false), new BoolGameOption(SIMPLE_NAME(tile_level_map_hide_messages), true), new BoolGameOption(SIMPLE_NAME(tile_level_map_hide_sidebar), false), new BoolGameOption(SIMPLE_NAME(tile_web_mouse_control), true), new StringGameOption(SIMPLE_NAME(tile_font_crt_family), "monospace"), new StringGameOption(SIMPLE_NAME(tile_font_msg_family), "monospace"), new StringGameOption(SIMPLE_NAME(tile_font_stat_family), "monospace"), new StringGameOption(SIMPLE_NAME(tile_font_lbl_family), "monospace"), new StringGameOption(SIMPLE_NAME(glyph_mode_font), "monospace"), new IntGameOption(SIMPLE_NAME(glyph_mode_font_size), 24, 8, 144), #endif #ifdef USE_FT new
c++
code
19,999
3,592
//============================================================================ // // SSSS tt lll lll // SS SS tt ll ll // SS tttttt eeee ll ll aaaa // SSSS tt ee ee ll ll aa // SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator" // SS SS tt ee ll ll aa aa // SSSS ttt eeeee llll llll aaaaa // // Copyright (c) 1995-1998 by Bradford W. Mott // // See the file "license" for information on usage and redistribution of // this file, and for a DISCLAIMER OF ALL WARRANTIES. // // $Id: Keyboard.cxx,v 1.1.1.1 2001/12/27 19:54:22 bwmott Exp $ //============================================================================ #include "Event.hxx" #include "Keyboard.hxx" // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Keyboard::Keyboard(Jack jack, const Event& event) : Controller(jack, event), myPinState(0) { } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Keyboard::~Keyboard() { } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Keyboard::read(DigitalPin pin) { if(pin == Six) { if((myPinState & 0x01) == 0) { return (myJack == Left) ? (myEvent.get(Event::KeyboardZero3) == 0) : (myEvent.get(Event::KeyboardOne3) == 0); } else if((myPinState & 0x02) == 0) { return (myJack == Left) ? (myEvent.get(Event::KeyboardZero6) == 0) : (myEvent.get(Event::KeyboardOne6) == 0); } else if((myPinState & 0x04) == 0) { return (myJack == Left) ? (myEvent.get(Event::KeyboardZero9) == 0) : (myEvent.get(Event::KeyboardOne9) == 0); } else if((myPinState & 0x08) == 0) { return (myJack == Left) ? (myEvent.get(Event::KeyboardZeroPound) == 0) : (myEvent.get(Event::KeyboardOnePound) == 0); } } return true; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Int32 Keyboard::read(AnalogPin pin) { if(pin == Nine) { if((myPinState & 0x01) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero1) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne1) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x02) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero4) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne4) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x04) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero7) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne7) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x08) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZeroStar) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOneStar) != 0) ? maximumResistance : minimumResistance; } } } else { if((myPinState & 0x01) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero2) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne2) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x02) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero5) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne5) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x04) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero8) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne8) != 0) ? maximumResistance : minimumResistance; } } else if((myPinState & 0x08) == 0) { if(myJack == Left) { return (myEvent.get(Event::KeyboardZero0) != 0) ? maximumResistance : minimumResistance; } else { return (myEvent.get(Event::KeyboardOne0) != 0) ? maximumResistance : minimumResistance; } } } return maximumResistance; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Keyboard::write(DigitalPin pin, bool value) { // Change the pin state based on value switch(pin) { case One: myPinState = (myPinState & 0x0E) | (value ? 0x01 : 0x00); break; case Two: myPinState = (myPinState & 0x0D) | (value ? 0x02 : 0x00); break; case Three: myPinState = (myPinState & 0x0B) | (value ? 0x04 : 0x00); break; case Four: myPinState = (myPinState & 0x07) | (value ? 0x08 : 0x00); break; default: break; } }
c++
code
5,419
1,251
// AUTO GENERATED by vnxcppcodegen #include <mmx/contract/package.hxx> #include <mmx/contract/MultiSig_rem_owner.hxx> #include <mmx/addr_t.hpp> #include <mmx/contract/MultiSig_rem_owner_return.hxx> #include <vnx/Value.h> #include <vnx/vnx.h> namespace mmx { namespace contract { const vnx::Hash64 MultiSig_rem_owner::VNX_TYPE_HASH(0x76c14727e0beab3cull); const vnx::Hash64 MultiSig_rem_owner::VNX_CODE_HASH(0x71180911183d85ccull); vnx::Hash64 MultiSig_rem_owner::get_type_hash() const { return VNX_TYPE_HASH; } std::string MultiSig_rem_owner::get_type_name() const { return "mmx.contract.MultiSig.rem_owner"; } const vnx::TypeCode* MultiSig_rem_owner::get_type_code() const { return mmx::contract::vnx_native_type_code_MultiSig_rem_owner; } std::shared_ptr<MultiSig_rem_owner> MultiSig_rem_owner::create() { return std::make_shared<MultiSig_rem_owner>(); } std::shared_ptr<vnx::Value> MultiSig_rem_owner::clone() const { return std::make_shared<MultiSig_rem_owner>(*this); } void MultiSig_rem_owner::read(vnx::TypeInput& _in, const vnx::TypeCode* _type_code, const uint16_t* _code) { vnx::read(_in, *this, _type_code, _code); } void MultiSig_rem_owner::write(vnx::TypeOutput& _out, const vnx::TypeCode* _type_code, const uint16_t* _code) const { vnx::write(_out, *this, _type_code, _code); } void MultiSig_rem_owner::accept(vnx::Visitor& _visitor) const { const vnx::TypeCode* _type_code = mmx::contract::vnx_native_type_code_MultiSig_rem_owner; _visitor.type_begin(*_type_code); _visitor.type_field(_type_code->fields[0], 0); vnx::accept(_visitor, address); _visitor.type_end(*_type_code); } void MultiSig_rem_owner::write(std::ostream& _out) const { _out << "{\"__type\": \"mmx.contract.MultiSig.rem_owner\""; _out << ", \"address\": "; vnx::write(_out, address); _out << "}"; } void MultiSig_rem_owner::read(std::istream& _in) { if(auto _json = vnx::read_json(_in)) { from_object(_json->to_object()); } } vnx::Object MultiSig_rem_owner::to_object() const { vnx::Object _object; _object["__type"] = "mmx.contract.MultiSig.rem_owner"; _object["address"] = address; return _object; } void MultiSig_rem_owner::from_object(const vnx::Object& _object) { for(const auto& _entry : _object.field) { if(_entry.first == "address") { _entry.second.to(address); } } } vnx::Variant MultiSig_rem_owner::get_field(const std::string& _name) const { if(_name == "address") { return vnx::Variant(address); } return vnx::Variant(); } void MultiSig_rem_owner::set_field(const std::string& _name, const vnx::Variant& _value) { if(_name == "address") { _value.to(address); } } /// \private std::ostream& operator<<(std::ostream& _out, const MultiSig_rem_owner& _value) { _value.write(_out); return _out; } /// \private std::istream& operator>>(std::istream& _in, MultiSig_rem_owner& _value) { _value.read(_in); return _in; } const vnx::TypeCode* MultiSig_rem_owner::static_get_type_code() { const vnx::TypeCode* type_code = vnx::get_type_code(VNX_TYPE_HASH); if(!type_code) { type_code = vnx::register_type_code(static_create_type_code()); } return type_code; } std::shared_ptr<vnx::TypeCode> MultiSig_rem_owner::static_create_type_code() { auto type_code = std::make_shared<vnx::TypeCode>(); type_code->name = "mmx.contract.MultiSig.rem_owner"; type_code->type_hash = vnx::Hash64(0x76c14727e0beab3cull); type_code->code_hash = vnx::Hash64(0x71180911183d85ccull); type_code->is_native = true; type_code->is_class = true; type_code->is_method = true; type_code->native_size = sizeof(::mmx::contract::MultiSig_rem_owner); type_code->create_value = []() -> std::shared_ptr<vnx::Value> { return std::make_shared<MultiSig_rem_owner>(); }; type_code->return_type = ::mmx::contract::MultiSig_rem_owner_return::static_get_type_code(); type_code->fields.resize(1); { auto& field = type_code->fields[0]; field.is_extended = true; field.name = "address"; field.code = {11, 32, 1}; } type_code->build(); return type_code; } } // namespace mmx } // namespace contract namespace vnx { void read(TypeInput& in, ::mmx::contract::MultiSig_rem_owner& value, const TypeCode* type_code, const uint16_t* code) { if(code) { switch(code[0]) { case CODE_OBJECT: case CODE_ALT_OBJECT: { Object tmp; vnx::read(in, tmp, type_code, code); value.from_object(tmp); return; } case CODE_DYNAMIC: case CODE_ALT_DYNAMIC: vnx::read_dynamic(in, value); return; } } if(!type_code) { vnx::skip(in, type_code, code); return; } if(code) { switch(code[0]) { case CODE_STRUCT: type_code = type_code->depends[code[1]]; break; case CODE_ALT_STRUCT: type_code = type_code->depends[vnx::flip_bytes(code[1])]; break; default: { vnx::skip(in, type_code, code); return; } } } in.read(type_code->total_field_size); if(type_code->is_matched) { } for(const auto* _field : type_code->ext_fields) { switch(_field->native_index) { case 0: vnx::read(in, value.address, type_code, _field->code.data()); break; default: vnx::skip(in, type_code, _field->code.data()); } } } void write(TypeOutput& out, const ::mmx::contract::MultiSig_rem_owner& value, const TypeCode* type_code, const uint16_t* code) { if(code && code[0] == CODE_OBJECT) { vnx::write(out, value.to_object(), nullptr, code); return; } if(!type_code || (code && code[0] == CODE_ANY)) { type_code = mmx::contract::vnx_native_type_code_MultiSig_rem_owner; out.write_type_code(type_code); vnx::write_class_header<::mmx::contract::MultiSig_rem_owner>(out); } else if(code && code[0] == CODE_STRUCT) { type_code = type_code->depends[code[1]]; } vnx::write(out, value.address, type_code, type_code->fields[0].code.data()); } void read(std::istream& in, ::mmx::contract::MultiSig_rem_owner& value) { value.read(in); } void write(std::ostream& out, const ::mmx::contract::MultiSig_rem_owner& value) { value.write(out); } void accept(Visitor& visitor, const ::mmx::contract::MultiSig_rem_owner& value) { value.accept(visitor); } } // vnx
c++
code
6,035
1,531
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/cpu/simple_orc_jit.h" #include <dlfcn.h> #include <stdint.h> #include <algorithm> #include <list> #include <utility> #include "external/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h" #include "external/llvm/include/llvm/ExecutionEngine/SectionMemoryManager.h" #include "external/llvm/include/llvm/IR/Mangler.h" #include "external/llvm/include/llvm/Support/CodeGen.h" #include "external/llvm/include/llvm/Support/Host.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/cpu/cpu_runtime.h" #include "tensorflow/compiler/xla/service/cpu/cpu_runtime_avx.h" #include "tensorflow/compiler/xla/service/cpu/cpu_runtime_sse4_1.h" #include "tensorflow/compiler/xla/service/cpu/runtime_conv2d.h" #include "tensorflow/compiler/xla/service/cpu/runtime_matmul.h" #include "tensorflow/compiler/xla/service/cpu/runtime_single_threaded_conv2d.h" #include "tensorflow/compiler/xla/service/cpu/runtime_single_threaded_matmul.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/platform/logging.h" namespace xla { namespace cpu { namespace { // Converts a symbol 'name' into the form expected by dlsym(). std::string CanonicalizeSymbol(const std::string &name) { #if defined(__APPLE__) // On Mac OS X, dlsym() expects names not to be prefixed with a leading // underscore. if (!name.empty() && name.front() == '_') { return name.substr(1); } #endif return name; } // A simple SymbolResolver that delegates to the host dynamic linker. struct SimpleResolver : public llvm::JITSymbolResolver { llvm::JITSymbol findSymbol(const std::string &name) override { void *func_addr = nullptr; std::string canonical_name = CanonicalizeSymbol(name); if (canonical_name == runtime::kEigenMatmulF32SymbolName) { func_addr = reinterpret_cast<void *>(__xla_cpu_runtime_EigenMatMulF32); } else if (canonical_name == runtime::kEigenSingleThreadedMatmulF32SymbolName) { func_addr = reinterpret_cast<void *>( __xla_cpu_runtime_EigenSingleThreadedMatMulF32); } else if (canonical_name == runtime::kEigenConvF32SymbolName) { func_addr = reinterpret_cast<void *>(__xla_cpu_runtime_EigenConvF32); } else if (canonical_name == runtime::kEigenSingleThreadedConvF32SymbolName) { func_addr = reinterpret_cast<void *>( __xla_cpu_runtime_EigenSingleThreadedConvF32); } else if (canonical_name == runtime::kAcquireInfeedBufferForDequeueSymbolName) { func_addr = reinterpret_cast<void *>( __xla_cpu_runtime_AcquireInfeedBufferForDequeue); } else if (canonical_name == runtime::kReleaseInfeedBufferAfterDequeueSymbolName) { func_addr = reinterpret_cast<void *>( __xla_cpu_runtime_ReleaseInfeedBufferAfterDequeue); } else if (canonical_name == runtime::kExpV4F32) { func_addr = reinterpret_cast<void *>(runtime::ExpV4F32); } else if (canonical_name == runtime::kExpV8F32) { func_addr = reinterpret_cast<void *>(runtime::ExpV8F32); } else if (canonical_name == runtime::kLogV4F32) { func_addr = reinterpret_cast<void *>(runtime::LogV4F32); } else if (canonical_name == runtime::kLogV8F32) { func_addr = reinterpret_cast<void *>(runtime::LogV8F32); } else if (canonical_name == runtime::kTanhV4F32) { func_addr = reinterpret_cast<void *>(runtime::TanhV4F32); } else if (canonical_name == runtime::kTanhV8F32) { func_addr = reinterpret_cast<void *>(runtime::TanhV8F32); } else { func_addr = dlsym(RTLD_DEFAULT, canonical_name.c_str()); } if (func_addr == nullptr) { return nullptr; } llvm::JITEvaluatedSymbol symbol_info(reinterpret_cast<uint64_t>(func_addr), llvm::JITSymbolFlags::None); return symbol_info; } llvm::JITSymbol findSymbolInLogicalDylib(const std::string &name) override { return nullptr; } }; llvm::SmallVector<std::string, 0> DetectMachineAttributes() { llvm::SmallVector<std::string, 0> result; llvm::StringMap<bool> host_features; if (llvm::sys::getHostCPUFeatures(host_features)) { for (auto &feature : host_features) { if (feature.second) { llvm::StringRef feature_name = feature.first(); // Skip avx512 for now, it isn't quite ready in LLVM. if (feature_name.startswith("avx512")) { continue; } result.push_back(feature_name); } } } return result; } llvm::StringRef GetHostCpuName() { auto cpu_name = llvm::sys::getHostCPUName(); // Skip avx512 for now, it isn't quite ready in LLVM. cpu_name.consume_back("-avx512"); return cpu_name; } CompilerFunctor::VectorIntrinsics GetAvailableIntrinsics() { CompilerFunctor::VectorIntrinsics intrinsics; intrinsics.sse_intrinsics = (&runtime::ExpV4F32 != nullptr); intrinsics.avx_intrinsics = (&runtime::ExpV8F32 != nullptr); return intrinsics; } } // namespace SimpleOrcJIT::SimpleOrcJIT(const llvm::TargetOptions &target_options, llvm::CodeGenOpt::Level opt_level, OptimizationCallback pre_optimization_callback, OptimizationCallback post_optimization_callback) : target_machine_( CHECK_NOTNULL(llvm::EngineBuilder() .setTargetOptions(target_options) .setOptLevel(opt_level) .selectTarget( /*TargetTriple=*/llvm::Triple(), /*MArch=*/"", /*MCPU=*/GetHostCpuName(), /*MAttrs=*/DetectMachineAttributes()))), disassembler_(*target_machine_), data_layout_(target_machine_->createDataLayout()), compile_layer_(object_layer_, CompilerFunctor(target_machine_.get(), &disassembler_, opt_level, GetAvailableIntrinsics(), std::move(pre_optimization_callback), std::move(post_optimization_callback))) { VLOG(1) << "CPU target: " << target_machine_->getTargetCPU().str() << " features: " << target_machine_->getTargetFeatureString().str(); } SimpleOrcJIT::ModuleHandleT SimpleOrcJIT::AddModule( std::unique_ptr<llvm::Module> module) { auto handle = compile_layer_.addModule( std::move(module), MakeUnique<llvm::SectionMemoryManager>(), MakeUnique<SimpleResolver>()); module_handles_.push_back(handle); return handle; } void SimpleOrcJIT::RemoveModule(SimpleOrcJIT::ModuleHandleT handle) { module_handles_.erase( std::remove(module_handles_.begin(), module_handles_.end(), handle), module_handles_.end()); compile_layer_.removeModule(handle); } llvm::JITSymbol SimpleOrcJIT::FindSymbol(const std::string &name) { std::string mangled_name; { llvm::raw_string_ostream mangled_name_stream(mangled_name); llvm::Mangler::getNameWithPrefix(mangled_name_stream, name, data_layout_); } // Resolve symbol from last module to first, allowing later redefinitions of // symbols shadow earlier ones. for (auto &handle : llvm::make_range(module_handles_.rbegin(), module_handles_.rend())) { if (auto symbol = compile_layer_.findSymbolIn(handle, mangled_name, /*ExportedSymbolsOnly=*/true)) { return symbol; } } return nullptr; } } // namespace cpu } // namespace xla
c++
code
8,240
1,417
#include "../../head.h" class Solution { public: int stoneGameII(std::vector<int> piles) { // plagiarizing from https://leetcode.com/problems/stone-game-ii/discuss/345354/Java-DP-with-memorization-easy-to-understand(with-explanation) // and https://leetcode.com/problems/stone-game-ii/discuss/345230/Python-DP-Solution if (piles.empty()) { return 0; } if (1 == piles.size()) { return piles.back(); } for (int index = piles.size() - 2; index >= 0; index--) { piles[index] += piles[index + 1]; // from end to begin to get sum; } std::vector<std::vector<int>> memo(piles.size(), std::vector<int>(M, 0)); return dpHelper(piles, memo, 0, 1); } private: int dpHelper(std::vector<int> const & piles, std::vector<std::vector<int>> & memo, int index, int m) { int const dM = 2 * m; if (dM + index >= piles.size()) { return piles[index]; // all belong to the step } if (0 != memo[index][m]) { return memo[index][m]; } int res = INT_MAX; for (int step = 1; step <= dM; step++) { res = std::min(res, dpHelper(piles, memo, index + step, std::max(m, step))); } return memo[index][m] = piles[index] - res; } private: static int const M = 32; // because piles.length() <= 100; when M = 32, // there is already getting at least 32 elements with 4 step, and the next max step can be 2 * M = 64. which is the fifth step; // 64 + 32 = 96, the six step will can be 64 * 2 = 128. lee will take all of them left };
c++
code
1,646
417
//--- // File: ossimNitfRsmidaTag.cpp //--- #include <ossim/support_data/ossimNitfRsmidaTag.h> #include <iomanip> #include <iostream> using namespace std; RTTI_DEF1(ossimNitfRsmidaTag, "ossimNitfRsmidaTag", ossimNitfRegisteredTag); ossimNitfRsmidaTag::ossimNitfRsmidaTag() : ossimNitfRegisteredTag(std::string("RSMIDA"), CEL_SIZE), m_iid(), m_edition(), m_isid(), m_sid(), m_stid(), m_year(), m_month(), m_day(), m_hour(), m_minute(), m_second(), m_nrg(), m_ncg(), m_trg(), m_tcg(), m_grndd(), m_xuor(), m_yuor(), m_zuor(), m_xuxr(), m_xuyr(), m_xuzr(), m_yuxr(), m_yuyr(), m_yuzr(), m_zuxr(), m_zuyr(), m_zuzr(), m_v1x(), m_v1y(), m_v1z(), m_v2x(), m_v2y(), m_v2z(), m_v3x(), m_v3y(), m_v3z(), m_v4x(), m_v4y(), m_v4z(), m_v5x(), m_v5y(), m_v5z(), m_v6x(), m_v6y(), m_v6z(), m_v7x(), m_v7y(), m_v7z(), m_v8x(), m_v8y(), m_v8z(), m_grpx(), m_grpy(), m_grpz(), m_fullr(), m_fullc(), m_minr(), m_maxr(), m_minc(), m_maxc(), m_ie0(), m_ier(), m_iec(), m_ierr(), m_ierc(), m_iecc(), m_ia0(), m_iar(), m_iac(), m_iarr(), m_iarc(), m_iacc(), m_spx(), m_svx(), m_sax(), m_spy(), m_svy(), m_say(), m_spz(), m_svz(), m_saz() { clearFields(); } void ossimNitfRsmidaTag::parseStream(std::istream& in) { in.read(m_iid, IID_SIZE); in.read(m_edition, EDITION_SIZE); in.read(m_isid, ISID_SIZE); in.read(m_sid, SID_SIZE); in.read(m_stid, STID_SIZE); in.read(m_year, YEAR_SIZE); in.read(m_month, MONTH_SIZE); in.read(m_day, DAY_SIZE); in.read(m_hour, HOUR_SIZE); in.read(m_minute, MINUTE_SIZE); in.read(m_second, SECOND_SIZE); in.read(m_nrg, NRG_SIZE); in.read(m_ncg, NCG_SIZE); in.read(m_trg, FLOAT21_SIZE); in.read(m_tcg, FLOAT21_SIZE); in.read(m_grndd, GRNDD_SIZE); in.read(m_xuor, FLOAT21_SIZE); in.read(m_yuor, FLOAT21_SIZE); in.read(m_zuor, FLOAT21_SIZE); in.read(m_xuxr, FLOAT21_SIZE); in.read(m_xuyr, FLOAT21_SIZE); in.read(m_xuzr, FLOAT21_SIZE); in.read(m_yuxr, FLOAT21_SIZE); in.read(m_yuyr, FLOAT21_SIZE); in.read(m_yuzr, FLOAT21_SIZE); in.read(m_zuxr, FLOAT21_SIZE); in.read(m_zuyr, FLOAT21_SIZE); in.read(m_zuzr, FLOAT21_SIZE); in.read(m_v1x, FLOAT21_SIZE); in.read(m_v1y, FLOAT21_SIZE); in.read(m_v1z, FLOAT21_SIZE); in.read(m_v2x, FLOAT21_SIZE); in.read(m_v2y, FLOAT21_SIZE); in.read(m_v2z, FLOAT21_SIZE); in.read(m_v3x, FLOAT21_SIZE); in.read(m_v3y, FLOAT21_SIZE); in.read(m_v3z, FLOAT21_SIZE); in.read(m_v4x, FLOAT21_SIZE); in.read(m_v4y, FLOAT21_SIZE); in.read(m_v4z, FLOAT21_SIZE); in.read(m_v5x, FLOAT21_SIZE); in.read(m_v5y, FLOAT21_SIZE); in.read(m_v5z, FLOAT21_SIZE); in.read(m_v6x, FLOAT21_SIZE); in.read(m_v6y, FLOAT21_SIZE); in.read(m_v6z, FLOAT21_SIZE); in.read(m_v7x, FLOAT21_SIZE); in.read(m_v7y, FLOAT21_SIZE); in.read(m_v7z, FLOAT21_SIZE); in.read(m_v8x, FLOAT21_SIZE); in.read(m_v8y, FLOAT21_SIZE); in.read(m_v8z, FLOAT21_SIZE); in.read(m_grpx, FLOAT21_SIZE); in.read(m_grpy, FLOAT21_SIZE); in.read(m_grpz, FLOAT21_SIZE); in.read(m_fullr, FULL_SIZE); in.read(m_fullc, FULL_SIZE); in.read(m_minr, MIN_SIZE); in.read(m_maxr, MAX_SIZE); in.read(m_minc, MIN_SIZE); in.read(m_maxc, MAX_SIZE); in.read(m_ie0, FLOAT21_SIZE); in.read(m_ier, FLOAT21_SIZE); in.read(m_iec, FLOAT21_SIZE); in.read(m_ierr, FLOAT21_SIZE); in.read(m_ierc, FLOAT21_SIZE); in.read(m_iecc, FLOAT21_SIZE); in.read(m_ia0, FLOAT21_SIZE); in.read(m_iar, FLOAT21_SIZE); in.read(m_iac, FLOAT21_SIZE); in.read(m_iarr, FLOAT21_SIZE); in.read(m_iarc, FLOAT21_SIZE); in.read(m_iacc, FLOAT21_SIZE); in.read(m_spx, FLOAT21_SIZE); in.read(m_svx, FLOAT21_SIZE); in.read(m_sax, FLOAT21_SIZE); in.read(m_spy, FLOAT21_SIZE); in.read(m_svy, FLOAT21_SIZE); in.read(m_say, FLOAT21_SIZE); in.read(m_spz, FLOAT21_SIZE); in.read(m_svz, FLOAT21_SIZE); in.read(m_saz, FLOAT21_SIZE); } void ossimNitfRsmidaTag::writeStream(std::ostream& out) { out.write(m_iid, IID_SIZE); out.write(m_edition, EDITION_SIZE); out.write(m_isid, ISID_SIZE); out.write(m_sid, SID_SIZE); out.write(m_stid, STID_SIZE); out.write(m_year, YEAR_SIZE); out.write(m_month, MONTH_SIZE); out.write(m_day, DAY_SIZE); out.write(m_hour, HOUR_SIZE); out.write(m_minute, MINUTE_SIZE); out.write(m_second, SECOND_SIZE); out.write(m_nrg, NRG_SIZE); out.write(m_ncg, NCG_SIZE); out.write(m_trg, FLOAT21_SIZE); out.write(m_tcg, FLOAT21_SIZE); out.write(m_grndd, GRNDD_SIZE); out.write(m_xuor, FLOAT21_SIZE); out.write(m_yuor, FLOAT21_SIZE); out.write(m_zuor, FLOAT21_SIZE); out.write(m_xuxr, FLOAT21_SIZE); out.write(m_xuyr, FLOAT21_SIZE); out.write(m_xuzr, FLOAT21_SIZE); out.write(m_yuxr, FLOAT21_SIZE); out.write(m_yuyr, FLOAT21_SIZE); out.write(m_yuzr, FLOAT21_SIZE); out.write(m_zuxr, FLOAT21_SIZE); out.write(m_zuyr, FLOAT21_SIZE); out.write(m_zuzr, FLOAT21_SIZE); out.write(m_v1x, FLOAT21_SIZE); out.write(m_v1y, FLOAT21_SIZE); out.write(m_v1z, FLOAT21_SIZE); out.write(m_v2x, FLOAT21_SIZE); out.write(m_v2y, FLOAT21_SIZE); out.write(m_v2z, FLOAT21_SIZE); out.write(m_v3x, FLOAT21_SIZE); out.write(m_v3y, FLOAT21_SIZE); out.write(m_v3z, FLOAT21_SIZE); out.write(m_v4x, FLOAT21_SIZE); out.write(m_v4y, FLOAT21_SIZE); out.write(m_v4z, FLOAT21_SIZE); out.write(m_v5x, FLOAT21_SIZE); out.write(m_v5y, FLOAT21_SIZE); out.write(m_v5z, FLOAT21_SIZE); out.write(m_v6x, FLOAT21_SIZE); out.write(m_v6y, FLOAT21_SIZE); out.write(m_v6z, FLOAT21_SIZE); out.write(m_v7x, FLOAT21_SIZE); out.write(m_v7y, FLOAT21_SIZE); out.write(m_v7z, FLOAT21_SIZE); out.write(m_v8x, FLOAT21_SIZE); out.write(m_v8y, FLOAT21_SIZE); out.write(m_v8z, FLOAT21_SIZE); out.write(m_grpx, FLOAT21_SIZE); out.write(m_grpy, FLOAT21_SIZE); out.write(m_grpz, FLOAT21_SIZE); out.write(m_fullr, FULL_SIZE); out.write(m_fullc, FULL_SIZE); out.write(m_minr, MIN_SIZE); out.write(m_maxr, MAX_SIZE); out.write(m_minc, MIN_SIZE); out.write(m_maxc, MAX_SIZE); out.write(m_ie0, FLOAT21_SIZE); out.write(m_ier, FLOAT21_SIZE); out.write(m_iec, FLOAT21_SIZE); out.write(m_ierr, FLOAT21_SIZE); out.write(m_ierc, FLOAT21_SIZE); out.write(m_iecc, FLOAT21_SIZE); out.write(m_ia0, FLOAT21_SIZE); out.write(m_iar, FLOAT21_SIZE); out.write(m_iac, FLOAT21_SIZE); out.write(m_iarr, FLOAT21_SIZE); out.write(m_iarc, FLOAT21_SIZE); out.write(m_iacc, FLOAT21_SIZE); out.write(m_spx, FLOAT21_SIZE); out.write(m_svx, FLOAT21_SIZE); out.write(m_sax, FLOAT21_SIZE); out.write(m_spy, FLOAT21_SIZE); out.write(m_svy, FLOAT21_SIZE); out.write(m_say, FLOAT21_SIZE); out.write(m_spz, FLOAT21_SIZE); out.write(m_svz, FLOAT21_SIZE); out.write(m_saz, FLOAT21_SIZE); } std::ostream& ossimNitfRsmidaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "IID:" << m_iid << "\n" << pfx << std::setw(24) << "EDITION:" << m_edition << "\n" << pfx << std::setw(24) << "ISID:" << m_isid << "\n" << pfx << std::setw(24) << "SID:" << m_sid << "\n" << pfx << std::setw(24) << "STID:" << m_stid << "\n" << pfx << std::setw(24) << "YEAR:" << m_year << "\n" << pfx << std::setw(24) << "MONTH:" << m_month << "\n" << pfx << std::setw(24) << "DAY:" << m_day << "\n" << pfx << std::setw(24) << "HOUR:" << m_hour << "\n" << pfx << std::setw(24) << "MINUTE:" << m_minute << "\n" << pfx << std::setw(24) << "SECOND:" << m_second << "\n" << pfx << std::setw(24) << "NRG:" << m_nrg << "\n" << pfx << std::setw(24) << "NCG:" << m_ncg << "\n" << pfx << std::setw(24) << "TRG:" << m_trg << "\n" << pfx << std::setw(24) << "TCG:" << m_tcg << "\n" << pfx << std::setw(24) << "GRNDD:" << m_grndd << "\n" << pfx << std::setw(24) << "XUOR:" << m_xuor << "\n" << pfx << std::setw(24) << "YUOR:" << m_yuor << "\n" << pfx << std::setw(24) << "ZUOR:" << m_zuor << "\n" << pfx << std::setw(24) << "XUXR:" << m_xuxr << "\n" << pfx << std::setw(24) << "XUYR:" << m_xuyr << "\n" << pfx << std::setw(24) << "XUZR:" << m_xuzr << "\n" << pfx << std::setw(24) << "YUXR:" << m_yuxr << "\n" << pfx << std::setw(24) << "YUYR:" << m_yuyr << "\n" << pfx << std::setw(24) << "YUZR:" << m_yuzr << "\n" << pfx << std::setw(24) << "ZUXR:" << m_zuxr << "\n" << pfx << std::setw(24) << "ZUYR:" << m_zuyr << "\n" << pfx << std::setw(24) << "ZUZR:" << m_zuzr << "\n" << pfx << std::setw(24) << "V1X:" << m_v1x << "\n" << pfx << std::setw(24) << "V1Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V1Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V2X:" << m_v1x << "\n" << pfx << std::setw(24) << "V2Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V2Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V3X:" << m_v1x << "\n" << pfx << std::setw(24) << "V3Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V3Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V4X:" << m_v1x << "\n" << pfx << std::setw(24) << "V4Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V4Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V5X:" << m_v1x << "\n" << pfx << std::setw(24) << "V5Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V5Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V6X:" << m_v1x << "\n" << pfx << std::setw(24) << "V6Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V6Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V7X:" << m_v1x << "\n" << pfx << std::setw(24) << "V7Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V7Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V8X:" << m_v1x << "\n" << pfx << std::setw(24) << "V8Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V8Z:" << m_v1x << "\n" << pfx << std::setw(24) << "GRPX:" << m_grpx << "\n" << pfx << std::setw(24) << "GRPY:" << m_grpy << "\n" << pfx << std::setw(24) << "GRPZ:" << m_grpz << "\n" << pfx << std::setw(24) << "FULLR:" << m_fullr << "\n" << pfx << std::setw(24) << "FULLC:" << m_fullc << "\n" << pfx << std::setw(24) << "MINR:" << m_minr << "\n" << pfx << std::setw(24) << "MAXR:" << m_maxr << "\n" << pfx << std::setw(24) << "MINC:" << m_minc << "\n" << pfx << std::setw(24) << "MAXC:" << m_maxc << "\n" << pfx << std::setw(24) << "IE0:" << m_ie0 << "\n" << pfx << std::setw(24) << "IER:" << m_ier << "\n" << pfx << std::setw(24) << "IEC:" << m_iec << "\n" << pfx << std::setw(24) << "IERR:" << m_ierr << "\n" << pfx << std::setw(24) << "IERC:" << m_ierc << "\n" << pfx << std::setw(24) << "IECC:" << m_iecc << "\n" << pfx << std::setw(24) << "IA0:" << m_ia0 << "\n" << pfx << std::setw(24) << "IAR:" << m_iar << "\n" << pfx << std::setw(24) << "IAC:" << m_iac << "\n" << pfx << std::setw(24) << "IARR:" << m_iarr << "\n" << pfx << std::setw(24) << "IARC:" << m_iarc << "\n" << pfx << std::setw(24) << "IACC:" << m_iacc << "\n" << pfx << std::setw(24) << "SPX:" << m_spx << "\n" << pfx << std::setw(24) << "SVX:" << m_svx << "\n" << pfx << std::setw(24) << "SAX:" << m_sax << "\n" << pfx << std::setw(24) << "SPY:" << m_spy << "\n" << pfx << std::setw(24) << "SVY:" << m_svy << "\n" << pfx << std::setw(24) << "SAY:" << m_say << "\n" << pfx << std::setw(24) << "SPZ:" << m_spz << "\n" << pfx << std::setw(24) << "SVZ:" << m_svz << "\n" << pfx << std::setw(24) << "SAZ:" << m_saz << "\n"; return out; } void ossimNitfRsmidaTag::clearFields() { memset(m_iid,' ', IID_SIZE); memset(m_edition, ' ', EDITION_SIZE); memset(m_isid, ' ', ISID_SIZE); memset(m_sid, ' ', SID_SIZE); memset(m_stid, ' ', STID_SIZE); memset(m_year, ' ', YEAR_SIZE); memset(m_month, ' ', MONTH_SIZE); memset(m_day, ' ', DAY_SIZE); memset(m_hour,' ', HOUR_SIZE); memset(m_minute, ' ', MINUTE_SIZE); memset(m_second, ' ', SECOND_SIZE); memset(m_nrg, ' ', NRG_SIZE); memset(m_ncg, ' ', NCG_SIZE); memset(m_trg, ' ', FLOAT21_SIZE); memset(m_tcg, ' ', FLOAT21_SIZE); memset(m_grndd, ' ', GRNDD_SIZE); memset(m_xuor, ' ', FLOAT21_SIZE); memset(m_yuor, ' ', FLOAT21_SIZE); memset(m_zuor, ' ', FLOAT21_SIZE); memset(m_xuxr, ' ', FLOAT21_SIZE); memset(m_xuyr, ' ', FLOAT21_SIZE); memset(m_xuzr, ' ', FLOAT21_SIZE); memset(m_yuxr, ' ', FLOAT21_SIZE); memset(m_yuyr, ' ', FLOAT21_SIZE); memset(m_yuzr, ' ', FLOAT21_SIZE); memset(m_zuxr, ' ', FLOAT21_SIZE); memset(m_zuyr, ' ', FLOAT21_SIZE); memset(m_zuzr, ' ', FLOAT21_SIZE); memset(m_v1x, ' ', FLOAT21_SIZE); memset(m_v1y, ' ', FLOAT21_SIZE); memset(m_v1z, ' ', FLOAT21_SIZE); memset(m_v2x, ' ', FLOAT21_SIZE); memset(m_v2y, ' ', FLOAT21_SIZE); memset(m_v2z, ' ', FLOAT21_SIZE); memset(m_v3x, ' ', FLOAT21_SIZE); memset(m_v3y, ' ', FLOAT21_SIZE); memset(m_v3z, ' ', FLOAT21_SIZE); memset(m_v4x, ' ', FLOAT21_SIZE); memset(m_v4y, ' ', FLOAT21_SIZE); memset(m_v4z, ' ', FLOAT21_SIZE); memset(m_v5x, ' ', FLOAT21_SIZE); memset(m_v5y, ' ', FLOAT21_SIZE); memset(m_v5z, ' ', FLOAT21_SIZE); memset(m_v6x, ' ', FLOAT21_SIZE); memset(m_v6y, ' ', FLOAT21_SIZE); memset(m_v6z, ' ', FLOAT21_SIZE); memset(m_v7x, ' ', FLOAT21_SIZE); memset(m_v7y, ' ', FLOAT21_SIZE); memset(m_v7z, ' ', FLOAT21_SIZE); memset(m_v8x, ' ', FLOAT21_SIZE); memset(m_v8y, ' ', FLOAT21_SIZE); memset(m_v8z, ' ', FLOAT21_SIZE); memset(m_grpx, ' ', FLOAT21_SIZE); memset(m_grpy, ' ', FLOAT21_SIZE); memset(m_grpz, ' ', FLOAT21_SIZE); memset(m_fullr, ' ', FULL_SIZE); memset(m_fullc, ' ', FULL_SIZE); memset(m_minr, ' ', MIN_SIZE); memset(m_maxr, ' ', MAX_SIZE); memset(m_minc, ' ', MIN_SIZE); memset(m_maxc, ' ', MAX_SIZE); memset(m_ie0, ' ', FLOAT21_SIZE); memset(m_ier, ' ', FLOAT21_SIZE); memset(m_iec, ' ', FLOAT21_SIZE); memset(m_ierr, ' ', FLOAT21_SIZE); memset(m_ierc, ' ', FLOAT21_SIZE); memset(m_iecc, ' ', FLOAT21_SIZE); memset(m_ia0, ' ', FLOAT21_SIZE); memset(m_iar, ' ', FLOAT21_SIZE); memset(m_iac, ' ', FLOAT21_SIZE); memset(m_iarr, ' ', FLOAT21_SIZE); memset(m_iarc, ' ', FLOAT21_SIZE); memset(m_iacc, ' ', FLOAT21_SIZE); memset(m_spx, ' ', FLOAT21_SIZE); memset(m_svx, ' ', FLOAT21_SIZE); memset(m_sax, ' ', FLOAT21_SIZE); memset(m_spy, ' ', FLOAT21_SIZE); memset(m_svy, ' ', FLOAT21_SIZE); memset(m_say, ' ', FLOAT21_SIZE); memset(m_spz, ' ', FLOAT21_SIZE); memset(m_svz, ' ', FLOAT21_SIZE); memset(m_saz, ' ', FLOAT21_SIZE); m_iid[IID_SIZE] = '\0'; m_edition[EDITION_SIZE] = '\0'; m_isid[ISID_SIZE] = '\0'; m_sid[SID_SIZE] = '\0'; m_stid[STID_SIZE] = '\0'; m_year[YEAR_SIZE] = '\0'; m_month[MONTH_SIZE] = '\0'; m_day[DAY_SIZE] = '\0'; m_hour[HOUR_SIZE] = '\0'; m_minute[MINUTE_SIZE] = '\0'; m_second[SECOND_SIZE] = '\0'; m_nrg[NRG_SIZE] = '\0'; m_ncg[NCG_SIZE] = '\0'; m_trg[FLOAT21_SIZE] = '\0'; m_tcg[FLOAT21_SIZE] = '\0'; m_grndd[GRNDD_SIZE] = '\0'; m_xuor[FLOAT21_SIZE] = '\0'; m_yuor[FLOAT21_SIZE] = '\0'; m_zuor[FLOAT21_SIZE] = '\0'; m_xuxr[FLOAT21_SIZE] = '\0'; m_xuyr[FLOAT21_SIZE] = '\0'; m_xuzr[FLOAT21_SIZE] = '\0'; m_yuxr[FLOAT21_SIZE] = '\0'; m_yuyr[FLOAT21_SIZE] = '\0'; m_yuzr[FLOAT21_SIZE] = '\0'; m_zuxr[FLOAT21_SIZE] = '\0'; m_zuyr[FLOAT21_SIZE] = '\0'; m_zuzr[FLOAT21_SIZE] = '\0'; m_v1x[FLOAT21_SIZE] = '\0'; m_v1y[FLOAT21_SIZE] = '\0'; m_v1z[FLOAT21_SIZE] = '\0'; m_v2x[FLOAT21_SIZE] = '\0'; m_v2y[FLOAT21_SIZE] = '\0'; m_v2z[FLOAT21_SIZE] = '\0'; m_v3x[FLOAT21_SIZE] = '\0'; m_v3y[FLOAT21_SIZE] = '\0'; m_v3z[FLOAT21_SIZE] = '\0'; m_v4x[FLOAT21_SIZE] = '\0'; m_v4y[FLOAT21_SIZE] = '\0'; m_v4z[FLOAT21_SIZE] = '\0'; m_v5x[FLOAT21_SIZE] = '\0'; m_v5y[FLOAT21_SIZE] = '\0'; m_v5z[FLOAT21_SIZE] = '\0'; m_v6x[FLOAT21_SIZE] = '\0'; m_v6y[FLOAT21_SIZE] = '\0'; m_v6z[FLOAT21_SIZE] = '\0'; m_v7x[FLOAT21_SIZE] = '\0'; m_v7y[FLOAT21_SIZE] = '\0'; m_v7z[FLOAT21_SIZE] = '\0'; m_v8x[FLOAT21_SIZE] = '\0'; m_v8y[FLOAT21_SIZE] = '\0'; m_v8z[FLOAT21_SIZE] = '\0'; m_grpx[FLOAT21_SIZE] = '\0'; m_grpy[FLOAT21_SIZE] = '\0'; m_grpz[FLOAT21_SIZE] = '\0'; m_fullr[FULL_SIZE] = '\0'; m_fullc[FULL_SIZE] = '\0'; m_minr[MIN_SIZE] = '\0'; m_maxr[MAX_SIZE] = '\0'; m_minc[MIN_SIZE] = '\0'; m_maxc[MAX_SIZE] = '\0'; m_ie0[FLOAT21_SIZE] = '\0'; m_ier[FLOAT21_SIZE] = '\0'; m_iec[FLOAT21_SIZE] = '\0'; m_ierr[FLOAT21_SIZE] = '\0'; m_ierc[FLOAT21_SIZE] = '\0'; m_iecc[FLOAT21_SIZE] = '\0'; m_ia0[FLOAT21_SIZE] = '\0'; m_iar[FLOAT21_SIZE] = '\0'; m_iac[FLOAT21_SIZE] = '\0'; m_iarr[FLOAT21_SIZE] = '\0'; m_iarc[FLOAT21_SIZE] = '\0'; m_iacc[FLOAT21_SIZE] = '\0'; m_spx[FLOAT21_SIZE] = '\0'; m_svx[FLOAT21_SIZE] = '\0'; m_sax[FLOAT21_SIZE] = '\0'; m_spy[FLOAT21_SIZE] = '\0'; m_svy[FLOAT21_SIZE] = '\0'; m_say[FLOAT21_SIZE] = '\0'; m_spz[FLOAT21_SIZE] = '\0'; m_svz[FLOAT21_SIZE] = '\0'; m_saz[FLOAT21_SIZE] = '\0'; } ossimString ossimNitfRsmidaTag::getIid() const { return ossimString(m_iid); } ossimString ossimNitfRsmidaTag::getEdition() const { return ossimString(m_edition); } ossimString ossimNitfRsmidaTag::getIsid() const { return ossimString(m_isid); } ossimString ossimNitfRsmidaTag::getSid() const { return ossimString(m_sid); } ossimString ossimNitfRsmidaTag::getStid() const { return ossimString(m_stid); } ossimString ossimNitfRsmidaTag::getYear() const { return ossimString(m_year); } ossimString ossimNitfRsmidaTag::getMonth() const { return ossimString(m_month); } ossimString ossimNitfRsmidaTag::getDay() const { return ossimString(m_day); } ossimString ossimNitfRsmidaTag::getHour() const { return ossimString(m_hour); } ossimString ossimNitfRsmidaTag::getMinute() const { return ossimString(m_minute); } ossimString ossimNitfRsmidaTag::getSecond() const { return ossimString(m_second); } ossimString ossimNitfRsmidaTag::getNrg() const { return ossimString(m_nrg); } ossimString ossimNitfRsmidaTag::getNcg() const { return ossimString(m_ncg); } ossimString ossimNitfRsmidaTag::getTrg() const { return ossimString(m_trg); } ossimString ossimNitfRsmidaTag::getTcg() const { return ossimString(m_tcg); } ossimString ossimNitfRsmidaTag::getGrndd() const { return ossimString(m_grndd); } ossimString ossimNitfRsmidaTag::getXuor() const { return ossimString(m_xuor); } ossimString ossimNitfRsmidaTag::getYuor() const { return ossimString(m_yuor); } ossimString ossimNitfRsmidaTag::getZuor() const { return ossimString(m_zuor); } ossimString ossimNitfRsmidaTag::getXuxr() const { return ossimString(m_xuxr); } ossimString ossimNitfRsmidaTag::getXuyr() const { return ossimString(m_xuyr); } ossimString ossimNitfRsmidaTag::getXuzr() const { return ossimString(m_xuzr); } ossimString ossimNitfRsmidaTag::getYuxr() const { return ossimString(m_yuxr); } ossimString ossimNitfRsmidaTag::getYuyr() const { return ossimString(m_yuyr); } ossimString ossimNitfRsmidaTag::getYuzr() const { return
c++
code
19,999
6,114
/* Copyright 2019 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/core/common_runtime/colocation_graph.h" #include <memory> #include <set> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "absl/strings/str_join.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/inspecting_placer.h" #include "tensorflow/core/common_runtime/partitioning_utils.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/attr_value_util.h" #include "tensorflow/core/framework/device_attributes.pb.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/util/device_name_utils.h" #include "tensorflow/core/util/dump_graph.h" #include "tensorflow/core/util/port.h" namespace tensorflow { namespace { // We hoist the conversion from C-style string literal to StringPiece here, // so that we can avoid the many repeated calls to strlen(). const StringPiece kColocationAttrNameStringPiece(kColocationAttrName); const StringPiece kColocationGroupPrefixStringPiece(kColocationGroupPrefix); // Returns a list of devices having type in supported_device_types. The // returned list is sorted by preferred type (higher numeric type is preferred). std::vector<Device*> FilterSupportedDevices( const std::vector<Device*>& devices, const PrioritizedDeviceTypeVector& supported_device_types, const Device* default_device) { Device* filtered_default_device = nullptr; std::vector<std::pair<Device*, int32>> prioritized_filtered_devices; for (const auto& supported_device_type : supported_device_types) { for (Device* device : devices) { if (DeviceType(device->attributes().device_type()) == supported_device_type.first) { if (default_device && (device == default_device || // TODO(nareshmodi, fishx): At times the device pointer in the // device set is different to the one passed in as the default // device. Figure out why this might be. device->name() == default_device->name())) { filtered_default_device = device; } else { prioritized_filtered_devices.emplace_back( device, supported_device_type.second); } } } } auto device_sort = [](const std::pair<Device*, int32>& a, const std::pair<Device*, int32>& b) { if (a.second != b.second) { return a.second > b.second; } auto a_priority = DeviceSet::DeviceTypeOrder(DeviceType(a.first->device_type())); auto b_priority = DeviceSet::DeviceTypeOrder(DeviceType(b.first->device_type())); // First sort by prioritized device type (higher is preferred) and // then by device name (lexicographically). if (a_priority != b_priority) { return a_priority > b_priority; } return StringPiece(a.first->name()) < StringPiece(b.first->name()); }; std::sort(prioritized_filtered_devices.begin(), prioritized_filtered_devices.end(), device_sort); std::vector<Device*> filtered_devices; if (filtered_default_device != nullptr) { filtered_devices.emplace_back(filtered_default_device); } for (const auto& prioritized_filtered_device : prioritized_filtered_devices) { filtered_devices.push_back(prioritized_filtered_device.first); } return filtered_devices; } // Using absl::StrJoin with lambda does not work in tf-lite builds. std::vector<string> DevicesToString(const std::vector<Device*> devices) { std::vector<string> v; v.reserve(devices.size()); for (Device* d : devices) { v.push_back(d->name()); } return v; } // Using absl::StrJoin with lambda does not work in tf-lite builds. std::vector<string> DeviceTypeAndPriorityToString( const PrioritizedDeviceTypeVector& devices) { std::vector<string> v; v.reserve(devices.size()); for (const std::pair<DeviceType, int32>& device_and_type : devices) { v.push_back(DeviceTypeString(device_and_type.first)); } return v; } bool IsRefOrResource(DataType data_type) { return IsRefType(data_type) || data_type == DT_RESOURCE; } // While Placer can override requested device on ops processing // resources, i.e. node that take (and potentially return) a resource, // it must not override requested device on ops generating a resource, // e.g. VarHandleOp, _Arg. Such ops are currently no-input, single resource/ref // output nodes. bool IsRefOrResourceGeneratorNode(const Node& node) { return node.num_inputs() == 0 && node.num_outputs() == 1 && IsRefOrResource(node.output_type(0)); } bool IsExemptFromResourceInputColocation(const Node* node) { // Note: Partitioned function calls, which place and partition their // function bodies, are exempt from this check: they forward resource and // ref inputs to operations that are appropriately placed, instead of // dereferencing them. const string& op_type = node->op_def().name(); return op_type == "PartitionedCall" || op_type == "StatefulPartitionedCall" || op_type == "ReduceDataset" || op_type == "ExperimentalScanDataset"; } bool HasPriorities(const PrioritizedDeviceTypeVector& device_types) { for (const auto& prioritized_device_type : device_types) { if (prioritized_device_type.second != 0) return true; } return false; } bool ArePrioritiesSame(const PrioritizedDeviceTypeVector& a_types, const PrioritizedDeviceTypeVector& b_types) { if (a_types.size() != b_types.size()) { return false; } for (int i = 0; i < a_types.size(); ++i) { if (a_types[i].first != b_types[i].first) { return false; } } return true; } } // namespace Status Member::SetParentAndSupportedDevices( const Node& node, const std::vector<DeviceType>& types) { int id = node.id(); if (id < 0) { return errors::Internal("Placer should not be creating a Member for node: ", node.DebugString()); } parent_ = id; return SupportedDeviceTypesForNode(types, node.def(), &supported_device_types_); } Status Member::SetAssignedDeviceName(const string& device_name) { if (DeviceNameUtils::HasSomeDetails(requested_device_name_)) { return errors::Internal( "Setting assigned device name when there is a requested device set " "is unsupported"); } if (!DeviceNameUtils::ParseFullName(device_name, &assigned_device_name_)) { return errors::Internal("Malformed assigned device '", device_name, "'"); } // Set requested device to assigned_device to maintain the invariant that // requested is a specialization of assigned. requested_device_name_ = assigned_device_name_; return Status::OK(); } Status Member::SetResourceDeviceName(const Node& node) { if (DeviceNameUtils::HasSomeDetails(requested_device_name_)) { return errors::Internal( "Setting resource device name when there is a requested device set " "is unsupported"); } if (!DeviceNameUtils::ParseFullName(node.requested_device(), &resource_device_name_)) { return errors::InvalidArgument("Malformed device specification '", node.requested_device(), "' in node: ", node.DebugString()); } // Set requested device to resource device to maintain the invariant that // requested is a specialization of resource. requested_device_name_ = resource_device_name_; return Status::OK(); } Status Member::SetRequestedDeviceName(const Node& node) { if (DeviceNameUtils::HasSomeDetails(assigned_device_name_)) { return errors::Internal( "Setting requested device name when there is an assigned device set " "is unsupported"); } if (DeviceNameUtils::HasSomeDetails(resource_device_name_)) { return errors::Internal( "Setting requested device name when there is a resource device set " "is unsupported"); } if (!DeviceNameUtils::ParseFullName(node.requested_device(), &requested_device_name_)) { return errors::InvalidArgument("Malformed device specification '", node.requested_device(), "' in node: ", node.DebugString()); } return Status::OK(); } Status Member::FillPossibleDevices(PossibleDevices* possible_device) const { if (DeviceNameUtils::HasSomeDetails(assigned_device_name_)) { return errors::Internal( "Cannot fill PossibleDevices from a member that has non-empty assigned " "device. Did we start assigning devices to functions called by deep " "ops? ", DebugString()); } possible_device->requested_device_name = requested_device_name_; possible_device->resource_device_name = resource_device_name_; possible_device->device_types = supported_device_types_; return Status::OK(); } Status Member::EnsureCompatibilityAcrossResourceEdge( const Node& src, const Member& src_root, const Node& dst, /*dst_root is this*/ bool log_device_placement) { if (!DeviceNameUtils::AreCompatibleDevNames(src_root.assigned_device_name_, assigned_device_name_)) { return errors::InvalidArgument( "Cannot place the graph because a reference or resource edge " "connects colocation groups with incompatible assigned devices: ", DeviceNameUtils::ParsedNameToString(src_root.assigned_device_name_), " vs ", DeviceNameUtils::ParsedNameToString(assigned_device_name_), ". The edge src node is ", src.name(), " , and the dst node is ", dst.name()); } if (!DeviceNameUtils::AreCompatibleDevNames(src_root.resource_device_name_, resource_device_name_)) { return errors::InvalidArgument( "Cannot place the graph because a reference or resource edge " "connects colocation groups with incompatible resource devices: ", DeviceNameUtils::ParsedNameToString(src_root.resource_device_name_), " vs ", DeviceNameUtils::ParsedNameToString(resource_device_name_), ". The edge src node is ", src.name(), " , and the dst node is ", dst.name()); } if (DeviceNameUtils::AreCompatibleDevNames(src_root.requested_device_name_, requested_device_name_)) { return Status::OK(); } // If we are here, assigned and resource devices are compatible but requested // ones are not. We will be overriding the requested device for destination // node, but need to preserve the invariant that it will be a specialization // of the assigned and resource devices. if (log_device_placement) { LOG(INFO) << "Ignoring device specification " << DeviceNameUtils::ParsedNameToString(requested_device_name_) << " for node '" << dst.name() << "' because the input edge from '" << src.name() << "' is a reference connection and already has a device " "field set to " << DeviceNameUtils::ParsedNameToString( src_root.requested_device_name_); } requested_device_name_ = src_root.requested_device_name_; DeviceNameUtils::EnsureSpecification(&requested_device_name_, assigned_device_name_); DeviceNameUtils::EnsureSpecification(&requested_device_name_, resource_device_name_); return Status::OK(); } void Member::Merge(std::vector<Member>* tree, int x_root, int y_root, Member** new_root, Member** old_root, bool dry_run) { Member& x_root_member = (*tree)[x_root]; Member& y_root_member = (*tree)[y_root]; // Merge the sets by setting the parent pointer of the smaller tree's root // node to point to the root of the larger tree. Together with path // compression in ColocationGraph::FindRoot, this ensures that we do not // experience pathological performance on graphs such as chains. int new_root_id, old_root_id; if (x_root_member.rank_ < y_root_member.rank_) { // The tree rooted at x_root is shallower, so connect it to // y_root. The rank of y_root is unchanged because its new // child has strictly less rank. if (!dry_run) { x_root_member.parent_ = y_root; } new_root_id = y_root; old_root_id = x_root; } else if (x_root_member.rank_ > y_root_member.rank_) { // The tree rooted at y_root is shallower, so connect it to // x_root. The rank of x_root is unchanged because its new // child has strictly less rank. if (!dry_run) { y_root_member.parent_ = x_root; } new_root_id = x_root; old_root_id = y_root; } else { if (!dry_run) { // Both trees have the same rank, so break the tie by choosing // x_root as the new root. y_root_member.parent_ = x_root; // Increment the rank of the tree rooted at x_root, because it // is now strictly deeper than before. ++x_root_member.rank_; } new_root_id = x_root; old_root_id = y_root; } *new_root = &(*tree)[new_root_id]; *old_root = &(*tree)[old_root_id]; } // tree is non-const because we can change some `parent` pointers in some // members for more efficient future lookups. The vector itself is not // changed. int Member::FindAndUpdateRoot(std::vector<Member>* tree, int node_id) { Member& member = (*tree)[node_id]; if (member.parent_ == node_id) { // member.parent is the root of this disjoint tree. Do nothing. } else { member.parent_ = FindAndUpdateRoot(tree, member.parent_); } // Now it is guaranteed that member.parent is the root of this disjoint // tree. return member.parent_; } int Member::FindRoot(const std::vector<Member>& tree, int node_id) { const Member& member = tree[node_id]; if (member.parent_ == node_id) { return member.parent_; } return FindRoot(tree, member.parent_); } Status Member::MergeDeviceNames(const Member& other, bool allow_soft_placement) { // Assuming the "requested is a specialization of assigned and resource // devices" invariant holds for this and `other`, it will hold after the // merges below. DeviceNameUtils::ParsedName assigned_device_name_copy = assigned_device_name_; TF_RETURN_IF_ERROR(DeviceNameUtils::MergeDevNames( &assigned_device_name_copy, other.assigned_device_name_)); DeviceNameUtils::ParsedName resource_device_name_copy = resource_device_name_; TF_RETURN_IF_ERROR(DeviceNameUtils::MergeDevNames( &resource_device_name_copy, other.resource_device_name_)); DeviceNameUtils::ParsedName requested_device_name_copy = requested_device_name_; TF_RETURN_IF_ERROR(DeviceNameUtils::MergeDevNames( &requested_device_name_copy, other.requested_device_name_, allow_soft_placement)); DeviceNameUtils::EnsureSpecification(&requested_device_name_copy, assigned_device_name_copy); DeviceNameUtils::EnsureSpecification(&requested_device_name_copy, resource_device_name_copy); // We checked for all errors, now change the devices. assigned_device_name_ = assigned_device_name_copy; resource_device_name_ = resource_device_name_copy; requested_device_name_ = requested_device_name_copy; return Status::OK(); } // Updates this to contain the intersection of the device types in // this and "other". bool Member::MergeSupportedDevices(const Member& other) { return MergeSupportedDevices(other.supported_device_types_); } bool Member::MergeSupportedDevices( const PrioritizedDeviceTypeVector& other_devices) { // Generate intersection with priorities. // Each vector contains the same device types but with different priorities. // The priorities are taken from the corresponding source vector. PrioritizedDeviceTypeVector target_intersection; PrioritizedDeviceTypeVector other_intersection; for (const auto& prioritized_device_type : supported_device_types_) { bool found = false; for (const auto& other_prioritized_device_type : other_devices) { if (prioritized_device_type.first == other_prioritized_device_type.first) { found = true; other_intersection.push_back(other_prioritized_device_type); break; } } if (found) { target_intersection.push_back(prioritized_device_type); } } // Sort the devices by priority order. auto device_sort = [](const std::pair<DeviceType, int32>& a, const std::pair<DeviceType, int32>& b) { // First look at set priorities. if (a.second != b.second) { return a.second > b.second; } // Then fallback to default priorities. auto a_priority = DeviceSet::DeviceTypeOrder(a.first); auto b_priority = DeviceSet::DeviceTypeOrder(b.first); if (a_priority != b_priority) { return a_priority > b_priority; } // Finally just look at the Device type strings. return a.first.type_string() < b.first.type_string(); }; std::sort(target_intersection.begin(), target_intersection.end(), device_sort); std::sort(other_intersection.begin(), other_intersection.end(), device_sort); PrioritizedDeviceTypeVector result; bool is_target_prioritized = HasPriorities(target_intersection); bool is_other_prioritized = HasPriorities(other_intersection); if (!is_target_prioritized && !is_other_prioritized) { // If neither are prioritized then we just return the original i.e. target // prioritization. result = target_intersection; } else if (is_target_prioritized && !is_other_prioritized) { // If only one is prioritized, then we respect priorities of that in the // intersection. result = target_intersection; } else if (!is_target_prioritized && is_other_prioritized) { result = other_intersection; } else { // If both have priorities and agree then we go with that. If the // prioritization order is different, then we just fallback to the default // i.e. what the DeviceTypeOrder suggests. In that case, we also set the // merged priorities to 0, so that downstream merges work correctly as well. if (ArePrioritiesSame(target_intersection, other_intersection)) { result = target_intersection; } else { for (const auto& prioritized_device : target_intersection) { result.push_back(std::make_pair(prioritized_device.first, 0)); } std::sort(result.begin(), result.end(), device_sort); } } if (result.empty()) { return false; } supported_device_types_ = result; return true; } Status Member::AssignDevice(const Node& node, bool allow_soft_placement) { if (node.assigned_device_name_index() == assigned_device_name_index_) { return Sta
c++
code
20,000
3,581
// Copyright 2013 The Flutter 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 "flutter/flow/paint_utils.h" #include <stdlib.h> #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkShader.h" namespace flow { namespace { sk_sp<SkShader> CreateCheckerboardShader(SkColor c1, SkColor c2, int size) { SkBitmap bm; bm.allocN32Pixels(2 * size, 2 * size); bm.eraseColor(c1); bm.eraseArea(SkIRect::MakeLTRB(0, 0, size, size), c2); bm.eraseArea(SkIRect::MakeLTRB(size, size, 2 * size, 2 * size), c2); return SkShader::MakeBitmapShader(bm, SkTileMode::kRepeat, SkTileMode::kRepeat); } } // anonymous namespace void DrawCheckerboard(SkCanvas* canvas, SkColor c1, SkColor c2, int size) { SkPaint paint; paint.setShader(CreateCheckerboardShader(c1, c2, size)); canvas->drawPaint(paint); } void DrawCheckerboard(SkCanvas* canvas, const SkRect& rect) { // Draw a checkerboard canvas->save(); canvas->clipRect(rect); auto checkerboard_color = SkColorSetARGB(64, rand() % 256, rand() % 256, rand() % 256); DrawCheckerboard(canvas, checkerboard_color, 0x00000000, 12); canvas->restore(); // Stroke the drawn area SkPaint debugPaint; debugPaint.setStrokeWidth(8); debugPaint.setColor(SkColorSetA(checkerboard_color, 255)); debugPaint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(rect, debugPaint); } } // namespace flow
c++
code
1,591
343
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "kinematics-precomp.h" // Precompiled header // #include <mrpt/kinematics/CVehicleVelCmd.h> #include <mrpt/serialization/CArchive.h> using namespace mrpt::kinematics; IMPLEMENTS_VIRTUAL_SERIALIZABLE(CVehicleVelCmd, CSerializable, mrpt::kinematics) CVehicleVelCmd::CVehicleVelCmd() = default; CVehicleVelCmd::CVehicleVelCmd(const CVehicleVelCmd& other) { *this = other; } CVehicleVelCmd::~CVehicleVelCmd() = default; std::string mrpt::kinematics::CVehicleVelCmd::asString() const { std::string s; s += "("; for (size_t i = 0; i < getVelCmdLength(); i++) { s += mrpt::format( "%s=%.03f ", getVelCmdDescription(i).c_str(), getVelCmdElement(i)); } s += ")"; return s; } CVehicleVelCmd& CVehicleVelCmd::operator=(const CVehicleVelCmd& other) { const size_t nThis = this->getVelCmdLength(); ASSERTMSG_( typeid(*this) == typeid(other), "Trying to copy incompatible classes"); for (size_t i = 0; i < nThis; i++) this->setVelCmdElement(i, other.getVelCmdElement(i)); return *this; } void CVehicleVelCmd::TVelCmdParams::loadConfigFile( const mrpt::config::CConfigFileBase& cfg, const std::string& section) { MRPT_LOAD_CONFIG_VAR_NO_DEFAULT(robotMax_V_mps, double, cfg, section); MRPT_LOAD_HERE_CONFIG_VAR_DEGREES_NO_DEFAULT( robotMax_W_degps, double, robotMax_W_radps, cfg, section); MRPT_LOAD_CONFIG_VAR(robotMinCurvRadius, double, cfg, section); } void CVehicleVelCmd::TVelCmdParams::saveToConfigFile( mrpt::config::CConfigFileBase& c, const std::string& s) const { MRPT_SAVE_CONFIG_VAR_COMMENT( robotMax_V_mps, "Max. linear speed (m/s) [Default=-1 (not set), will raise exception " "if needed and not set]"); MRPT_SAVE_CONFIG_VAR_DEGREES_COMMENT( "robotMax_W_degps", robotMax_W_radps, "Max. angular speed (deg/s) [Default=-1 (not set), will raise " "exception if needed and not set]"); MRPT_SAVE_CONFIG_VAR_COMMENT( robotMinCurvRadius, "Min. radius of curvature of paths (m) [Default=-1 (not set), will " "raise exception if needed and not set]"); } CVehicleVelCmd::TVelCmdParams::TVelCmdParams() = default;
c++
code
2,693
585
/* * Copyright (c) 2021, Krisna Pranav * * SPDX-License-Identifier: BSD-2-Clause */ // includes #include <base/CharacterTypes.h> #include <base/JsonArray.h> #include <base/JsonObject.h> #include <base/JsonParser.h> namespace Base { constexpr bool is_space(int ch) { return ch == '\t' || ch == '\n' || ch == '\r' || ch == ' '; } String JsonParser::consume_and_unescape_string() { if (!consume_specific('"')) return {}; StringBuilder final_sb; for (;;) { size_t peek_index = m_index; char ch = 0; for (;;) { if (peek_index == m_input.length()) break; ch = m_input[peek_index]; if (ch == '"' || ch == '\\') break; if (is_ascii_c0_control(ch)) return {}; ++peek_index; } while (peek_index != m_index) { final_sb.append(m_input[m_index]); m_index++; } if (m_index == m_input.length()) break; if (ch == '"') break; if (ch != '\\') { final_sb.append(consume()); continue; } ignore(); if (next_is('"')) { ignore(); final_sb.append('"'); continue; } if (next_is('\\')) { ignore(); final_sb.append('\\'); continue; } if (next_is('/')) { ignore(); final_sb.append('/'); continue; } if (next_is('n')) { ignore(); final_sb.append('\n'); continue; } if (next_is('r')) { ignore(); final_sb.append('\r'); continue; } if (next_is('t')) { ignore(); final_sb.append('\t'); continue; } if (next_is('b')) { ignore(); final_sb.append('\b'); continue; } if (next_is('f')) { ignore(); final_sb.append('\f'); continue; } if (next_is('u')) { ignore(); if (tell_remaining() < 4) return {}; auto code_point = Base::StringUtils::convert_to_uint_from_hex(consume(4)); if (code_point.has_value()) { final_sb.append_code_point(code_point.value()); continue; } else { return {}; } } return {}; } if (!consume_specific('"')) return {}; return final_sb.to_string(); } Optional<JsonValue> JsonParser::parse_object() { JsonObject object; if (!consume_specific('{')) return {}; for (;;) { ignore_while(is_space); if (peek() == '}') break; ignore_while(is_space); auto name = consume_and_unescape_string(); if (name.is_null()) return {}; ignore_while(is_space); if (!consume_specific(':')) return {}; ignore_while(is_space); auto value = parse_helper(); if (!value.has_value()) return {}; object.set(name, value.release_value()); ignore_while(is_space); if (peek() == '}') break; if (!consume_specific(',')) return {}; ignore_while(is_space); if (peek() == '}') return {}; } if (!consume_specific('}')) return {}; return JsonValue { move(object) }; } Optional<JsonValue> JsonParser::parse_array() { JsonArray array; if (!consume_specific('[')) return {}; for (;;) { ignore_while(is_space); if (peek() == ']') break; auto element = parse_helper(); if (!element.has_value()) return {}; array.append(element.release_value()); ignore_while(is_space); if (peek() == ']') break; if (!consume_specific(',')) return {}; ignore_while(is_space); if (peek() == ']') return {}; } ignore_while(is_space); if (!consume_specific(']')) return {}; return JsonValue { move(array) }; } Optional<JsonValue> JsonParser::parse_string() { auto result = consume_and_unescape_string(); if (result.is_null()) return {}; return JsonValue(result); } Optional<JsonValue> JsonParser::parse_number() { JsonValue value; Vector<char, 128> number_buffer; Vector<char, 128> fraction_buffer; bool is_double = false; for (;;) { char ch = peek(); if (ch == '.') { if (is_double) return {}; is_double = true; ++m_index; continue; } if (ch == '-' || (ch >= '0' && ch <= '9')) { if (is_double) { if (ch == '-') return {}; fraction_buffer.append(ch); } else { if (number_buffer.size() > 0) { if (number_buffer.at(0) == '0') return {}; } if (number_buffer.size() > 1) { if (number_buffer.at(0) == '-' && number_buffer.at(1) == '0') return {}; } number_buffer.append(ch); } ++m_index; continue; } break; } StringView number_string(number_buffer.data(), number_buffer.size()); StringView fraction_string(fraction_buffer.data(), fraction_buffer.size()); #ifndef KERNEL if (is_double) { int whole = 0; auto to_signed_result = number_string.to_uint(); if (to_signed_result.has_value()) { whole = to_signed_result.value(); } else { auto number = number_string.to_int(); if (!number.has_value()) return {}; whole = number.value(); } auto fraction_string_uint = fraction_string.to_uint(); if (!fraction_string_uint.has_value()) return {}; int fraction = fraction_string_uint.value(); fraction *= (whole < 0) ? -1 : 1; auto divider = 1; for (size_t i = 0; i < fraction_buffer.size(); ++i) { divider *= 10; } value = JsonValue((double)whole + ((double)fraction / divider)); } else { #endif auto to_unsigned_result = number_string.to_uint<u64>(); if (to_unsigned_result.has_value()) { auto number = *to_unsigned_result; if (number <= NumericLimits<u32>::max()) value = JsonValue((u32)number); else value = JsonValue(number); } else { auto number = number_string.to_int<i64>(); if (!number.has_value()) return {}; if (number.value() <= NumericLimits<i32>::max()) { value = JsonValue((i32)number.value()); } else { value = JsonValue(number.value()); } } #ifndef KERNEL } #endif return value; } Optional<JsonValue> JsonParser::parse_true() { if (!consume_specific("true")) return {}; return JsonValue(true); } Optional<JsonValue> JsonParser::parse_false() { if (!consume_specific("false")) return {}; return JsonValue(false); } Optional<JsonValue> JsonParser::parse_null() { if (!consume_specific("null")) return {}; return JsonValue(JsonValue::Type::Null); } Optional<JsonValue> JsonParser::parse_helper() { ignore_while(is_space); auto type_hint = peek(); switch (type_hint) { case '{': return parse_object(); case '[': return parse_array(); case '"': return parse_string(); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return parse_number(); case 'f': return parse_false(); case 't': return parse_true(); case 'n': return parse_null(); } return {}; } Optional<JsonValue> JsonParser::parse() { auto result = parse_helper(); if (!result.has_value()) return {}; ignore_while(is_space); if (!is_eof()) return {}; return result; } }
c++
code
8,453
1,860
 // Test of ORM Lite // https://github.com/BOT-Man-JL/ORM-Lite // BOT Man, 2016 #include <iostream> #include <memory> #include <string> #include "../src/ormlite.h" using namespace BOT_ORM; using namespace BOT_ORM::Expression; #define CATCH_CONFIG_MAIN #include "catch.hpp" #define TESTDB "test.db" struct ModelA { int a_int; std::string a_string; double a_double; Nullable<int> an_int; Nullable<double> an_double; Nullable<std::string> an_string; // Inject ORM-Lite into this Class :-) ORMAP ("ModelA", a_int, a_string, a_double, an_int, an_double, an_string); }; struct ModelB { unsigned long b_ulong; float b_float; Nullable<unsigned long> bn_ulong; Nullable<float> bn_float; // Inject ORM-Lite into this Class :-) ORMAP ("ModelB", b_ulong, b_float, bn_ulong, bn_float); }; struct ModelC { unsigned c_uint; int a_int; unsigned long b_ulong; // Inject ORM-Lite into this Class :-) ORMAP ("ModelC", c_uint, a_int, b_ulong); }; struct ModelD { int d_int; // Inject ORM-Lite into this Class :-) ORMAP ("ModelD", d_int); }; namespace detail { template<typename Model> void ResetTable (const Model &model) { ORMapper mapper (TESTDB); try { mapper.CreateTbl (model); } catch (...) { mapper.DropTbl (model); mapper.CreateTbl (model); } } } void ResetTables () {} template<typename Model, typename ...OtherModels> void ResetTables (const Model &model, const OtherModels &...models) { detail::ResetTable (model); ResetTables (models...); } TEST_CASE ("create/drop tables") { ResetTables (ModelA {}, ModelB {}, ModelC {}, ModelD {}); ORMapper mapper (TESTDB); mapper.DropTbl (ModelA {}); mapper.DropTbl (ModelB {}); mapper.DropTbl (ModelC {}); mapper.DropTbl (ModelD {}); mapper.CreateTbl (ModelA {}); mapper.CreateTbl (ModelB {}); mapper.CreateTbl (ModelC {}); mapper.CreateTbl (ModelD {}); } TEST_CASE ("normal cases") { ModelA ma; ModelD md; auto field = FieldExtractor { ma, md }; ORMapper mapper (TESTDB); mapper.Insert (ModelD { 0 }); mapper.Insert (ModelD { 0 }, false); mapper.InsertRange (std::list<ModelD> { ModelD { 2 }, ModelD { 3 } }); mapper.InsertRange (std::list<ModelD> { ModelD { 2 }, ModelD { 3 } }, false); mapper.Update (ModelD { 0 }); mapper.UpdateRange (std::list<ModelD> { ModelD { 2 }, ModelD { 3 } }); mapper.Update (ModelD {}, field (md.d_int) = 6, field (md.d_int) == 0); // 0 -> 6 mapper.Delete (ModelD { 1 }); mapper.Delete (ModelD {}, field (md.d_int) == 0); // No such one constexpr auto countExpected = 5; constexpr auto firstIdExpected = 2; constexpr auto lastIdExpected = 6; // Expected: 2, 3, 4, 5, 6 REQUIRE (mapper.Query (ModelD {}) .Aggregate (Count ()).Value () == countExpected); REQUIRE (mapper.Query (ModelD {}) .LeftJoin (ModelA {}, field (ma.a_int) == field (md.d_int)) .Aggregate (Count ()).Value () == countExpected); mapper.Insert (ModelA {}, false); REQUIRE (mapper.Query (ModelD {}).Select (field (md.d_int)) .Union (mapper.Query (ModelA {}).Select (field (ma.a_int))) .ToList ().size () == countExpected + 1); REQUIRE (mapper.Query (ModelD {}) .ToVector ()[countExpected - 1].d_int == lastIdExpected); auto firstTuple = mapper.Query (ModelD {}) .Select (field (md.d_int)) .ToList ().front (); REQUIRE (std::get<0> (firstTuple).Value () == firstIdExpected); } TEST_CASE ("handle existing table") { // before ResetTables (ModelD {}); { sqlite3 *db; sqlite3_open (TESTDB, &db); sqlite3_exec (db, "DROP TABLE ModelD;" "CREATE TABLE ModelD (d_int INTEGER, d_str TEXT);" "INSERT INTO ModelD values (1, 'John');", nullptr, nullptr, nullptr); sqlite3_close (db); } // test ORMapper mapper (TESTDB); REQUIRE_THROWS_WITH (mapper.Query (ModelD {}).ToList (), "SQL error: 'Bad Column Count' at 'select * from ModelD;'"); } TEST_CASE ("chinese characters") { // before ResetTables (ModelA {}); // test ORMapper mapper (TESTDB); mapper.Insert ( ModelA { 0, "你好", 0, nullptr, nullptr, nullptr }, false); mapper.Insert ( ModelA { 0, u8"世界", 0, nullptr, nullptr, nullptr }, false); auto chinese = mapper.Query (ModelA {}).ToVector (); REQUIRE (chinese.size () == 2); REQUIRE (chinese[0].a_string == "你好"); REQUIRE (chinese[1].a_string == u8"世界"); } TEST_CASE ("lifetime of mapper") { // before ResetTables (ModelA {}); { ORMapper mapper (TESTDB); mapper.Insert (ModelA {}, false); mapper.Insert (ModelA {}, false); } // test std::unique_ptr<Queryable<ModelA>> queryable; { ORMapper mapper (TESTDB); queryable.reset (new Queryable<ModelA> { mapper.Query (ModelA {}) }); } REQUIRE (queryable->ToList ().size () == 2); } using InvalidModel = int; TEST_CASE ("invalid model", "[not-compile]") { ORMapper mapper (TESTDB); //mapper.CreateTbl (InvalidModel {}); //mapper.CreateTbl (InvalidModel {}, Constraint::Unique (Field<int> {"", nullptr})); //mapper.DropTbl (InvalidModel {}); //mapper.Insert (InvalidModel {}); //mapper.Insert (InvalidModel {}, false); ////mapper.InsertRange (InvalidModel {}); //mapper.InsertRange (std::vector<int> {}); //mapper.InsertRange (std::vector<int> {}, false); //mapper.Update (InvalidModel {}); ////mapper.UpdateRange (InvalidModel {}); //mapper.UpdateRange (std::vector<int> {}); //mapper.Update (InvalidModel {}, SetExpr { "" }, Expr { Selectable<int> {"", nullptr}, "" }); //mapper.Delete (InvalidModel {}); //mapper.Delete (InvalidModel {}, Expr { Selectable<int> {"", nullptr}, "" }); //mapper.Query (InvalidModel {}); //FieldExtractor { InvalidModel {}, double () }; ////mapper.Query (ModelA {}) //// .Join (InvalidModel {}, Expr { Selectable<int> {"", nullptr}, "" }); ////mapper.Query (ModelA {}) //// .LeftJoin (InvalidModel {}, Expr { Selectable<int> {"", nullptr}, "" }); } struct SickModel { ModelD dd; char ch; ORMAP ("SickModel", dd, ch); }; TEST_CASE ("invalid field", "[not-compile]") { ORMapper mapper (TESTDB); //mapper.CreateTbl (SickModel {}); //mapper.Insert (SickModel {}); //mapper.Update (SickModel {}); //mapper.Delete (SickModel {}); //mapper.Query (SickModel {}).ToList (); }
c++
code
6,661
1,630
// Copyright (C) 2018 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock-spec-builders.h> #include <mock_mkldnn_extension.hpp> #include <cpp_interfaces/impl/mock_executable_thread_safe_async_only.hpp> #include <cpp_interfaces/impl/mock_async_infer_request_internal.hpp> #include <ie_version.hpp> #include <cpp_interfaces/base/ie_executable_network_base.hpp> using namespace ::testing; using namespace std; using namespace InferenceEngine; using namespace InferenceEngine::details; class ExecutableNetworkThreadSafeAsyncOnlyTests : public ::testing::Test { protected: shared_ptr<MockExecutableNetworkThreadSafeAsyncOnly> mockExeNetwork; shared_ptr<MockAsyncInferRequestInternal> mockAsyncInferRequestInternal; shared_ptr<IExecutableNetwork> exeNetwork; ResponseDesc dsc; StatusCode sts; virtual void TearDown() { EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockAsyncInferRequestInternal.get())); EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockExeNetwork.get())); } virtual void SetUp() { mockExeNetwork = make_shared<MockExecutableNetworkThreadSafeAsyncOnly>(); exeNetwork = details::shared_from_irelease( new ExecutableNetworkBase<MockExecutableNetworkThreadSafeAsyncOnly>(mockExeNetwork)); InputsDataMap networkInputs; OutputsDataMap networkOutputs; mockAsyncInferRequestInternal = make_shared<MockAsyncInferRequestInternal>(networkInputs, networkOutputs); } }; TEST_F(ExecutableNetworkThreadSafeAsyncOnlyTests, createAsyncInferRequestCallsThreadSafeImplAndSetNetworkIO) { IInferRequest::Ptr req; EXPECT_CALL(*mockExeNetwork.get(), CreateAsyncInferRequestImpl(_, _)).WillOnce( Return(mockAsyncInferRequestInternal)); EXPECT_NO_THROW(exeNetwork->CreateInferRequest(req, &dsc)); auto threadSafeReq = dynamic_pointer_cast<InferRequestBase<AsyncInferRequestInternal>>(req); ASSERT_NE(threadSafeReq, nullptr); } TEST_F(ExecutableNetworkThreadSafeAsyncOnlyTests, returnErrorIfInferThrowsException) { IInferRequest::Ptr req; EXPECT_CALL(*mockExeNetwork.get(), CreateAsyncInferRequestImpl(_, _)).WillOnce( Return(mockAsyncInferRequestInternal)); EXPECT_NO_THROW(exeNetwork->CreateInferRequest(req, &dsc)); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), InferImpl()).WillOnce(Throw(std::runtime_error(""))); EXPECT_NO_THROW(sts = req->Infer(&dsc)); ASSERT_EQ(StatusCode::GENERAL_ERROR, sts) << dsc.msg; } TEST_F(ExecutableNetworkThreadSafeAsyncOnlyTests, returnErrorIfStartAsyncThrowsException) { IInferRequest::Ptr req; EXPECT_CALL(*mockExeNetwork.get(), CreateAsyncInferRequestImpl(_, _)).WillOnce( Return(mockAsyncInferRequestInternal)); EXPECT_NO_THROW(exeNetwork->CreateInferRequest(req, &dsc)); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), StartAsyncImpl()).WillOnce(Throw(std::runtime_error(""))); EXPECT_NO_THROW(sts = req->StartAsync(&dsc)); ASSERT_EQ(StatusCode::GENERAL_ERROR, sts) << dsc.msg; } TEST_F(ExecutableNetworkThreadSafeAsyncOnlyTests, canForwardStartAsyncAndInfer) { IInferRequest::Ptr req; EXPECT_CALL(*mockExeNetwork.get(), CreateAsyncInferRequestImpl(_, _)).WillOnce( Return(mockAsyncInferRequestInternal)); EXPECT_NO_THROW(exeNetwork->CreateInferRequest(req, &dsc)); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), StartAsyncImpl()).Times(1); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), InferImpl()).Times(1); EXPECT_NO_THROW(req->StartAsync(&dsc)) << dsc.msg; EXPECT_NO_THROW(req->Infer(&dsc)) << dsc.msg; } TEST_F(ExecutableNetworkThreadSafeAsyncOnlyTests, canForwardInferAndStartAsync) { IInferRequest::Ptr req; EXPECT_CALL(*mockExeNetwork.get(), CreateAsyncInferRequestImpl(_, _)).WillOnce( Return(mockAsyncInferRequestInternal)); EXPECT_NO_THROW(exeNetwork->CreateInferRequest(req, &dsc)); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), StartAsyncImpl()).Times(1); EXPECT_CALL(*mockAsyncInferRequestInternal.get(), InferImpl()).Times(1); EXPECT_NO_THROW(req->Infer(&dsc)) << dsc.msg; EXPECT_NO_THROW(req->StartAsync(&dsc)) << dsc.msg; }
c++
code
4,244
743
#include "feasible.h" int main(int argc, char** argv) { Feasible fs; srand (time(NULL)); int i=1; if (argc<3 or argc>4){ cout << "Syntax: fs [input_instance.json][MAX or SUM]" << endl; exit(1); } cout << "input instance: " << argv[1] << endl; fs.input=argv[1]; if (argv[2]==string("MAX")) { fs.use_Grid3D2 = false; fs.minimize_makespan = true; } else if(argv[2]==string("SUM")){ fs.use_Grid3D2 = true; fs.minimize_makespan = false; } else{ cout << "the 3rd argument should be MAX or SUM" << endl; exit(1); } fs.Objective = argv[2]; fs.ReadData(); struct tm curr_tm; time_t curr_time = time(nullptr); localtime_r(&curr_time, &curr_tm); fs.starttime = " "+to_string(curr_tm.tm_mday)+"/"+to_string(curr_tm.tm_mon+1)+"_"; fs.starttime = fs.starttime+to_string(curr_tm.tm_hour)+":"+to_string(curr_tm.tm_min)+":"+to_string(curr_tm.tm_sec); clock_t s=(int) clock(); if(fs.minimize_makespan) fs.Simultaneous(); else if(fs.use_Grid3D2) fs.Simultaneous1(); s=(float)(clock()-s)/CLOCKS_PER_SEC; fs.elapse_t=to_string(s)+" s"; cout<<"Running time "<< fs.elapse_t <<endl; fs.WriteFile(); //fs.WriteVisual(); return 0; }
c++
code
1,282
378
#ifndef _EMD_HAT_SIGNATURE_INTERFACE_HXX #define _EMD_HAT_SIGNATURE_INTERFACE_HXX #include "EMD_DEFS.hpp" #include "emd_hat.hpp" //============================================================================= // This interface is similar to Rubner's interface. See: // http://www.cs.duke.edu/~tomasi/software/emd.htm // With the following changes; // 1. Weights of signature should be of type NUM_T (see emd_hat.hpp) // 2. Return value of the distance function (func) should be of type NUM_T // 3. Return value of the emd_hat_signature_interface function is NUM_T // 4. The function does not return a flow (I may add this in future, if needed) // 5. The function also gets the penalty for extra mass - if you want metric property // should be at least half the diameter of the space (maximum possible distance // between any two points). In Rubner's code this is implicitly 0. // 6. The result is not normalized with the flow. // // To get the same results as Rubner's code you should set extra_mass_penalty to 0, // and divide by the minimum of the sum of the two signature's weights. However, I // suggest not to do this as you lose the metric property and more importantly, in my // experience the performance is better with emd_hat. for more on the difference // between emd and emd_hat, see the paper: // A Linear Time Histogram Metric for Improved SIFT Matching // Ofir Pele, Michael Werman // ECCV 2008 // // To get shorter running time, set the ground distance function (func) to // be a thresholded distance. For example: min( L2, T ). Where T is some threshold. // Note that the running time is shorter with smaller T values. Note also that // thresholding the distance will probably increase accuracy. Finally, a thresholded // metric is also a metric. See paper: // Fast and Robust Earth Mover's Distances // Ofir Pele, Michael Werman // ICCV 2009 // // If you use this code, please cite the papers. //============================================================================= /*****************************************************************************/ /* feature_tt SHOULD BE MODIFIED BY THE USER TO REFLECT THE FEATURE TYPE */ typedef int feature_tt; /*****************************************************************************/ template<typename NUM_T> struct signature_tt { int n; /* Number of features in the signature */ feature_tt* Features; /* Pointer to the features vector */ NUM_T* Weights; /* Pointer to the weights of the features (Changed from Rubner's)*/ }; /// Similar to Rubner's emd interface. /// extra_mass_penalty - it's alpha*maxD_ij in my ECCV paper. If you want metric property /// should be at least half the diameter of the space (maximum possible distance /// between any two points). In Rubner's code this is implicitly 0. /// Default value is -1 which means 1*max_distance_between_bins_of_signatures template<typename NUM_T> NUM_T emd_hat_signature_interface(signature_tt<NUM_T>* Signature1, signature_tt<NUM_T>* Signature2, NUM_T (*func)(feature_tt*, feature_tt*), NUM_T extra_mass_penalty) { std::vector<NUM_T> P(Signature1->n + Signature2->n , 0); std::vector<NUM_T> Q(Signature1->n + Signature2->n , 0); for (int i=0; i<Signature1->n; ++i) { P[i]= Signature1->Weights[i]; } for (int j=0; j<Signature2->n; ++j) { Q[j+Signature1->n]= Signature2->Weights[j]; } std::vector< std::vector<NUM_T> > C(P.size(), std::vector<NUM_T>(P.size(), 0) ); {for (int i=0; i<Signature1->n; ++i) { {for (int j=0; j<Signature2->n; ++j) { NUM_T dist= func( (Signature1->Features+i) , (Signature2->Features+j) ); assert(dist>=0); C[i][j+Signature1->n]= dist; C[j+Signature1->n][i]= dist; }} }} return emd_hat<NUM_T,NO_FLOW>()(P,Q,C, extra_mass_penalty); } // emd_hat_signature_interface #endif // Copyright (c) 2009-2012, Ofir Pele // 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 The Hebrew University of Jerusalem nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
c++
code
5,647
1,285
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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 <HugeCTR/pybind/model.hpp> #include <layer.hpp> #include <layers/add_layer.hpp> #include <layers/batch_norm_layer.hpp> #include <layers/cast_layer.hpp> #include <layers/concat_layer.hpp> #include <layers/dot_product_layer.hpp> #include <layers/dropout_layer.hpp> #include <layers/elementwise_multiply_layer.hpp> #include <layers/elu_layer.hpp> #include <layers/fm_order2_layer.hpp> #include <layers/fully_connected_layer.hpp> #include <layers/fully_connected_layer_half.hpp> #include <layers/fused_fully_connected_layer.hpp> #include <layers/fused_relu_bias_fully_connected_layer.hpp> #include <layers/fused_reshape_concat_general_layer.hpp> #include <layers/fused_reshape_concat_layer.hpp> #include <layers/gather_layer.hpp> #include <layers/gru_layer.hpp> #include <layers/interaction_layer.hpp> #include <layers/matrix_multiply_layer.hpp> #include <layers/multi_cross_layer.hpp> #include <layers/prelu_dice_layer.hpp> #include <layers/reduce_mean_layer.hpp> #include <layers/reduce_sum_layer.hpp> #include <layers/relu_layer.hpp> #include <layers/reshape_layer.hpp> #include <layers/scale_layer.hpp> #include <layers/sigmoid_layer.hpp> #include <layers/slice_layer.hpp> #include <layers/softmax_layer.hpp> #include <layers/sub_layer.hpp> #include <layers/weight_multiply_layer.hpp> #include <regularizers/l1_regularizer.hpp> #include <regularizers/l2_regularizer.hpp> #include <regularizers/no_regularizer.hpp> #ifdef ENABLE_MPI #include <mpi.h> #endif namespace HugeCTR { void save_graph_to_json(nlohmann::json& layer_config_array, std::vector<DenseLayer>& dense_layer_params, std::vector<SparseEmbedding>& sparse_embedding_params, std::vector<Input>& input_params, std::vector<std::shared_ptr<OptParamsPy>>& embedding_opt_params_list, bool use_mixed_precision) { nlohmann::json input_config; input_config["type"] = "Data"; nlohmann::json input_label_config; nlohmann::json input_dense_config; nlohmann::json input_sparse_config_array = nlohmann::json::array(); assert(input_params.size() == 1); Input input_param = input_params[0]; input_label_config["top"] = input_param.label_name; input_label_config["label_dim"] = input_param.label_dim; input_dense_config["top"] = input_param.dense_name; input_dense_config["dense_dim"] = input_param.dense_dim; for (size_t i = 0; i < input_param.data_reader_sparse_param_array.size(); ++i) { nlohmann::json input_sparse_config; input_sparse_config["top"] = input_param.data_reader_sparse_param_array[i].top_name; input_sparse_config["type"] = READER_SPARSE_TYPE_TO_STRING[input_param.data_reader_sparse_param_array[i].type]; input_sparse_config["nnz_per_slot"] = input_param.data_reader_sparse_param_array[i].nnz_per_slot; input_sparse_config["is_fixed_length"] = input_param.data_reader_sparse_param_array[i].is_fixed_length; input_sparse_config["slot_num"] = input_param.data_reader_sparse_param_array[i].slot_num; input_sparse_config_array.push_back(input_sparse_config); } input_config["label"] = input_label_config; input_config["dense"] = input_dense_config; input_config["sparse"] = input_sparse_config_array; layer_config_array.push_back(input_config); for (size_t i = 0; i < sparse_embedding_params.size(); ++i) { nlohmann::json sparse_config; sparse_config["type"] = EMBEDDING_TYPE_TO_STRING[sparse_embedding_params[i].embedding_type]; sparse_config["bottom"] = sparse_embedding_params[i].bottom_name; sparse_config["top"] = sparse_embedding_params[i].sparse_embedding_name; nlohmann::json sparse_hparam_config; sparse_hparam_config["workspace_size_per_gpu_in_mb"] = sparse_embedding_params[i].workspace_size_per_gpu_in_mb; sparse_hparam_config["max_vocabulary_size_global"] = sparse_embedding_params[i].max_vocabulary_size_global; sparse_hparam_config["embedding_vec_size"] = sparse_embedding_params[i].embedding_vec_size; if (sparse_embedding_params[i].combiner == 0) { sparse_hparam_config["combiner"] = "sum"; } else if (sparse_embedding_params[i].combiner == 1) { sparse_hparam_config["combiner"] = "mean"; } else { CK_THROW_(Error_t::WrongInput, "combiner error"); } if (sparse_embedding_params[i].slot_size_array.size() > 0) { sparse_hparam_config["slot_size_array"] = sparse_embedding_params[i].slot_size_array; } if (sparse_embedding_params[i].embedding_type == Embedding_t::HybridSparseEmbedding) { sparse_hparam_config["max_num_frequent_categories"] = sparse_embedding_params[i].hybrid_embedding_param.max_num_frequent_categories; sparse_hparam_config["max_num_infrequent_samples"] = sparse_embedding_params[i].hybrid_embedding_param.max_num_infrequent_samples; sparse_hparam_config["p_dup_max"] = sparse_embedding_params[i].hybrid_embedding_param.p_dup_max; sparse_hparam_config["max_all_reduce_bandwidth"] = sparse_embedding_params[i].hybrid_embedding_param.max_all_reduce_bandwidth; sparse_hparam_config["max_all_to_all_bandwidth"] = sparse_embedding_params[i].hybrid_embedding_param.max_all_to_all_bandwidth; sparse_hparam_config["efficiency_bandwidth_ratio"] = sparse_embedding_params[i].hybrid_embedding_param.efficiency_bandwidth_ratio; sparse_hparam_config["communication_type"] = HE_COMM_TYPE_TO_STRING[sparse_embedding_params[i] .hybrid_embedding_param.communication_type]; sparse_hparam_config["hybrid_embedding_type"] = HE_TYPE_TO_STRING[sparse_embedding_params[i] .hybrid_embedding_param.hybrid_embedding_type]; } sparse_config["sparse_embedding_hparam"] = sparse_hparam_config; nlohmann::json optimizer_config; nlohmann::json optimizer_hparam_config; optimizer_config["update_type"] = embedding_opt_params_list[i]->update_type == Update_t::Global ? "Global" : (embedding_opt_params_list[i]->update_type == Update_t::Local ? "Local" : "LazyGlobal"); switch (embedding_opt_params_list[i]->optimizer) { case Optimizer_t::Adam: { optimizer_config["type"] = "Adam"; optimizer_hparam_config["beta1"] = embedding_opt_params_list[i]->hyperparams.adam.beta1; optimizer_hparam_config["beta2"] = embedding_opt_params_list[i]->hyperparams.adam.beta2; optimizer_hparam_config["epsilon"] = embedding_opt_params_list[i]->hyperparams.adam.epsilon; optimizer_config["adam_hparam"] = optimizer_hparam_config; break; } case Optimizer_t::AdaGrad: { optimizer_config["type"] = "AdaGrad"; optimizer_hparam_config["initial_accu_value"] = embedding_opt_params_list[i]->hyperparams.adagrad.initial_accu_value; optimizer_hparam_config["epsilon"] = embedding_opt_params_list[i]->hyperparams.adagrad.epsilon; optimizer_config["adagrad_hparam"] = optimizer_hparam_config; break; } case Optimizer_t::MomentumSGD: { optimizer_config["type"] = "MomentumSGD"; optimizer_hparam_config["momentum_factor"] = embedding_opt_params_list[i]->hyperparams.momentum.factor; optimizer_config["momentum_sgd_hparam"] = optimizer_hparam_config; break; } case Optimizer_t::Nesterov: { optimizer_config["type"] = "Nesterov"; optimizer_hparam_config["momentum_factor"] = embedding_opt_params_list[i]->hyperparams.nesterov.mu; optimizer_config["nesterov_hparam"] = optimizer_hparam_config; break; } case Optimizer_t::SGD: { optimizer_config["type"] = "SGD"; optimizer_hparam_config["atomic_update"] = embedding_opt_params_list[i]->hyperparams.sgd.atomic_update; optimizer_config["sgd_hparam"] = optimizer_hparam_config; break; } default: { assert(!"Error: no such optimizer && should never get here!"); } } sparse_config["optimizer"] = optimizer_config; layer_config_array.push_back(sparse_config); } auto& layer_type_to_string = use_mixed_precision ? LAYER_TYPE_TO_STRING_MP : LAYER_TYPE_TO_STRING; for (size_t i = 0; i < dense_layer_params.size(); ++i) { nlohmann::json layer_config; layer_config["type"] = layer_type_to_string[dense_layer_params[i].layer_type]; if (dense_layer_params[i].bottom_names.size() == 1) { layer_config["bottom"] = dense_layer_params[i].bottom_names[0]; } else { layer_config["bottom"] = dense_layer_params[i].bottom_names; } if (dense_layer_params[i].top_names.size() == 1) { layer_config["top"] = dense_layer_params[i].top_names[0]; } else { layer_config["top"] = dense_layer_params[i].top_names; } switch (dense_layer_params[i].layer_type) { case Layer_t::BatchNorm: { nlohmann::json bn_param_config; bn_param_config["factor"] = dense_layer_params[i].factor; bn_param_config["eps"] = dense_layer_params[i].eps; if (dense_layer_params[i].gamma_init_type != Initializer_t::Default) { bn_param_config["gamma_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].gamma_init_type]; } if (dense_layer_params[i].beta_init_type != Initializer_t::Default) { bn_param_config["beta_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].beta_init_type]; } layer_config["bn_param"] = bn_param_config; break; } case Layer_t::Dropout: { layer_config["rate"] = dense_layer_params[i].dropout_rate; break; } case Layer_t::ELU: { nlohmann::json elu_param_config; elu_param_config["alpha"] = dense_layer_params[i].elu_alpha; layer_config["elu_param"] = elu_param_config; break; } case Layer_t::FusedInnerProduct: { nlohmann::json fc_param_config; fc_param_config["num_output"] = dense_layer_params[i].num_output; if (dense_layer_params[i].weight_init_type != Initializer_t::Default) { fc_param_config["weight_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].weight_init_type]; } if (dense_layer_params[i].bias_init_type != Initializer_t::Default) { fc_param_config["bias_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].bias_init_type]; } layer_config["position"] = FC_POSITION_TO_STRING[dense_layer_params[i].pos_type]; layer_config["activation"] = FC_ACTIVATION_TO_STRING[dense_layer_params[i].act_type]; layer_config["fc_param"] = fc_param_config; break; } case Layer_t::InnerProduct: { nlohmann::json fc_param_config; fc_param_config["num_output"] = dense_layer_params[i].num_output; if (dense_layer_params[i].weight_init_type != Initializer_t::Default) { fc_param_config["weight_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].weight_init_type]; } if (dense_layer_params[i].bias_init_type != Initializer_t::Default) { fc_param_config["bias_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].bias_init_type]; } layer_config["fc_param"] = fc_param_config; break; } case Layer_t::MultiCross: { nlohmann::json mc_param_config; mc_param_config["num_layers"] = dense_layer_params[i].num_layers; if (dense_layer_params[i].weight_init_type != Initializer_t::Default) { mc_param_config["weight_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].weight_init_type]; } if (dense_layer_params[i].bias_init_type != Initializer_t::Default) { mc_param_config["bias_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].bias_init_type]; } layer_config["mc_param"] = mc_param_config; break; } case Layer_t::Reshape: { if (dense_layer_params[i].selected) { layer_config["selected"] = dense_layer_params[i].selected_slots; } else { layer_config["leading_dim"] = dense_layer_params[i].leading_dim; layer_config["time_step"] = dense_layer_params[i].time_step; } break; } case Layer_t::Slice: { layer_config["ranges"] = dense_layer_params[i].ranges; break; } case Layer_t::WeightMultiply: { layer_config["weight_dims"] = dense_layer_params[i].weight_dims; if (dense_layer_params[i].weight_init_type != Initializer_t::Default) { layer_config["weight_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].weight_init_type]; } break; } case Layer_t::FmOrder2: { layer_config["out_dim"] = dense_layer_params[i].out_dim; break; } case Layer_t::ReduceSum: { layer_config["axis"] = dense_layer_params[i].axis; break; } case Layer_t::ReduceMean: { layer_config["axis"] = dense_layer_params[i].axis; break; } case Layer_t::Gather: { layer_config["indices"] = dense_layer_params[i].indices; break; } case Layer_t::GRU: { nlohmann::json gru_param_config; gru_param_config["num_output"] = dense_layer_params[i].num_output; gru_param_config["batchsize"] = dense_layer_params[i].batchsize; gru_param_config["SeqLength"] = dense_layer_params[i].SeqLength; gru_param_config["vector_size"] = dense_layer_params[i].vector_size; if (dense_layer_params[i].weight_init_type != Initializer_t::Default) { gru_param_config["weight_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].weight_init_type]; } if (dense_layer_params[i].bias_init_type != Initializer_t::Default) { gru_param_config["bias_init"] = INITIALIZER_TYPE_TO_STRING[dense_layer_params[i].bias_init_type]; } layer_config["gru_param"] = gru_param_config; break; } case Layer_t::PReLU_Dice: { nlohmann::json prelu_dice_param_config; prelu_dice_param_config["alpha"] = dense_layer_params[i].elu_alpha; prelu_dice_param_config["eps"] = dense_layer_params[i].eps; layer_config["prelu_dice_param"] = prelu_dice_param_config; break; } case Layer_t::Scale: { nlohmann::json scale_param_config; scale_param_config["axis"] = dense_layer_params[i].axis; scale_param_config["factor"] = dense_layer_params[i].factor; layer_config["scale_param"] = scale_param_config; break; } case Layer_t::MultiCrossEntropyLoss: { if (dense_layer_params[i].target_weight_vec.size() > 0) { layer_config["target_weight"] = dense_layer_params[i].target_weight_vec; } if (dense_layer_params[i].use_regularizer) { layer_config["regularizer"] = dense_layer_params[i].regularizer_type == Regularizer_t::L1 ? "L1" : "L2"; layer_config["lambda"] = dense_layer_params[i].lambda; } break; } case Layer_t::BinaryCrossEntropyLoss: { if (dense_layer_params[i].use_regularizer) { layer_config["regularizer"] = dense_layer_params[i].regularizer_type == Regularizer_t::L1 ? "L1" : "L2"; layer_config["lambda"] = dense_layer_params[i].lambda; } break; } case Layer_t::CrossEntropyLoss: { if (dense_layer_params[i].use_regularizer) { layer_config["regularizer"] = dense_layer_params[i].regularizer_type == Regularizer_t::L1 ? "L1" : "L2"; layer_config["lambda"] = dense_layer_params[i].lambda; } break; } default: { break; } } layer_config_array.push_back(layer_config); } } DenseLayer get_dense_layer_from_json(const nlohmann::json& j_dense_layer) { Layer_t layer_type; auto layer_type_name = get_value_from_json<std::string>(j_dense_layer, "type"); if (!find_item_in_map(layer_type, layer_type_name, LAYER_TYPE_MAP) && !find_item_in_map(layer_type, layer_type_name, LAYER_TYPE_MAP_MP)) { CK_THROW_(Error_t::WrongInput, "No such layer: " + layer_type_name); } auto bottom = get_json(j_dense_layer, "bottom"); auto top = get_json(j_dense_layer, "top"); std::vector<std::string> bottom_names = get_layer_names(bottom); std::vector<std::string> top_names = get_layer_names(top); DenseLayer dense_layer = DenseLayer(layer_type, bottom_names, top_names); switch (layer_type) { case Layer_t::BatchNorm: { auto j_bn_hparam = get_json(j_dense_layer, "bn_param"); auto factor = get_value_from_json<float>(j_bn_hparam, "factor"); auto eps = get_value_from_json<float>(j_bn_hparam, "eps"); dense_layer.factor = factor; dense_layer.eps = eps; if (has_key_(j_bn_hparam, "gamma_init")) { const auto gamma_init_name = get_value_from_json<std::string>(j_bn_hparam, "gamma_init"); Initializer_t gamma_init_type; if (find_item_in_map(gamma_init_type, gamma_init_name, INITIALIZER_TYPE_MAP)) { dense_layer.gamma_init_type = gamma_init_type; } else { CK_THROW_(Error_t::WrongInput, "No such initializer: " + gamma_init_name); } } if (has_key_(j_bn_hparam, "beta_init")) { const auto beta_init_name = get_value_from_json<std::string>(j_bn_hparam, "beta_init"); Initializer_t beta_init_type; if (find_item_in_map(beta_init_type, beta_init_name, INITIALIZER_TYPE_MAP)) { dense_layer.beta_init_type = beta_init_type; } else { CK_THROW_(Error_t::WrongInput, "No such initializer: " + beta_init_name); } } break; } case Layer_t::Dropout: { auto rate_it = j_dense_layer.find("rate"); if (rate_it != j_dense_layer.end()) { dense_layer.dropout_rate = rate_it->get<float>(); } break; } case Layer_t::ELU: { auto j_elu_hparam = get_json(j_dense_layer, "elu_param"); auto alpha = get_value_from_json<float>(j_elu_hparam, "alpha"); dense_layer.elu_alpha = alpha; break; } case Layer_t::FusedInnerProduct: { auto j_fc_param = get_json(j_dense_layer, "fc_param"); if (has_key_(j_fc_param, "weight_init")) { const auto weight_init_name = get_value_from_json<std::string>(j_fc_param, "weight_init"); Initializer_t weight_init_type; if (find_item_in_map(weight_init_type, weight_init_name, INITIALIZER_TYPE_MAP)) { dense_layer.weight_init_type = weight_init_type; } else { CK_THROW_(Error_t::WrongInput, "No such initializer: " + weight_init_name); } } if (has_key_(j_fc_param, "bias_init")) { const auto bias_init_name = get_value_from_json<std::string>(j_fc_param, "bias_init"); Initializer_t bias_init_type; if (find_item_in_map(bias_init_type, bias_init_name, INITIALIZER_TYPE_MAP)) { den
c++
code
20,000
3,462
#include <iostream> using namespace std; int main () { int statical; int *statically = &statical; int *dynamically = new int; *statically = 10; *dynamically = 15; cout << "The value of the statically allocated variable: " << *statically << ", and the address: " << statically << endl; cout << "The value of the dynamically allocated variable: " << *dynamically << ", and the address: " << dynamically << endl; delete dynamically; return 0; }
c++
code
504
114
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdbusmodel.h" #include <QtCore/qvector.h> #include <QtCore/QDebug> #include <QtXml/QDomDocument> #include <QtDBus/QDBusObjectPath> #include <QtDBus/QDBusInterface> #include <QtDBus/QDBusReply> struct QDBusItem { inline QDBusItem(QDBusModel::Type aType, const QString &aName, QDBusItem *aParent = 0) : type(aType), parent(aParent), isPrefetched(type != QDBusModel::PathItem), name(aName) {} inline ~QDBusItem() { qDeleteAll(children); } QString path() const { Q_ASSERT(type == QDBusModel::PathItem); QString s; const QDBusItem *item = this; while (item) { s.prepend(item->name); item = item->parent; } if (s.length() > 1) s.chop(1); // remove tailing slash return s; } QDBusModel::Type type; QDBusItem *parent; QVector<QDBusItem *> children; bool isPrefetched; QString name; QString caption; QString typeSignature; }; QDomDocument QDBusModel::introspect(const QString &path) { QDomDocument doc; QDBusInterface iface(service, path, QLatin1String("org.freedesktop.DBus.Introspectable"), c); if (!iface.isValid()) { QDBusError err(iface.lastError()); emit busError(QString::fromLatin1("Cannot introspect object %1 at %2:\n %3 (%4)\n").arg(path).arg( service).arg(err.name()).arg(err.message())); return doc; } QDBusReply<QString> xml = iface.call(QLatin1String("Introspect")); if (!xml.isValid()) { QDBusError err(xml.error()); if (err.isValid()) { emit busError(QString::fromLatin1("Call to object %1 at %2:\n %3 (%4) failed\n").arg( path).arg(service).arg(err.name()).arg(err.message())); } else { emit busError(QString::fromLatin1("Invalid XML received from object %1 at %2\n").arg( path).arg(service)); } return doc; } doc.setContent(xml); return doc; } void QDBusModel::addMethods(QDBusItem *parent, const QDomElement &iface) { Q_ASSERT(parent); QDomElement child = iface.firstChildElement(); while (!child.isNull()) { QDBusItem *item = 0; if (child.tagName() == QLatin1String("method")) { item = new QDBusItem(QDBusModel::MethodItem, child.attribute(QLatin1String("name")), parent); item->caption = QLatin1String("Method: ") + item->name; //get "type" from <arg> where "direction" is "in" QDomElement n = child.firstChildElement(); while (!n.isNull()) { if (n.attribute(QLatin1String("direction")) == QLatin1String("in")) item->typeSignature += n.attribute(QLatin1String("type")); n = n.nextSiblingElement(); } } else if (child.tagName() == QLatin1String("signal")) { item = new QDBusItem(QDBusModel::SignalItem, child.attribute(QLatin1String("name")), parent); item->caption = QLatin1String("Signal: ") + item->name; } else if (child.tagName() == QLatin1String("property")) { item = new QDBusItem(QDBusModel::PropertyItem, child.attribute(QLatin1String("name")), parent); item->caption = QLatin1String("Property: ") + item->name; } else { qDebug() << "addMethods: unknown tag:" << child.tagName(); } if (item) parent->children.append(item); child = child.nextSiblingElement(); } } void QDBusModel::addPath(QDBusItem *parent) { Q_ASSERT(parent); QString path = parent->path(); QDomDocument doc = introspect(path); QDomElement node = doc.documentElement(); QDomElement child = node.firstChildElement(); while (!child.isNull()) { if (child.tagName() == QLatin1String("node")) { QDBusItem *item = new QDBusItem(QDBusModel::PathItem, child.attribute(QLatin1String("name")) + QLatin1Char('/'), parent); parent->children.append(item); addMethods(item, child); } else if (child.tagName() == QLatin1String("interface")) { QDBusItem *item = new QDBusItem(QDBusModel::InterfaceItem, child.attribute(QLatin1String("name")), parent); parent->children.append(item); addMethods(item, child); } else { qDebug() << "addPath: Unknown tag name:" << child.tagName(); } child = child.nextSiblingElement(); } parent->isPrefetched = true; } QDBusModel::QDBusModel(const QString &aService, const QDBusConnection &connection) : service(aService), c(connection), root(0) { root = new QDBusItem(QDBusModel::PathItem, QLatin1String("/")); } QDBusModel::~QDBusModel() { delete root; } QModelIndex QDBusModel::index(int row, int column, const QModelIndex &parent) const { const QDBusItem *item = static_cast<QDBusItem *>(parent.internalPointer()); if (!item) item = root; if (column != 0 || row < 0 || row >= item->children.count()) return QModelIndex(); return createIndex(row, 0, item->children.at(row)); } QModelIndex QDBusModel::parent(const QModelIndex &child) const { QDBusItem *item = static_cast<QDBusItem *>(child.internalPointer()); if (!item || !item->parent || !item->parent->parent) return QModelIndex(); return createIndex(item->parent->parent->children.indexOf(item->parent), 0, item->parent); } int QDBusModel::rowCount(const QModelIndex &parent) const { QDBusItem *item = static_cast<QDBusItem *>(parent.internalPointer()); if (!item) item = root; if (!item->isPrefetched) const_cast<QDBusModel *>(this)->addPath(item); return item->children.count(); } int QDBusModel::columnCount(const QModelIndex &) const { return 1; } QVariant QDBusModel::data(const QModelIndex &index, int role) const { const QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); if (!item) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); return item->caption.isEmpty() ? item->name : item->caption; } QVariant QDBusModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole || orientation == Qt::Vertical || section != 0) return QVariant(); return QLatin1String("Methods"); } QDBusModel::Type QDBusModel::itemType(const QModelIndex &index) const { const QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); return item ? item->type : PathItem; } void QDBusModel::refresh(const QModelIndex &aIndex) { QModelIndex index = aIndex; while (index.isValid() && static_cast<QDBusItem *>(index.internalPointer())->type != PathItem) { index = index.parent(); } QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); if (!item) item = root; if (!item->children.isEmpty()) { beginRemoveRows(index, 0, item->children.count() - 1); qDeleteAll(item->children); item->children.clear(); endRemoveRows(); } addPath(item); if (!item->children.isEmpty()) { beginInsertRows(index, 0, item->children.count() - 1); endInsertRows(); } } QString QDBusModel::dBusPath(const QModelIndex &aIndex) const { QModelIndex index = aIndex; while (index.isValid() && static_cast<QDBusItem *>(index.internalPointer())->type != PathItem) { index = index.parent(); } QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); if (!item) item = root; return item->path(); } QString QDBusModel::dBusInterface(const QModelIndex &index) const { QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); if (!item) return QString(); if (item->type == InterfaceItem) return item->name; if (item->parent && item->parent->type == InterfaceItem) return item->parent->name; return QString(); } QString QDBusModel::dBusMethodName(const QModelIndex &index) const { QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); return item ? item->name : QString(); } QString QDBusModel::dBusTypeSignature(const QModelIndex &index) const { QDBusItem *item = static_cast<QDBusItem *>(index.internalPointer()); return item ? item->typeSignature : QString(); } QModelIndex QDBusModel::findObject(const QDBusObjectPath &objectPath) { QStringList path = objectPath.path().split(QLatin1Char('/'), QString::SkipEmptyParts); QDBusItem *item = root; int childIdx = -1; while (item && !path.isEmpty()) { const QString branch = path.takeFirst() + QLatin1Char('/'); childIdx = -1; // do a linear search over all the children for (int i = 0; i < item->children.count(); ++i) { QDBusItem *child = item->children.at(i); if (child->type == PathItem && child->name == branch) { item = child; childIdx = i; // prefetch the found branch if (!item->isPrefetched) addPath(item); break; } } // branch not found - bail out if (childIdx == -1) return QModelIndex(); } // found the right item if (childIdx != -1 && item && path.isEmpty()) return createIndex(childIdx, 0, item); return QModelIndex(); }
c++
code
10,876
2,635
/* A producer continuously produces a stream of characters. There are multiple consumer threads which read the chars and match to one of known strings and increment the counter for that pattern. Write the consumer function. Show how you will synchronize and maintain parallelism. Ex: Producer: abcdegabccaabbaacv ...... Known strings[] = {"ab", "aa", "fff" ... } patternMatchCount[] = {3, 2, 0 ... } */ /* Solution: 1) Clarification of patternMatchcount is required: do overlaping patterns count or not: e.g. in "AAA" how many times does "AA" occure 1 or 2 times? assumption: 2, overlaping counts 2) The syncronization can depend on the pattern matching approach: a) The use of brute force or Rabin-Karp requires to hold a buffer of length of the pattern to verify if it's a match. Such a buffer can be held by each consumer-thread which can be efficient in terms of synchronization but inefficient in terms of memory usage (if there are a lot of patterns) b) If it's automaton based, no buffer is required. Automaton based is preferable, but much more complicated to implement (I doubt it is expected to derive the algorithm in an interview...) 3) For simplicity I would assume the first implementation is that each consumer has his own buffer and later on I would correct this with an automaton based approach. 4) Synchronization in this case is now, the producer has to push a character to all consumers, this can be done using a waitable queue. The waitable queue will be inefficient in terms of syncrhonization needed and because it may dynamically create items, thus a critical section is held over a heap allocation etc... It could be improved with a lockless buffer which is going to be quite tricky to implement in a non-managed language such as C++ if multicore support is required. If you're not a hard core C++ low level programmer with experience in writing drivers and lockless stuff it's maybe a good idea to point out that you wont get it error-free and efficient. 5) An other thing to consider is how the system shuts down once the producer decides to terminate (reaches the end of the input stream) Here the rather messy code in C++ 11 */ #include <memory> #include <iostream> #include <string> #include <queue> #include <thread> #include <mutex> #include <condition_variable> using namespace std; class WaitableQueue { private: mutex mutex_; condition_variable signal_; queue<char> queue_; public: void push(char item) { { unique_lock<mutex> cs(mutex_); queue_.push(item); } signal_.notify_one(); } char pop() { unique_lock<mutex> cs(mutex_); signal_.wait(cs, [&]() { return queue_.size() > 0; }); char result = queue_.front(); queue_.pop(); return result; } }; class Consumer { private: WaitableQueue queue_; string pattern_; string buffer_; int bufferEnd_; int counter_; thread thread_; public: Consumer(const string &pattern) : counter_(0), bufferEnd_(0), pattern_(pattern) { thread_ = thread([&] { while (true) { char item = queue_.pop(); if (item == '\0') break; // end signal if (matchNext(item)) counter_++; } }); } WaitableQueue *getQueue() { return &queue_; } int getCounter() const { return counter_; } string getPattern() const { return pattern_; } void join() { thread_.join(); } private: bool matchNext(char next) { // this match code is inefficient, improvements possible // by using Rabin-Karp or an automaton based approach int m = pattern_.length(); if (buffer_.length() < bufferEnd_ + 1) buffer_.append(1, next); else buffer_[bufferEnd_] = next; bufferEnd_ = (bufferEnd_ + 1) % m; bool match = buffer_.length() == m; for (int i = 0; i < m && match; ++i) match = buffer_[(bufferEnd_ + i) % m] == pattern_[i]; return match; } }; class Producer { private: vector<WaitableQueue *> queues_; string input_; thread thread_; public: Producer(const vector<WaitableQueue *> &queues, const string &input) : queues_(queues), input_(input) { thread_ = thread([&] { // send input for (auto ch : input_) { for (auto co : queues) co->push(ch); } // signal end of input for (auto co : queues) co->push('\0'); }); } void join() { thread_.join(); } }; int main() { // create consumers vector<Consumer *> consumers({new Consumer("ab"), new Consumer("aa"), new Consumer("ffff")}); // get queues from consumers vector<WaitableQueue *> queues; for (auto &co : consumers) queues.push_back(co->getQueue()); // create producer Producer p(queues, "abcdegabccaabbaacv"); // wait for producer p.join(); // wait and print result of consumer for (auto &co : consumers) { co->join(); cout << "pattern: " << co->getPattern() << " count: " << co->getCounter() << endl; } }
c++
code
5,538
1,138
/* * ghex-org * * Copyright (c) 2014-2021, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include <hwmalloc/detail/pool.hpp> #include <vector> namespace hwmalloc { namespace detail { template<typename Context> class fixed_size_heap { public: using pool_type = pool<Context>; using block_type = typename pool_type::block_type; private: Context* m_context; std::size_t m_block_size; std::size_t m_segment_size; bool m_never_free; std::size_t m_num_reserve_segments; std::vector<std::unique_ptr<pool_type>> m_pools; #if HWMALLOC_ENABLE_DEVICE std::size_t m_num_devices; std::vector<std::unique_ptr<pool_type>> m_device_pools; #endif public: fixed_size_heap(Context* context, std::size_t block_size, std::size_t segment_size, bool never_free, std::size_t num_reserve_segments) : m_context(context) , m_block_size(block_size) , m_segment_size(segment_size) , m_never_free(never_free) , m_num_reserve_segments{num_reserve_segments} , m_pools(numa().num_host_nodes()) #if HWMALLOC_ENABLE_DEVICE , m_num_devices{(std::size_t)get_num_devices()} , m_device_pools(numa().num_host_nodes() * m_num_devices) #endif { for (unsigned int i = 0; i < numa().num_host_nodes(); ++i) { m_pools[i] = std::make_unique<pool_type>(m_context, m_block_size, m_segment_size, i, m_never_free, m_num_reserve_segments); #if HWMALLOC_ENABLE_DEVICE for (unsigned int j = 0; j < m_num_devices; ++j) { m_device_pools[i * m_num_devices + j] = std::make_unique<pool_type>(m_context, m_block_size, m_segment_size, i, (int)j, m_never_free, m_num_reserve_segments); } #endif } } fixed_size_heap(fixed_size_heap const&) = delete; fixed_size_heap(fixed_size_heap&&) = default; block_type allocate(std::size_t numa_node) { return m_pools[numa_node]->allocate(); } #if HWMALLOC_ENABLE_DEVICE block_type allocate(std::size_t numa_node, int device_id) { return m_device_pools[numa_node * m_num_devices + device_id]->allocate(); } #endif void free(block_type const& b) { b.release(); } }; } // namespace detail } // namespace hwmalloc
c++
code
2,544
459
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2019 Nicholas Frechette & Animation Compression Library contributors // // 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 <catch2/catch.hpp> #include <acl/core/iterator.h> #include <acl/core/memory_utils.h> #include <cstdint> using namespace acl; TEST_CASE("iterator", "[core][iterator]") { constexpr uint32_t num_items = 3; uint32_t items[num_items]; auto i = iterator<uint32_t>(items, num_items); SECTION("mutable returns correct type") { CHECK(std::is_same<uint32_t*, decltype(i.begin())>::value); CHECK(std::is_same<uint32_t*, decltype(i.end())>::value); } SECTION("const returns correct type") { auto ci = const_iterator<uint32_t>(items, num_items); CHECK(std::is_same<const uint32_t*, decltype(ci.begin())>::value); CHECK(std::is_same<const uint32_t*, decltype(ci.end())>::value); } SECTION("bounds are correct") { CHECK(i.begin() == items + 0); CHECK(i.end() == items + num_items); } }
c++
code
2,166
472
///////////////////////////////////////////////////////////////////////////// // // File : QHoverEvent.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:01:59 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <wchar.h> #include <qtc_wrp_core.h> #include <qtc_wrp_gui.h> #include <qtc_subclass.h> #ifndef dhclassheader #define dhclassheader #include <qpointer.h> #include <dynamicqhandler.h> #include <DhOther_gui.h> #include <DhAutohead_gui.h> #endif extern "C" { QTCEXPORT(void*,qtc_QHoverEvent)(void* x1) { QHoverEvent*tr = new QHoverEvent((const QHoverEvent&)(*(QHoverEvent*)x1)); return (void*) tr; } QTCEXPORT(void*,qtc_QHoverEvent1)(long x1, void* x2, void* x3) { QHoverEvent*tr = new QHoverEvent((QEvent::Type)x1, (const QPoint&)(*(QPoint*)x2), (const QPoint&)(*(QPoint*)x3)); return (void*) tr; } QTCEXPORT(void*,qtc_QHoverEvent2)(long x1, int x2_x, int x2_y, int x3_x, int x3_y) { QPoint tx2(x2_x, x2_y); QPoint tx3(x3_x, x3_y); QHoverEvent*tr = new QHoverEvent((QEvent::Type)x1, tx2, tx3); return (void*) tr; } QTCEXPORT(void*,qtc_QHoverEvent_oldPos)(void* x0) { return (void*) &((QHoverEvent*)x0)->oldPos(); } QTCEXPORT(void,qtc_QHoverEvent_oldPos_qth)(void* x0, int* _ret_x, int* _ret_y) { QPoint tc = ((QHoverEvent*)x0)->oldPos(); *_ret_x = tc.x(); *_ret_y = tc.y(); return; } QTCEXPORT(void*,qtc_QHoverEvent_pos)(void* x0) { return (void*) &((QHoverEvent*)x0)->pos(); } QTCEXPORT(void,qtc_QHoverEvent_pos_qth)(void* x0, int* _ret_x, int* _ret_y) { QPoint tc = ((QHoverEvent*)x0)->pos(); *_ret_x = tc.x(); *_ret_y = tc.y(); return; } QTCEXPORT(void,qtc_QHoverEvent_finalizer)(void* x0) { delete ((QHoverEvent*)x0); } QTCEXPORT(void*,qtc_QHoverEvent_getFinalizer)() { return (void*)(&qtc_QHoverEvent_finalizer); } QTCEXPORT(void,qtc_QHoverEvent_delete)(void* x0) { delete((QHoverEvent*)x0); } }
c++
code
2,101
531
/* Masstree * Eddie Kohler, Yandong Mao, Robert Morris * Copyright (c) 2012-2014 President and Fellows of Harvard College * Copyright (c) 2012-2014 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Masstree LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Masstree LICENSE file; the license in that file * is legally binding. */ #ifndef MASSTREE_TCURSOR_HH #define MASSTREE_TCURSOR_HH 1 #include "local_vector.hh" #include "masstree_key.hh" #include "masstree_struct.hh" namespace Masstree { template <typename P> struct gc_layer_rcu_callback; template <typename P> class unlocked_tcursor { public: typedef typename P::value_type value_type; typedef key<typename P::ikey_type> key_type; typedef typename P::threadinfo_type threadinfo; typedef typename leaf<P>::nodeversion_type nodeversion_type; typedef typename nodeversion_type::value_type nodeversion_value_type; typedef typename leaf<P>::permuter_type permuter_type; inline unlocked_tcursor(const basic_table<P>& table, Str str) : ka_(str), lv_(leafvalue<P>::make_empty()), root_(table.root()) {} inline unlocked_tcursor(basic_table<P>& table, Str str) : ka_(str), lv_(leafvalue<P>::make_empty()), root_(table.fix_root()) {} inline unlocked_tcursor(const basic_table<P>& table, const char* s, int len) : ka_(s, len), lv_(leafvalue<P>::make_empty()), root_(table.root()) {} inline unlocked_tcursor(basic_table<P>& table, const char* s, int len) : ka_(s, len), lv_(leafvalue<P>::make_empty()), root_(table.fix_root()) {} inline unlocked_tcursor(const basic_table<P>& table, const unsigned char* s, int len) : ka_(reinterpret_cast<const char*>(s), len), lv_(leafvalue<P>::make_empty()), root_(table.root()) {} inline unlocked_tcursor(basic_table<P>& table, const unsigned char* s, int len) : ka_(reinterpret_cast<const char*>(s), len), lv_(leafvalue<P>::make_empty()), root_(table.fix_root()) {} inline unlocked_tcursor() {} bool find_unlocked(threadinfo& ti); inline value_type value() const { return lv_.value(); } inline leaf<P>* node() const { return n_; } inline permuter_type permutation() const { return perm_; } inline int compare_key(const key_type& a, int bp) const { return n_->compare_key(a, bp); } inline nodeversion_value_type full_version_value() const { static_assert(int(nodeversion_type::traits_type::top_stable_bits) >= int(leaf<P>::permuter_type::size_bits), "not enough bits to add size to version"); return (v_.version_value() << leaf<P>::permuter_type::size_bits) + perm_.size(); } public: leaf<P>* n_; key_type ka_; typename leaf<P>::nodeversion_type v_; permuter_type perm_; leafvalue<P> lv_; const node_base<P>* root_; }; template <typename P> class tcursor { public: typedef node_base<P> node_type; typedef leaf<P> leaf_type; typedef internode<P> internode_type; typedef typename P::value_type value_type; typedef leafvalue<P> leafvalue_type; typedef typename leaf_type::permuter_type permuter_type; typedef typename P::ikey_type ikey_type; typedef key<ikey_type> key_type; typedef typename leaf<P>::nodeversion_type nodeversion_type; typedef typename nodeversion_type::value_type nodeversion_value_type; typedef typename P::threadinfo_type threadinfo; static constexpr int new_nodes_size = 1; // unless we make a new trie newnodes will have at most 1 item typedef local_vector<std::pair<leaf_type*, nodeversion_value_type>, new_nodes_size> new_nodes_type; tcursor(basic_table<P>& table, Str str) : ka_(str), root_(table.fix_root()) {} tcursor(basic_table<P>& table, const char* s, int len) : ka_(s, len), root_(table.fix_root()) {} tcursor(basic_table<P>& table, const unsigned char* s, int len) : ka_(reinterpret_cast<const char*>(s), len), root_(table.fix_root()) {} tcursor(node_base<P>* root, const char* s, int len) : ka_(s, len), root_(root) {} tcursor(node_base<P>* root, const unsigned char* s, int len) : ka_(reinterpret_cast<const char*>(s), len), root_(root) {} inline bool has_value() const { return kx_.p >= 0; } inline value_type& value() const { return n_->lv_[kx_.p].value(); } inline bool is_first_layer() const { return !ka_.is_shifted(); } inline leaf<P>* node() const { return n_; } inline kvtimestamp_t node_timestamp() const { return n_->node_ts_; } inline kvtimestamp_t& node_timestamp() { return n_->node_ts_; } inline leaf_type* original_node() const { return original_n_; } inline nodeversion_value_type original_version_value() const { return original_v_; } inline nodeversion_value_type updated_version_value() const { return updated_v_; } inline const new_nodes_type& new_nodes() const { return new_nodes_; } inline bool find_locked(threadinfo& ti); inline bool find_insert(threadinfo& ti); inline void finish(int answer, threadinfo& ti); inline nodeversion_value_type previous_full_version_value() const; inline nodeversion_value_type next_full_version_value(int state) const; public: leaf_type* n_; key_type ka_; key_indexed_position kx_; node_base<P>* root_; int state_; leaf_type* original_n_; nodeversion_value_type original_v_; nodeversion_value_type updated_v_; new_nodes_type new_nodes_; inline node_type* reset_retry() { ka_.unshift_all(); return root_; } bool make_new_layer(threadinfo& ti); bool make_split(threadinfo& ti); inline void finish_insert(); inline bool finish_remove(threadinfo& ti); static void collapse(internode_type* p, ikey_type ikey, node_type* root, Str prefix, threadinfo& ti); /** Remove @a leaf from the Masstree rooted at @a rootp. * @param prefix String defining the path to the tree containing this leaf. * If removing a leaf in layer 0, @a prefix is empty. * If removing, for example, the node containing key "01234567ABCDEF" in the * layer-1 tree * rooted at "01234567", then @a prefix should equal "01234567". */ static bool remove_leaf(leaf_type* leaf, node_type* root, Str prefix, threadinfo& ti); bool gc_layer(threadinfo& ti); friend struct gc_layer_rcu_callback<P>; }; template <typename P> inline typename tcursor<P>::nodeversion_value_type tcursor<P>::previous_full_version_value() const { static_assert(int(nodeversion_type::traits_type::top_stable_bits) >= int(leaf<P>::permuter_type::size_bits), "not enough bits to add size to version"); return (n_->unlocked_version_value() << leaf<P>::permuter_type::size_bits) + n_->size(); } template <typename P> inline typename tcursor<P>::nodeversion_value_type tcursor<P>::next_full_version_value(int state) const { static_assert(int(nodeversion_type::traits_type::top_stable_bits) >= int(leaf<P>::permuter_type::size_bits), "not enough bits to add size to version"); typename node_base<P>::nodeversion_type v(*n_); v.unlock(); nodeversion_value_type result = (v.version_value() << leaf<P>::permuter_type::size_bits) + n_->size(); if (state < 0 && (state_ & 1)) return result - 1; else if (state > 0 && state_ == 2) return result + 1; else return result; } } // namespace Masstree #endif
c++
code
7,916
1,744
/* * Vulkan Example - Animated gears using multiple uniform buffers * * See readme.md for details * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkangear.h" int32_t VulkanGear::newVertex(std::vector<Vertex> *vBuffer, float x, float y, float z, const glm::vec3& normal) { Vertex v(glm::vec3(x, y, z), normal, color); vBuffer->push_back(v); return (int32_t)(vBuffer->size() - 1); } void VulkanGear::newFace(std::vector<uint32_t> *iBuffer, int a, int b, int c) { iBuffer->push_back(a); iBuffer->push_back(b); iBuffer->push_back(c); } VulkanGear::VulkanGear(VkDevice device, VulkanExampleBase *example) { this->device = device; this->exampleBase = example; } VulkanGear::~VulkanGear() { // Clean up vulkan resources vkDestroyBuffer(device, uniformData.buffer, nullptr); vkFreeMemory(device, uniformData.memory, nullptr); vkDestroyBuffer(device, vertexBuffer.buf, nullptr); vkFreeMemory(device, vertexBuffer.mem, nullptr); vkDestroyBuffer(device, indexBuffer.buf, nullptr); vkFreeMemory(device, indexBuffer.mem, nullptr); } void VulkanGear::generate(GearInfo *gearinfo, VkQueue queue) { this->color = gearinfo->color; this->pos = gearinfo->pos; this->rotOffset = gearinfo->rotOffset; this->rotSpeed = gearinfo->rotSpeed; std::vector<Vertex> vBuffer; std::vector<uint32_t> iBuffer; int i; // , j; double r0, r1, r2; double ta, da; double u1, v1, u2, v2, len; double cos_ta, cos_ta_1da, cos_ta_2da, cos_ta_3da, cos_ta_4da; double sin_ta, sin_ta_1da, sin_ta_2da, sin_ta_3da, sin_ta_4da; int32_t ix0, ix1, ix2, ix3, ix4, ix5; r0 = gearinfo->innerRadius; r1 = gearinfo->outerRadius - gearinfo->toothDepth / 2.0; r2 = gearinfo->outerRadius + gearinfo->toothDepth / 2.0; da = 2.0 * M_PI / gearinfo->numTeeth / 4.0; glm::vec3 normal; for (i = 0; i < gearinfo->numTeeth; i++) { ta = i * 2.0 * M_PI / gearinfo->numTeeth; cos_ta = cos(ta); cos_ta_1da = cos(ta + da); cos_ta_2da = cos(ta + 2 * da); cos_ta_3da = cos(ta + 3 * da); cos_ta_4da = cos(ta + 4 * da); sin_ta = sin(ta); sin_ta_1da = sin(ta + da); sin_ta_2da = sin(ta + 2 * da); sin_ta_3da = sin(ta + 3 * da); sin_ta_4da = sin(ta + 4 * da); u1 = r2 * cos_ta_1da - r1 * cos_ta; v1 = r2 * sin_ta_1da - r1 * sin_ta; len = sqrt(u1 * u1 + v1 * v1); u1 /= len; v1 /= len; u2 = r1 * cos_ta_3da - r2 * cos_ta_2da; v2 = r1 * sin_ta_3da - r2 * sin_ta_2da; // front face normal = glm::vec3(0.0, 0.0, 1.0); ix0 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(gearinfo->width * 0.5), normal); ix4 = newVertex(&vBuffer, (float)(r0 * cos_ta_4da), (float)(r0 * sin_ta_4da), (float)(gearinfo->width * 0.5), normal); ix5 = newVertex(&vBuffer, (float)(r1 * cos_ta_4da), (float)(r1 * sin_ta_4da), (float)(gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); newFace(&iBuffer, ix2, ix3, ix4); newFace(&iBuffer, ix3, ix5, ix4); // front sides of teeth normal = glm::vec3(0.0, 0.0, 1.0); ix0 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); // back face normal = glm::vec3(0.0, 0.0, -1.0); ix0 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(-gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(-gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(-gearinfo->width * 0.5), normal); ix4 = newVertex(&vBuffer, (float)(r1 * cos_ta_4da), (float)(r1 * sin_ta_4da), (float)(-gearinfo->width * 0.5), normal); ix5 = newVertex(&vBuffer, (float)(r0 * cos_ta_4da), (float)(r0 * sin_ta_4da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); newFace(&iBuffer, ix2, ix3, ix4); newFace(&iBuffer, ix3, ix5, ix4); // back sides of teeth normal = glm::vec3(0.0, 0.0, -1.0); ix0 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(-gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(-gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); // draw outward faces of teeth normal = glm::vec3(v1, -u1, 0.0); ix0 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r1 * cos_ta), (float)(r1 * sin_ta), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); normal = glm::vec3(cos_ta, sin_ta, 0.0); ix0 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r2 * cos_ta_1da), (float)(r2 * sin_ta_1da), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); normal = glm::vec3(v2, -u2, 0.0); ix0 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(gearinfo->width * 0.5 ), normal); ix1 = newVertex(&vBuffer, (float)(r2 * cos_ta_2da), (float)(r2 * sin_ta_2da), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(gearinfo->width * 0.5 ), normal); ix3 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); normal = glm::vec3(cos_ta, sin_ta, 0.0); ix0 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(gearinfo->width * 0.5), normal); ix1 = newVertex(&vBuffer, (float)(r1 * cos_ta_3da), (float)(r1 * sin_ta_3da), (float)(-gearinfo->width * 0.5), normal); ix2 = newVertex(&vBuffer, (float)(r1 * cos_ta_4da), (float)(r1 * sin_ta_4da), (float)(gearinfo->width * 0.5), normal); ix3 = newVertex(&vBuffer, (float)(r1 * cos_ta_4da), (float)(r1 * sin_ta_4da), (float)(-gearinfo->width * 0.5), normal); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); // draw inside radius cylinder ix0 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(-gearinfo->width * 0.5), glm::vec3(-cos_ta, -sin_ta, 0.0)); ix1 = newVertex(&vBuffer, (float)(r0 * cos_ta), (float)(r0 * sin_ta), (float)(gearinfo->width * 0.5), glm::vec3(-cos_ta, -sin_ta, 0.0)); ix2 = newVertex(&vBuffer, (float)(r0 * cos_ta_4da), (float)(r0 * sin_ta_4da), (float)(-gearinfo->width * 0.5), glm::vec3(-cos_ta_4da, -sin_ta_4da, 0.0)); ix3 = newVertex(&vBuffer, (float)(r0 * cos_ta_4da), (float)(r0 * sin_ta_4da), (float)(gearinfo->width * 0.5), glm::vec3(-cos_ta_4da, -sin_ta_4da, 0.0)); newFace(&iBuffer, ix0, ix1, ix2); newFace(&iBuffer, ix1, ix3, ix2); } size_t vertexBufferSize = vBuffer.size() * sizeof(Vertex); size_t indexBufferSize = iBuffer.size() * sizeof(uint32_t); bool useStaging = true; if (useStaging) { struct { VkBuffer buffer; VkDeviceMemory memory; } vertexStaging, indexStaging; // Create staging buffers // Vertex data exampleBase->createBuffer( VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, vertexBufferSize, vBuffer.data(), &vertexStaging.buffer, &vertexStaging.memory); // Index data exampleBase->createBuffer( VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, indexBufferSize, iBuffer.data(), &indexStaging.buffer, &indexStaging.memory); // Create device local buffers // Vertex buffer exampleBase->createBuffer( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBufferSize, nullptr, &vertexBuffer.buf, &vertexBuffer.mem); // Index buffer exampleBase->createBuffer( VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBufferSize, nullptr, &indexBuffer.buf, &indexBuffer.mem); // Copy from staging buffers VkCommandBuffer copyCmd = exampleBase->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkBufferCopy copyRegion = {}; copyRegion.size = vertexBufferSize; vkCmdCopyBuffer( copyCmd, vertexStaging.buffer, vertexBuffer.buf, 1, &copyRegion); copyRegion.size = indexBufferSize; vkCmdCopyBuffer( copyCmd, indexStaging.buffer, indexBuffer.buf, 1, &copyRegion); exampleBase->flushCommandBuffer(copyCmd, queue, true); vkDestroyBuffer(device, vertexStaging.buffer, nullptr); vkFreeMemory(device, vertexStaging.memory, nullptr); vkDestroyBuffer(device, indexStaging.buffer, nullptr); vkFreeMemory(device, indexStaging.memory, nullptr); } else { // Vertex buffer exampleBase->createBuffer( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, vertexBufferSize, vBuffer.data(), &vertexBuffer.buf, &vertexBuffer.mem); // Index buffer exampleBase->createBuffer( VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, indexBufferSize, iBuffer.data(), &indexBuffer.buf, &indexBuffer.mem); } indexBuffer.count = (uint32_t)iBuffer.size(); prepareUniformBuffer(); } void VulkanGear::draw(VkCommandBuffer cmdbuffer, VkPipelineLayout pipelineLayout) { VkDeviceSize offsets[1] = { 0 }; vkCmdBindDescriptorSets(cmdbuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); vkCmdBindVertexBuffers(cmdbuffer, 0, 1, &vertexBuffer.buf, offsets); vkCmdBindIndexBuffer(cmdbuffer, indexBuffer.buf, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(cmdbuffer, indexBuffer.count, 1, 0, 0, 1); } void VulkanGear::updateUniformBuffer(glm::mat4 perspective, glm::vec3 rotation, float zoom, float timer) { ubo.projection = perspective; ubo.view = glm::lookAt( glm::vec3(0, 0, -zoom), glm::vec3(-1.0, -1.5, 0), glm::vec3(0, 1, 0) ); ubo.view = glm::rotate(ubo.view, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); ubo.view = glm::rotate(ubo.view, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); ubo.model = glm::mat4(); ubo.model = glm::translate(ubo.model, pos); rotation.z = (rotSpeed * timer) + rotOffset; ubo.model = glm::rotate(ubo.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); ubo.normal = glm::inverseTranspose(ubo.view * ubo.model); ubo.lightPos = glm::vec3(0.0f, 0.0f, 2.5f); ubo.lightPos.x = sin(glm::radians(timer)) * 8.0f; ubo.lightPos.z = cos(glm::radians(timer)) * 8.0f; uint8_t *pData; VK_CHECK_RESULT(vkMapMemory(device, uniformData.memory, 0, sizeof(ubo), 0, (void **)&pData)); memcpy(pData, &ubo, sizeof(ubo)); vkUnmapMemory(device, uniformData.memory); } void VulkanGear::setupDescriptorSet(VkDescriptorPool pool, VkDescriptorSetLayout descriptorSetLayout) { VkDescriptorSetAllocateInfo allocInfo = vkTools::initializers::descriptorSetAllocateInfo( pool, &descriptorSetLayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); // Binding 0 : Vertex shader uniform buffer VkWriteDescriptorSet writeDescriptorSet = vkTools::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformData.descriptor); vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, NULL); } void VulkanGear::prepareUniformBuffer() { // Vertex shader uniform buffer block VkMemoryAllocateInfo allocInfo = vkTools::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; VkBufferCreateInfo bufferInfo = vkTools::initializers::bufferCreateInfo( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, sizeof(ubo)); VK_CHECK_RESULT(vkCreateBuffer(device, &bufferInfo, nullptr, &uniformData.buffer)); vkGetBufferMemoryRequirements(device, uniformData.buffer, &memReqs); allocInfo.allocationSize = memReqs.size; allocInfo.memoryTypeIndex = exampleBase->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &allocInfo, nullptr, &uniformData.memory)); VK_CHECK_RESULT(vkBindBufferMemory(device, uniformData.buffer, uniformData.memory, 0)); uniformData.descriptor.buffer = uniformData.buffer; uniformData.descriptor.offset = 0; uniformData.descriptor.range = sizeof(ubo); uniformData.allocSize = allocInfo.allocationSize; }
c++
code
14,235
3,849
#include <cstdio> #include <cmath> int MainFunc(double **array, int lines, int columns, double &res) { /* Функция обрабатывает массив вещественных чисел- * среди сумм элементов столбцов * находит максимальный * * Входные параметры: * array - матрица * (размеры которой lines & columns) * lines - кол-во строк * columns - кол-во столбцов * * Выходной параметр: * res - максимальная сумма * элементов столбцов * (передаётся по ссылке) * * Программа возвращает: * 0 - при успешной работе * 1 - при возникновени ошибок */ int result = 1; double maxMin = -1e20; double tmpElement; if (lines > 0 && columns > 0) { int i, j; for (i = 0; i < columns; i++) { tmpElement = 0; for (j = 0; j < lines; j++) tmpElement += array[j][i]; if (tmpElement > maxMin) { maxMin = tmpElement; } } res = maxMin; result = 0; } return result; } int main() { int min_el, max_el, funcRes, rows, columns; bool mainLoop = true; int i, j; int myBool = 0; double **arr; double maxSumRow; int actFU; bool ok = true; char name[127]; double t; // Main Menu do { printf("\nChoose option:\n"); printf("Create table:\n"); printf(" 1 - Create the table using rand;\n"); printf(" 2 - Create your hands;\n"); printf(" 3 - Create the table from file;\n"); printf("4 - Process table;\n"); printf("5 - Show table;\n"); printf("6 - Show result;\n"); printf("Exit:\n"); printf(" 7 - Exit with saving in file;\n"); printf(" 8 - Exit without saving.\n"); scanf("%d", &actFU); if (actFU == 1) { do { printf("Enter count of rows: "); scanf("%d", &rows); } while (rows <= 0); do { printf("Enter count of columns: "); scanf("%d", &columns); } while (columns <= 0); arr = new double *[rows]; for (i = 0; i < rows; i++) { arr[i] = new double[columns]; } if (arr != NULL) { printf("Enter int min: "); scanf("%d", &min_el); printf("Enter int max: "); scanf("%d", &max_el); for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) arr[i][j] = (double)(((rand() % (100 * max_el)) + (50 * min_el))) * 0.01; myBool = 1; } else { printf("Error\n"); } } else if (actFU == 2) { do { printf("Enter count of rows: "); scanf("%d", &rows); } while (rows <= 0); do { printf("Enter count of columns: "); scanf("%d", &columns); } while (columns <= 0); arr = new double *[rows]; for (int i = 0; i < rows; i++) { arr[i] = new double[columns]; } if (arr != NULL) { for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) { printf("[%d][%d]: ", i, j); scanf("%lf", &arr[i][j]); } myBool = 1; } else { printf("\nERROR\n"); } } else if (actFU == 3) { printf("Enter file name(with .txt): "); scanf("%s", name); FILE *readFile; readFile = fopen(name, "r"); if (readFile) { ok = fscanf(readFile, "%i", &rows); if (ok && rows >= 1) { ok = fscanf(readFile, "%i", &columns); if (ok && columns >= 1) { arr = new double *[rows]; for (i = 0; i < rows; i++) { arr[i] = new double[columns]; } for (i = 0; (i < rows) && ok; i++) { for (j = 0; (j < columns) && ok; j++) { ok = fscanf(readFile, "%lf", &t); if (ok == 1) { arr[i][j] = t; } } } myBool = 1; } } fclose(readFile); } else { printf("File dosn't open\n"); } } else if (actFU == 4) { if (myBool == 1) { funcRes = MainFunc(arr, rows, columns, maxSumRow); if (funcRes == 0) { printf("\nTable has been processed\n"); myBool = 2; } else { printf("\nError\n"); } } else { printf("\nYou haven't created a table\n"); } } else if (actFU == 5) { if (myBool == 1) { for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) printf(" %4.2lf ", arr[i][j]); printf("\n"); } } else { printf("\nYou haven't created a table\n"); } } else if (actFU == 6) { if (myBool == 2) { if (funcRes == 0) { printf("\nMAX: %4.2lf\n", maxSumRow); } else { printf("\nError\n"); } } else { printf("\nYou haven't process a table\n"); } } else if (actFU == 7) { printf("Enter file name(with .txt): "); scanf("%s", name); FILE *writeFile; writeFile = fopen(name, "w"); fprintf(writeFile, "%d ", rows); fprintf(writeFile, "%d ", columns); fprintf(writeFile, "\n"); for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { fprintf(writeFile, "%.3lf ", arr[i][j]); } delete[] arr[i]; fprintf(writeFile, "\n"); } fprintf(writeFile, "\nMAX:%.3lf", maxSumRow); fclose(writeFile); delete[] arr; mainLoop = false; } else if (actFU == 8) { for (i = 0; i < rows; i++) { delete[] arr[i]; } delete[] arr; mainLoop = false; } else { printf("ERROR"); } } while (mainLoop); return 0; }
c++
code
7,724
1,593
/* * Copyright (c) 2013 - 2016 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 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. */ #ifndef __CPU_TRACE_TRACE_CPU_HH__ #define __CPU_TRACE_TRACE_CPU_HH__ #include <cstdint> #include <list> #include <queue> #include <set> #include <unordered_map> #include "arch/registers.hh" #include "base/statistics.hh" #include "cpu/base.hh" #include "debug/TraceCPUData.hh" #include "debug/TraceCPUInst.hh" #include "params/TraceCPU.hh" #include "proto/inst_dep_record.pb.h" #include "proto/packet.pb.h" #include "proto/protoio.hh" #include "sim/sim_events.hh" /** * The trace cpu replays traces generated using the elastic trace probe * attached to the O3 CPU model. The elastic trace is an execution trace with * register data dependencies and ordering dependencies annotated to it. The * trace cpu also replays a fixed timestamp fetch trace that is also generated * by the elastic trace probe. This trace cpu model aims at achieving faster * simulation compared to the detailed cpu model and good correlation when the * same trace is used for playback on different memory sub-systems. * * The TraceCPU inherits from BaseCPU so some virtual methods need to be * defined. It has two port subclasses inherited from RequestPort for * instruction and data ports. It issues the memory requests deducing the * timing from the trace and without performing real execution of micro-ops. As * soon as the last dependency for an instruction is complete, its * computational delay, also provided in the input trace is added. The * dependency-free nodes are maintained in a list, called 'ReadyList', ordered * by ready time. Instructions which depend on load stall until the responses * for read requests are received thus achieving elastic replay. If the * dependency is not found when adding a new node, it is assumed complete. * Thus, if this node is found to be completely dependency-free its issue time * is calculated and it is added to the ready list immediately. This is * encapsulated in the subclass ElasticDataGen. * * If ready nodes are issued in an unconstrained way there can be more nodes * outstanding which results in divergence in timing compared to the O3CPU. * Therefore, the Trace CPU also models hardware resources. A sub-class to * model hardware resources contains the maximum sizes of load buffer, store * buffer and ROB. If resources are not available, the node is not issued. Such * nodes that are pending issue are held in the 'depFreeQueue' structure. * * Modeling the ROB size in the Trace CPU as a resource limitation is arguably * the most important parameter of all resources. The ROB occupancy is * estimated using the newly added field 'robNum'. We need to use ROB number as * sequence number is at times much higher due to squashing and trace replay is * focused on correct path modeling. * * A map called 'inFlightNodes' is added to track nodes that are not only in * the readyList but also load nodes that are executed (and thus removed from * readyList) but are not complete. ReadyList handles what and when to execute * next node while the inFlightNodes is used for resource modelling. The oldest * ROB number is updated when any node occupies the ROB or when an entry in the * ROB is released. The ROB occupancy is equal to the difference in the ROB * number of the newly dependency-free node and the oldest ROB number in * flight. * * If no node depends on a non load/store node then there is no reason to * track it in the dependency graph. We filter out such nodes but count them * and add a weight field to the subsequent node that we do include in the * trace. The weight field is used to model ROB occupancy during replay. * * The depFreeQueue is chosen to be FIFO so that child nodes which are in * program order get pushed into it in that order and thus issued in program * order, like in the O3CPU. This is also why the dependents is made a * sequential container, std::set to std::vector. We only check head of the * depFreeQueue as nodes are issued in order and blocking on head models that * better than looping the entire queue. An alternative choice would be to * inspect top N pending nodes where N is the issue-width. This is left for * future as the timing correlation looks good as it is. * * At the start of an execution event, first we attempt to issue such pending * nodes by checking if appropriate resources have become available. If yes, we * compute the execute tick with respect to the time then. Then we proceed to * complete nodes from the readyList. * * When a read response is received, sometimes a dependency on it that was * supposed to be released when it was issued is still not released. This * occurs because the dependent gets added to the graph after the read was * sent. So the check is made less strict and the dependency is marked complete * on read response instead of insisting that it should have been removed on * read sent. * * There is a check for requests spanning two cache lines as this condition * triggers an assert fail in the L1 cache. If it does then truncate the size * to access only until the end of that line and ignore the remainder. * Strictly-ordered requests are skipped and the dependencies on such requests * are handled by simply marking them complete immediately. * * A CountedExitEvent that contains a static int belonging to the Trace CPU * class as a down counter is used to implement multi Trace CPU simulation * exit. */ class TraceCPU : public BaseCPU { public: TraceCPU(const TraceCPUParams &params); void init(); /** * This is a pure virtual function in BaseCPU. As we don't know how many * insts are in the trace but only know how how many micro-ops are we * cannot count this stat. * * @return 0 */ Counter totalInsts() const { return 0; } /** * Return totalOps as the number of committed micro-ops plus the * speculatively issued loads that are modelled in the TraceCPU replay. * * @return number of micro-ops i.e. nodes in the elastic data generator */ Counter totalOps() const { return traceStats.numOps.value(); } /* * Set the no. of ops when elastic data generator completes executing a * node. */ void updateNumOps(uint64_t rob_num); /* Pure virtual function in BaseCPU. Do nothing. */ void wakeup(ThreadID tid=0) { return; } /* * When resuming from checkpoint in FS mode, the TraceCPU takes over from * the old cpu. This function overrides the takeOverFrom() function in the * BaseCPU. It unbinds the ports of the old CPU and binds the ports of the * TraceCPU. */ void takeOverFrom(BaseCPU *oldCPU); /** * When instruction cache port receives a retry, schedule event * icacheNextEvent. */ void icacheRetryRecvd(); /** * When data cache port receives a retry, schedule event * dcacheNextEvent. */ void dcacheRetryRecvd(); /** * When data cache port receives a response, this calls the dcache * generator method handle to complete the load writeback. * * @param pkt Pointer to packet received */ void dcacheRecvTimingResp(PacketPtr pkt); /** * Schedule event dcacheNextEvent at the given tick * * @param when Tick at which to schedule event */ void schedDcacheNextEvent(Tick when); protected: /** * IcachePort class that interfaces with L1 Instruction Cache. */ class IcachePort : public RequestPort { public: /** Default constructor. */ IcachePort(TraceCPU* _cpu) : RequestPort(_cpu->name() + ".icache_port", _cpu), owner(_cpu) {} public: /** * Receive the timing reponse and simply delete the packet since * instruction fetch requests are issued as per the timing in the trace * and responses are ignored. * * @param pkt Pointer to packet received * @return true */ bool recvTimingResp(PacketPtr pkt); /** * Required functionally but do nothing. * * @param pkt Pointer to packet received */ void recvTimingSnoopReq(PacketPtr pkt) {} /** * Handle a retry signalled by the cache if instruction read failed in * the first attempt. */ void recvReqRetry(); private: TraceCPU* owner; }; /** * DcachePort class that interfaces with L1 Data Cache. */ class DcachePort : public RequestPort { public: /** Default constructor. */ DcachePort(TraceCPU* _cpu) : RequestPort(_cpu->name() + ".dcache_port", _cpu), owner(_cpu) {} public: /** * Receive the timing reponse and call dcacheRecvTimingResp() method * of the dcacheGen to handle completing the load * * @param pkt Pointer to packet received * @return true */ bool recvTimingResp(PacketPtr pkt); /** * Required functionally but do nothing. * * @param pkt Pointer to packet received */ void recvTimingSnoopReq(PacketPtr pkt) {} /** * Required functionally but do nothing. * * @param pkt Pointer to packet received */ void recvFunctionalSnoop(PacketPtr pkt) {} /** * Handle a retry signalled by the cache if data access failed in the * first attempt. */ void recvReqRetry(); /** * Required functionally. * * @return true since we have to snoop */ bool isSnooping() const { return true; } private: TraceCPU* owner; }; /** Port to connect to L1 instruction cache. */ IcachePort icachePort; /** Port to connect to L1 data cache. */ DcachePort dcachePort; /** Requestor id for instruction read requests. */ const RequestorID instRequestorID; /** Requestor id for data read and write requests. */ const RequestorID dataRequestorID; /** File names for input instruction and data traces. */ std::string instTraceFile, dataTraceFile; /** * Generator to read protobuf trace containing memory requests at fixed * timestamps, perform flow control and issue memory requests. If L1 cache * port sends packet succesfully, determine the tick to send the next * packet else wait for retry from cache. */ class FixedRetryGen { private: /** * This struct stores a line in the trace file. */ struct TraceElement { /** Specifies if the request is to be a read or a write */ MemCmd cmd; /** The address for the request */ Addr addr; /** The size of the access for the request */ Addr blocksize; /** The time at which the request should be sent */ Tick tick; /** Potential request flags to use */ Request::FlagsType flags; /** Instruction PC */ Addr pc; /** * Check validity of this element. * * @return if this element is valid */ bool isValid() const { return cmd != MemCmd::InvalidCmd; } /** * Make this element invalid. */ void clear() { cmd = MemCmd::InvalidCmd; } }; /** * The InputStream encapsulates a trace file and the * internal buffers and populates TraceElements based on * the input. */ class InputStream { private: // Input file stream for the protobuf trace ProtoInputStream trace; public: /** * Create a trace input stream for a given file name. * * @param filename Path to the file to read from */ InputStream(const std::string& filename); /** * Reset the stream such that it can be played once * again. */ void reset(); /** * Attempt to read a trace element from the stream, * and also notify the caller if the end of the file * was reached. * * @param element Trace element to populate * @return True if an element could be read successfully */ bool read(TraceElement* element); }; public: /* Constructor */ FixedRetryGen(TraceCPU& _owner, const std::string& _name, RequestPort& _port, RequestorID requestor_id, const std::string& trace_file) : owner(_owner), port(_port), requestorId(requestor_id), trace(trace_file), genName(owner.name() + ".fixedretry." + _name), retryPkt(nullptr), delta(0), traceComplete(false), fixedStats(&_owner, _name) { } /** * Called from TraceCPU init(). Reads the first message from the * input trace file and returns the send tick. * * @return Tick when first packet must be sent */ Tick init(); /** * This tries to send current or retry packet and returns true if * successfull. It calls nextExecute() to read next message. * * @return bool true if packet is sent successfully */ bool tryNext(); /** Returns name of the FixedRetryGen instance. */ const std::string& name() const { return genName; } /** * Creates a new request assigning the request parameters passed by the * arguments. Calls the port's sendTimingReq() and returns true if * the packet was sent succesfully. It is called by tryNext() * * @param addr address of request * @param size size of request * @param cmd if it is a read or write request * @param flags associated request flags * @param pc instruction PC that generated the request * * @return true if packet was sent successfully */ bool send(Addr addr, unsigned size, const MemCmd& cmd, Request::FlagsType flags, Addr pc); /** Exit the FixedRetryGen. */ void exit(); /** * Reads a line of the trace file. Returns the tick * when the next request should be generated. If the end * of the file has been reached, it returns false. * * @return bool false id end of file has been reached */ bool nextExecute(); /** * Returns the traceComplete variable which is set when end of the * input trace file is reached. * * @return bool true if traceComplete is set, false otherwise. */ bool isTraceComplete() { return traceComplete; } int64_t tickDelta() { return delta; } private: /** Reference of the TraceCPU. */ TraceCPU& owner; /** Reference of the port to be used to issue memory requests. */ RequestPort& port; /** RequestorID used for the requests being sent. */ const RequestorID requestorId; /** Input stream used for reading the input trace file. */ InputStream trace; /** String to store the name of the FixedRetryGen. */ std::string genName; /** PacketPtr used to store the packet to retry. */ PacketPtr retryPkt; /** * Stores the difference in the send ticks of the current and last * packets. Keeping this signed to check overflow to a negative value * which will be caught by assert(delta > 0) */ int64_t delta; /** * Set to true when end of trace is reached. */ bool traceComplete; /** Store an element read from the trace to send as the next packet. */ TraceElement currElement; protected: struct FixedRetryGenStatGroup : public Stats::Group { /** name is the extension to the name for these stats */ FixedRetryGenStatGroup(Stats::Group *parent, const std::string& _name); /** Stats for instruction accesses replayed. */ Stats::Scalar numSendAttempted; Stats::Scalar numSendSucceeded; Stats::Scalar numSendFailed; Stats::Scalar numRetrySucceeded; /** Last simulated tick by the FixedRetryGen */ Stats::Scalar instLastTick; } fixedStats; }; /** * The elastic data memory request generator to read protobuf trace * containing execution trace annotated with data and ordering * dependencies. It deduces the time at which to send a load/store request * by tracking the dependencies. It attempts to send a memory request for a * load/store without performing real execution of micro-ops. If L1 cache * port sends packet succesfully, the generator checks which instructions * became dependency free as a result of this and schedules an event * accordingly. If it fails to send the packet, it waits for a retry from * the cache. */ class ElasticDataGen { private: /** Node sequence number type. */ typedef uint64_t NodeSeqNum; /** Node ROB number type. */ typedef uint64_t NodeRobNum; typedef ProtoMessage::InstDepRecord::RecordType RecordType; typedef ProtoMessage::InstDepRecord Record; /** * The struct GraphNode stores an instruction in the trace file. Th
c++
code
20,000
3,646
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* pruneTree(TreeNode* root) { // 这题可以通过从下到上的方式处理,如果叶节点的值为0则 // 删除它(返回NULL),正好是先处理子树再处理自己的过 // 程,使用后续遍历即可完成 if(root==NULL) return root ; root->left=pruneTree(root->left); root->right=pruneTree(root->right); if(root->left==NULL && root->right==NULL){ return root->val==0 ? NULL : root; } return root; } };
c++
code
627
153
/* Coin application in Gecode. From "The ECLiPSe Book" pages 99f and 234 ff The solution in ECLiPSe is at page 236. """ What is the minimum number of coins that allows one to pay _exactly_ any amount smaller than one Euro? Recall that there are six different euro cents, of denomination 1, 2, 5, 10, 20, 50 """ Compare with the following models: * MiniZinc: http://www.hakank.org/minizinc/coins3.mzn * Comet: http://www.hakank.org/comet/coins3.co This Gecode model was created by Hakan Kjellerstrand ([email protected]) Also, see my Gecode page: http://www.hakank.org/gecode/ . */ #include <gecode/driver.hh> #include <gecode/int.hh> #include <gecode/minimodel.hh> using namespace Gecode; class Coins3 : public MinimizeScript { protected: static const int n = 6; // number of different coins int num_coins_val; // set the number of coins (for showing all solutions) IntVarArray x; // array for number of each coins IntVar num_coins; // number of coins used (to minimize) public: // Search variants enum { SEARCH_DFS, // Use depth first search to find the smallest tick SEARCH_BAB, // Use branch and bound to optimize }; Coins3(const SizeOptions& opt) : num_coins_val(opt.size()), x(*this, n, 0, 99), num_coins(*this, 0, 99) { // values of the coins int _variables[] = {1, 2, 5, 10, 25, 50}; IntArgs variables(n, _variables); // sum the number of coins linear(*this, x, IRT_EQ, num_coins, opt.icl()); // This is the "main loop": // Checks that all changes from 1 to 99 can be made for(int j = 0; j < 99; j++) { IntVarArray tmp(*this, n, 0, 99); linear(*this, variables, tmp, IRT_EQ, j, opt.icl()); for(int i = 0; i < n; i++) { rel(*this, tmp[i] <= x[i], opt.icl()); } } // set the number of coins (via opt.size()) // don't forget // -search dfs if (num_coins_val) { rel(*this, num_coins == num_coins_val, opt.icl()); } branch(*this, x, INT_VAR_SIZE_MAX(), INT_VAL_MIN()); } // Print solution virtual void print(std::ostream& os) const { os << "num_coins: " << num_coins << std::endl; os << "x: " << x << std::endl; os << std::endl; } // Constructor for cloning s Coins3(bool share, Coins3& s) : MinimizeScript(share,s) { x.update(*this, share, s.x); num_coins.update(*this, share, s.num_coins); } // Return cost virtual IntVar cost(void) const { return num_coins; } // Copy during cloning virtual Space* copy(bool share) { return new Coins3(share,*this); } }; int main(int argc, char* argv[]) { SizeOptions opt("Coins3"); opt.solutions(0); opt.search(Coins3::SEARCH_BAB); opt.search(Coins3::SEARCH_DFS, "dfs"); opt.search(Coins3::SEARCH_BAB, "bab"); opt.parse(argc,argv); switch (opt.search()) { case Coins3::SEARCH_DFS: MinimizeScript::run<Coins3,DFS,SizeOptions>(opt); break; case Coins3::SEARCH_BAB: MinimizeScript::run<Coins3,BAB,SizeOptions>(opt); break; } return 0; }
c++
code
3,103
775
#include <iostream> #include <sbgn/SbgnTypes.h> int main(int argc, const char* argv[]) { auto* doc = new SbgnDocument(); SbgnGlyph* glyph = NULL; SbgnState* state = NULL; SbgnEntity* entity = NULL; SbgnCallout* co = NULL; SbgnGlyph* clone = NULL; SbgnLabel* label = NULL; SbgnArc* arc = NULL; SbgnBBox* bbox = NULL; SbgnPoint* point = NULL; SbgnPort* port= NULL; auto* map = doc->createMap(); map->setId("map1"); map->setLanguage("process description"); glyph = map->createGlyph(); glyph->setId("glyph1"); glyph->setClazz("macromolecule"); label = glyph->createLabel(); label->setText("B"); bbox = glyph->createBBox(); bbox->setX(286); bbox->setY(140); bbox->setWidth(108); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph0"); glyph->setClazz("macromolecule"); label = glyph->createLabel(); label->setText("C"); bbox = glyph->createBBox(); bbox->setX(446); bbox->setY(90); bbox->setWidth(108); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph2"); glyph->setClazz("macromolecule"); label = glyph->createLabel(); label->setText("D"); bbox = glyph->createBBox(); bbox->setX(636); bbox->setY(90); bbox->setWidth(108); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph5"); glyph->setClazz("simple chemical"); label = glyph->createLabel(); label->setText("I"); bbox = glyph->createBBox(); bbox->setX(250); bbox->setY(490); bbox->setWidth(60); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph4"); glyph->setClazz("simple chemical"); label = glyph->createLabel(); label->setText("II"); bbox = glyph->createBBox(); bbox->setX(460); bbox->setY(490); bbox->setWidth(60); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph9"); glyph->setClazz("process"); label = glyph->createLabel(); bbox = glyph->createBBox(); bbox->setX(368); bbox->setY(508); bbox->setWidth(24); bbox->setHeight(24); port = glyph->createPort(); port->setId("glyph9.1"); port->setX(356); port->setY(520); port = glyph->createPort(); port->setId("glyph9.2"); port->setX(404); port->setY(520); glyph = map->createGlyph(); glyph->setId("glyph3"); glyph->setClazz("macromolecule"); label = glyph->createLabel(); label->setText("A"); bbox = glyph->createBBox(); bbox->setX(156); bbox->setY(260); bbox->setWidth(108); bbox->setHeight(60); glyph = map->createGlyph(); glyph->setId("glyph6"); glyph->setClazz("not"); label = glyph->createLabel(); label->setText("NOT"); bbox = glyph->createBBox(); bbox->setX(319); bbox->setY(249); bbox->setWidth(42); bbox->setHeight(42); port = glyph->createPort(); port->setId("glyph6.1"); port->setX(340); port->setY(228); port = glyph->createPort(); port->setId("glyph6.2"); port->setX(340); port->setY(312); glyph = map->createGlyph(); glyph->setId("glyph7"); glyph->setClazz("and"); label = glyph->createLabel(); label->setText("AND"); bbox = glyph->createBBox(); bbox->setX(549); bbox->setY(239); bbox->setWidth(42); bbox->setHeight(42); port = glyph->createPort(); port->setId("glyph7.1"); port->setX(570); port->setY(218); port = glyph->createPort(); port->setId("glyph7.2"); port->setX(570); port->setY(302); glyph = map->createGlyph(); glyph->setId("glyph8"); glyph->setClazz("or"); label = glyph->createLabel(); label->setText("OR"); bbox = glyph->createBBox(); bbox->setX(359); bbox->setY(419); bbox->setWidth(42); bbox->setHeight(42); port = glyph->createPort(); port->setId("glyph8.2"); port->setX(380); port->setY(482); port = glyph->createPort(); port->setId("glyph8.1"); port->setX(380); port->setY(398); arc = map->createArc(); arc->setId("arc000000"); arc->setClazz("logic arc"); arc->setSource("glyph1"); arc->setTarget("glyph6.1"); point = arc->createStart(); point->setElementName("start"); point->setX(340); point->setY(200); point = arc->createEnd(); point->setElementName("end"); point->setX(340); point->setY(228); arc = map->createArc(); arc->setId("arc000001"); arc->setClazz("logic arc"); arc->setSource("glyph0"); arc->setTarget("glyph7.1"); point = arc->createStart(); point->setElementName("start"); point->setX(521.429); point->setY(150); point = arc->createEnd(); point->setElementName("end"); point->setX(570); point->setY(218); arc = map->createArc(); arc->setId("arc000002"); arc->setClazz("logic arc"); arc->setSource("glyph2"); arc->setTarget("glyph7.1"); point = arc->createStart(); point->setElementName("start"); point->setX(653.265); point->setY(150); point = arc->createEnd(); point->setElementName("end"); point->setX(570); point->setY(218); arc = map->createArc(); arc->setId("arc000003"); arc->setClazz("consumption"); arc->setSource("glyph5"); arc->setTarget("glyph9.1"); point = arc->createStart(); point->setElementName("start"); point->setX(310); point->setY(520); point = arc->createEnd(); point->setElementName("end"); point->setX(356); point->setY(520); arc = map->createArc(); arc->setId("arc000004"); arc->setClazz("production"); arc->setSource("glyph9.2"); arc->setTarget("glyph4"); point = arc->createStart(); point->setElementName("start"); point->setX(404); point->setY(520); point = arc->createEnd(); point->setElementName("end"); point->setX(460); point->setY(520); arc = map->createArc(); arc->setId("arc000005"); arc->setClazz("stimulation"); arc->setSource("glyph8.2"); arc->setTarget("glyph9"); point = arc->createStart(); point->setElementName("start"); point->setX(380); point->setY(482); point = arc->createEnd(); point->setElementName("end"); point->setX(380); point->setY(508); arc = map->createArc(); arc->setId("arc000006"); arc->setClazz("logic arc"); arc->setSource("glyph3"); arc->setTarget("glyph8.1"); point = arc->createStart(); point->setElementName("start"); point->setX(257.222); point->setY(320); point = arc->createEnd(); point->setElementName("end"); point->setX(380); point->setY(398); arc = map->createArc(); arc->setId("arc000007"); arc->setClazz("logic arc"); arc->setSource("glyph6.2"); arc->setTarget("glyph8.1"); point = arc->createStart(); point->setElementName("start"); point->setX(340); point->setY(312); point = arc->createEnd(); point->setElementName("end"); point->setX(380); point->setY(398); arc = map->createArc(); arc->setId("arc000008"); arc->setClazz("logic arc"); arc->setSource("glyph7.2"); arc->setTarget("glyph8.1"); point = arc->createStart(); point->setElementName("start"); point->setX(570); point->setY(302); point = arc->createEnd(); point->setElementName("end"); point->setX(380); point->setY(398); std::string outfile = "out.sbgn"; if (argc > 1) outfile = argv[1]; writeSBGNToFile(doc, outfile.c_str()); delete doc; return 0; }
c++
code
8,054
2,405
#include "base_test.hpp" namespace opossum { // Test for the cache implementation in lib/cache. // Not using SQL types in this test, only testing cache eviction. class CachePolicyTest : public BaseTest { protected: template <typename Key, typename Value> double inflation(const GDFSCache<Key, Value>& cache) const { return cache._inflation; } template <typename Key, typename Value> const boost::heap::fibonacci_heap<typename GDFSCache<Key, Value>::GDFSCacheEntry>& queue( const GDFSCache<Key, Value>& cache) const { return cache._queue; } template <typename Key, typename Value> const typename GDFSCache<Key, Value>::GDFSCacheEntry get_full_entry(const GDFSCache<Key, Value>& cache, const Key& key) const { return *(cache._map.find(key)->second); } }; // GDFS Strategy TEST_F(CachePolicyTest, GDFSCacheTest) { GDFSCache<int, int> cache(2); ASSERT_FALSE(cache.has(1)); ASSERT_FALSE(cache.has(2)); ASSERT_FALSE(cache.has(3)); cache.set(1, 2); // Miss, insert, L=0, Fr=1 ASSERT_EQ(1.0, get_full_entry(cache, 1).priority); ASSERT_EQ(1, get_full_entry(cache, 1).frequency); ASSERT_TRUE(cache.has(1)); ASSERT_FALSE(cache.has(2)); ASSERT_FALSE(cache.has(3)); ASSERT_EQ(2, cache.try_get(1)); // Hit, L=0, Fr=2 ASSERT_EQ(2.0, get_full_entry(cache, 1).priority); ASSERT_EQ(2, get_full_entry(cache, 1).frequency); cache.set(1, 2); // Hit, L=0, Fr=3 ASSERT_EQ(3.0, get_full_entry(cache, 1).priority); ASSERT_EQ(3, get_full_entry(cache, 1).frequency); cache.set(2, 4); // Miss, insert, L=0, Fr=1 ASSERT_EQ(1.0, get_full_entry(cache, 2).priority); ASSERT_EQ(1, get_full_entry(cache, 2).frequency); cache.set(3, 6); // Miss, evict 2, L=1, Fr=1 ASSERT_EQ(2.0, get_full_entry(cache, 3).priority); ASSERT_EQ(1.0, inflation(cache)); ASSERT_EQ(1, get_full_entry(cache, 3).frequency); ASSERT_EQ(2.0, queue(cache).top().priority); ASSERT_TRUE(cache.has(1)); ASSERT_FALSE(cache.has(2)); ASSERT_TRUE(cache.has(3)); ASSERT_EQ(6, cache.try_get(3)); // Hit, L=1, Fr=2 ASSERT_EQ(3.0, get_full_entry(cache, 3).priority); ASSERT_EQ(3.0, queue(cache).top().priority); ASSERT_EQ(2, get_full_entry(cache, 3).frequency); ASSERT_EQ(6, cache.try_get(3)); // Hit, L=1, Fr=3 ASSERT_EQ(4.0, get_full_entry(cache, 3).priority); ASSERT_EQ(3.0, get_full_entry(cache, 1).priority); ASSERT_EQ(3.0, queue(cache).top().priority); ASSERT_EQ(3, get_full_entry(cache, 3).frequency); cache.set(2, 5); // Miss, evict 1, L=1, Fr=3 ASSERT_EQ(3.0, inflation(cache)); ASSERT_EQ(1, get_full_entry(cache, 2).frequency); ASSERT_FALSE(cache.has(1)); ASSERT_TRUE(cache.has(2)); ASSERT_TRUE(cache.has(3)); ASSERT_EQ(3, get_full_entry(cache, 3).frequency); } class CacheTest : public BaseTest {}; TEST_F(CacheTest, Size) { GDFSCache<int, int> cache(3); cache.set(1, 2); cache.set(2, 4); ASSERT_EQ(cache.size(), 2u); } TEST_F(CacheTest, Clear) { GDFSCache<int, int> cache(3); cache.set(1, 2); cache.set(2, 4); ASSERT_TRUE(cache.has(1)); ASSERT_TRUE(cache.has(2)); cache.clear(); ASSERT_EQ(cache.capacity(), 3u); ASSERT_EQ(cache.size(), 0u); ASSERT_FALSE(cache.has(1)); ASSERT_FALSE(cache.has(2)); } TEST_F(CacheTest, NoGrowthOverCapacity) { GDFSCache<int, int> cache(3); cache.set(1, 2); cache.set(2, 4); cache.set(4, 6); cache.set(6, 8); ASSERT_EQ(cache.size(), 3u); } TEST_F(CacheTest, TryGet) { { GDFSCache<int, int> cache(0); cache.set(1, 2); ASSERT_EQ(cache.try_get(1), std::nullopt); } GDFSCache<int, int> cache(3); cache.set(1, 2); ASSERT_EQ(cache.try_get(2), std::nullopt); } TEST_F(CacheTest, ResizeGrow) { GDFSCache<int, int> cache(3); ASSERT_EQ(cache.capacity(), 3u); cache.set(1, 2); cache.set(2, 4); cache.resize(5); ASSERT_EQ(cache.capacity(), 5u); ASSERT_EQ(cache.size(), 2u); ASSERT_TRUE(cache.has(1)); ASSERT_TRUE(cache.has(2)); } TEST_F(CacheTest, ResizeShrink) { GDFSCache<int, int> cache(3); ASSERT_EQ(cache.capacity(), 3u); cache.set(1, 2); cache.set(2, 4); cache.set(3, 6); cache.resize(1); ASSERT_EQ(cache.capacity(), 1u); ASSERT_EQ(cache.size(), 1u); ASSERT_FALSE(cache.try_get(1)); ASSERT_FALSE(cache.try_get(2)); ASSERT_TRUE(cache.try_get(3)); ASSERT_EQ(cache.try_get(3), 6); } TEST_F(CacheTest, Snapshot) { GDFSCache<int, int> cache(5); const auto values = {1, 2, 3, 4, 5}; for (const auto value : values) { cache.set(value, value); } const auto snapshot = cache.snapshot(); for (const auto value : values) { const auto it = snapshot.find(value); EXPECT_NE(it, snapshot.end()); const auto entry = it->second; EXPECT_EQ(entry.value, value); EXPECT_EQ(entry.frequency, 1); } } } // namespace opossum
c++
code
4,855
1,420
/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include <catch.hpp> #include "mocks/MasterTestObject.h" #include "mocks/MeasurementComparisons.h" #include <testlib/HexConversions.h> #include <dnp3mocks/CallbackQueue.h> #include <dnp3mocks/APDUHexBuilders.h> #include <opendnp3/app/APDUResponse.h> #include <opendnp3/app/APDUBuilders.h> using namespace openpal; using namespace opendnp3; #define SUITE(name) "MasterUnsolTestSuite - " name TEST_CASE(SUITE("ReceiveUnsolBeforeTransmit")) { MasterParams params; params.disableUnsolOnStartup = false; MasterTestObject t(params); t.context.OnLowerLayerUp(); t.SendToMaster(hex::NullUnsolicited(0, IINField::Empty())); t.exe.RunMany(); REQUIRE(t.lower.PopWriteAsHex() == hex::UnsolConfirm(0)); t.context.OnSendResult(true); t.exe.RunMany(); REQUIRE(t.lower.PopWriteAsHex() == hex::IntegrityPoll(0)); }
c++
code
1,836
367
/* * Copyright 2019 Carnegie Technologies * * 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. */ #pragma once #include "basic/MemHandle.hpp" #include "error/Error.hpp" namespace Pravala { /// @brief Protocol decoder. class ProtoDec { public: /// @brief Constructor. /// @param [in] buf The buffer to use for decoding. ProtoDec ( const MemHandle & buf ); /// @brief Decodes the data. /// @param [out] output The output lines. It is cleared first. /// @return Standard error code. ERRCODE decode ( StringList & output ); private: const MemHandle _buf; ///< The memory to use. size_t _fieldIdWidth; ///< The width of the field ID value. size_t _fieldSizeWidth; ///< The width of the field size value. /// @brief Contains a single output entry struct Entry { String data; ///< The content line. size_t offFrom; ///< Start offset of the field/payload. size_t offTo; ///< End offset of the field/payload. size_t indent; ///< Indent level. bool isHdr; ///< Whether this contains a field header, or a payload /// @brief Constructor. /// @param [in] offF Start offset. /// @param [in] offT End offset. /// @param [in] i Indent level. /// @param [in] isH Whether this is a field header or a payload. Entry ( size_t offF, size_t offT, size_t i, bool isH ): offFrom ( offF ), offTo ( offT ), indent ( i ), isHdr ( isH ) { } /// @brief Sets just the content line. /// @param [in] val The new content to set. /// @return A reference to this entry. Entry & set ( const String & val ) { data = val; return *this; } }; /// @brief Decode a data starting at a given offset. /// @param [in] idPath The ID path so far. /// @param [in] offset Start offset of the data. /// @param [in] dataSize The size of the data to decode (starting from the given offset). /// @param [in] indent Indent level. /// @param [out] output The output to append to. It is not cleared. /// @return Standard error code. ERRCODE decodeData ( const String & idPath, size_t offset, size_t dataSize, size_t indent, List<Entry> & output ); /// @brief Adds the content of a single field to output. /// @param [in] idPath The ID/ID path of the field. /// @param [in] hdrOffset Start offset of field's header. /// @param [in] offset Start offset of field's payload. /// @param [in] fieldId The ID of this field. /// @param [in] fieldSize The size of this field's payload. /// @param [in] wireType Wire type used by this field. /// @param [in] indent Indent level. /// @param [out] output The output to append to. It is not cleared. void dumpField ( const String & idPath, size_t hdrOffset, size_t offset, uint8_t fieldId, size_t fieldSize, uint8_t wireType, size_t indent, List<Entry> & output ); /// @brief Adds the content of a value of the field to the output. /// @param [in] idPath The ID/ID path of the field. /// @param [in] hdrOffset Start offset of field's header. /// @param [in] offset Start offset of field's payload. /// @param [in] fieldId The ID of this field. /// @param [in] fieldSize The size of this field's payload. /// @param [in] wireType Wire type used by this field. /// @param [in] indent Indent level. /// @param [out] output The output to append to. It is not cleared. /// @param [out] inlineValue Set to true if the value generated can be used in inline mode; False otherwise. void dumpFieldValue ( const String & idPath, size_t hdrOffset, size_t offset, uint8_t fieldId, size_t fieldSize, uint8_t wireType, size_t indent, List<Entry> & output, bool & inlineValue ); /// @brief Adds the binary dump of a field's value to output. /// @param [in] hdrOffset Start offset of field's header. /// @param [in] offset Start offset of field's payload. /// @param [in] fieldSize The size of this field's payload. /// @param [in] indent Indent level. /// @param [out] output The output to append to. It is not cleared. void dumpData ( size_t hdrOffset, size_t offset, size_t fieldSize, size_t indent, List<Entry> & output ); /// @brief Returns the name of the wire type. /// @param [in] wireType the wire type. /// @return The name of the given wire type. static const char * getWireType ( uint8_t wireType ); }; }
c++
code
5,457
1,075
/* * Copyright 2017 Jacopo Urbani * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include <trident/iterators/cacheitr.h> #include <trident/kb/querier.h> #include <trident/kb/cacheidx.h> void CacheItr::init(Querier *q, const uint64_t estimatedSize, CacheIdx *cache, int64_t c1, int64_t c2) { this->cache = cache; this->estimatedSize = estimatedSize; this->q = q; constraint1 = c1; constraint2 = c2; v1 = 0; v2 = 0; idxEndGroup = 0; currentIdx = 0; groupSet = false; newPairs.clear(); p = NULL; newBlocks.clear(); startDelta = 0; lastDeltaValue = -2; //Initially the iterator is set to return some triples since there must //be some. The first time that the iterator is moved to a location then //the flags will be set accordingly. hasNextChecked = true; n = true; //Get existing pairs from cache std::pair<std::vector<std::pair<uint64_t, uint64_t>>*, std::vector<CacheBlock>*> pair = cache->getIndex(getKey()); existingPairs = pair.first; existingBlocks = pair.second; } int64_t CacheItr::getValue1() { return v1; } int64_t CacheItr::getValue2() { return v2; } bool CacheItr::hasNext() { if (!hasNextChecked) { n = true; if (groupSet) { if (currentIdx >= idxEndGroup || p->at(currentIdx).first != v1) { n = false; } else if (constraint2 != -1 && p->at(currentIdx).second != constraint2) { n = false; } } else { n = false; } hasNextChecked = true; } assert(groupSet || !n); return n; } void CacheItr::next() { assert(groupSet); v2 = p->at(currentIdx).second; currentIdx++; hasNextChecked = false; } void CacheItr::clear() { LOG(DEBUGL) << "Collected " << newPairs.size() << " pairs and " << newBlocks.size() << " blocks. All pairs are " << estimatedSize; if (newPairs.size() > 0) { if (startDelta != newPairs.size()) { CacheBlock b; b.startKey = newPairs[startDelta].first; b.endKey = newPairs[newPairs.size() - 1].first; b.startArray = startDelta; b.endArray = newPairs.size(); newBlocks.push_back(b); } std::sort(newBlocks.begin(), newBlocks.end()); //Remove the duplicates uint64_t lastKey = 0; uint64_t lastEndKey = 0; bool first = true; std::vector<CacheBlock> *cacheBlock = new std::vector<CacheBlock>(); for (std::vector<CacheBlock>::iterator itr = newBlocks.begin(); itr != newBlocks.end(); ++itr) { if (first) { cacheBlock->push_back(*itr); first = false; lastKey = itr->startKey; lastEndKey = itr->endKey; } else if (itr->startKey != lastKey) { if (itr->startKey <= lastEndKey) { if (itr->endKey <= lastEndKey) { //Continue continue; } else { //Change the key, and move forward itr->startArray += lastEndKey - itr->startKey + 1; itr->startKey = lastEndKey + 1; } } cacheBlock->push_back(*itr); lastKey = itr->startKey; lastEndKey = itr->endKey; } } std::vector<std::pair<uint64_t, uint64_t>> *cachePairs = new std::vector<std::pair<uint64_t, uint64_t>>(); newPairs.swap(*cachePairs); cache->storeIdx(getKey(), cacheBlock, cachePairs); newPairs.clear(); newBlocks.clear(); } } CacheBlock *CacheItr::searchBlock(std::vector<CacheBlock> *blocks, const uint64_t v) { if (blocks == NULL) return NULL; CacheBlock b; b.startKey = v; std::vector<CacheBlock>::iterator itr = std::lower_bound(blocks->begin(), blocks->end(), b); if (itr != blocks->begin() || v == itr->startKey) { if (v != itr->startKey) itr--; if (v <= itr->endKey) { return &(*itr); } else { return NULL; } } else { return NULL; } } bool CacheItr::gotoFirstTerm(int64_t c1) { //does c1 exist in the existing blocks? For now, assume it does not CacheBlock *block = searchBlock(existingBlocks, c1); if (block != NULL) { p = existingPairs; currentIdx = block->startArray + c1 - block->startKey; idxEndGroup = block->endArray; assert(currentIdx < idxEndGroup); while (currentIdx < idxEndGroup && p->at(currentIdx).first < c1) { ++currentIdx; } v1 = c1; v2 = p->at(currentIdx).second; hasNextChecked = true; n = p->at(currentIdx).first == c1; groupSet = true; return v1 == c1; } if (c1 != lastDeltaValue + 1 && newPairs.size() != startDelta) { //Start a new delta... CacheBlock b; b.startKey = newPairs[startDelta].first; b.endKey = newPairs[newPairs.size() - 1].first; b.startArray = startDelta; b.endArray = newPairs.size(); newBlocks.push_back(b); startDelta = newPairs.size(); } currentIdx = newPairs.size(); PairItr *subitr = q->getIterator(IDX_SPO, c1, getKey(), -1); while (subitr->hasNext()) { subitr->next(); newPairs.push_back(std::make_pair(c1, subitr->getValue2())); } q->releaseItr(subitr); if (newPairs.size() != currentIdx) { p = &newPairs; lastDeltaValue = c1; v1 = c1; v2 = newPairs.at(currentIdx).second; n = true; groupSet = true; idxEndGroup = newPairs.size(); } else { n = false; groupSet = false; } hasNextChecked = true; return v1 == c1; } void CacheItr::gotoSecondTerm(int64_t c2) { while (currentIdx < idxEndGroup && v1 == p->at(currentIdx).first && p->at(currentIdx).second < c2) { currentIdx++; } if (currentIdx < idxEndGroup && v1 == p->at(currentIdx).first && p->at(currentIdx).second == c2) n = true; else n = false; hasNextChecked = true; } void CacheItr::mark() { } void CacheItr::reset(const char i) { } uint64_t CacheItr::getCardinality() { throw 10; } /*uint64_t CacheItr::estimateCardinality() { return estimatedSize; }*/
c++
code
7,384
1,597
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_34.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-34.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_34 { typedef union { twointsclass * a; twointsclass * b; } union_type; #ifndef OMITBAD void bad() { twointsclass * data; union_type my_union; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (twointsclass *)realloc(data, 100*sizeof(twointsclass)); my_union.a = data; { twointsclass * data = my_union.b; /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { twointsclass * data; union_type my_union; /* Initialize data*/ data = NULL; /* FIX: Allocate memory using new [] */ data = new twointsclass[100]; my_union.a = data; { twointsclass * data = my_union.b; /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2G() { twointsclass * data; union_type my_union; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (twointsclass *)realloc(data, 100*sizeof(twointsclass)); my_union.a = data; { twointsclass * data = my_union.b; /* FIX: Free memory using free() */ free(data); } } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } // close namespace /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_34; // so that we can use good and bad easily int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
c++
code
3,503
688
// pen_string.cpp // Copyright 2014 - 2019 Alex Dixon. // License: https://github.com/polymonster/pmtech/blob/master/license.md #include "pen_string.h" #include "memory.h" #include <stdarg.h> namespace pen { void string_to_wide(const c8* src, c16* dest) { u32 len = pen::string_length(src); for (u32 i = 0; i < len; ++i) { dest[i] = (c16)src[i]; } } void string_to_ascii(const c16* src, c8* dest) { u32 len = pen::string_length_wide(src); for (u32 i = 0; i < len; ++i) { dest[i] = (c8)src[i]; } } u32 string_compare(const c8* string_a, const c8* string_b) { return strcmp(string_a, string_b); } u32 string_compare_wide(const c16* string_a, const c16* string_b) { return wcscmp(string_a, string_b); } void string_format_va(c8* dest, u32 buffer_size, const c8* format, va_list& va) { vsprintf_s(dest, buffer_size, format, va); } void string_format(c8* dest, u32 buffer_size, const c8* format, ...) { // memset( dest, 0x0, buffer_size ); va_list va; va_start(va, format); vsprintf_s(dest, buffer_size, format, va); va_end(va); } void string_format_wide(c16* dest, u32 buffer_size, const c16* format, ...) { // memset( dest, 0x0, buffer_size * 2 ); va_list va; va_start(va, format); vswprintf_s(dest, buffer_size, format, va); va_end(va); } void string_concatonate(c8* dest, const c8* src, u32 buffer_size) { strcat_s(dest, buffer_size, src); } void string_concatonate_wide(c16* dest, const c16* src, u32 buffer_size) { wcscat_s(dest, buffer_size, src); } u32 string_length(const c8* string) { return strlen(string); } u32 string_length_wide(const c16* string) { return wcslen(string); } } // namespace pen
c++
code
1,978
426