hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
bc6747102e6ab8a206d1a82eb8c61d368458af3b
2,557
cc
C++
core/Player.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
75
2015-04-26T11:22:07.000Z
2022-02-12T17:18:37.000Z
core/Player.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
7
2016-05-31T21:56:01.000Z
2019-09-15T06:25:28.000Z
core/Player.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
19
2015-09-23T01:50:15.000Z
2022-02-12T17:18:41.000Z
#include <core/Player.h> #include <util/Plugin.h> #include "PlayerImpl.h" namespace mous { Player::Player() : impl(std::make_unique<Impl>()) { } Player::~Player() { } PlayerStatus Player::Status() const { return impl->Status(); } void Player::LoadFormatProbePlugin(const std::shared_ptr<Plugin>& plugin) { return impl->LoadFormatProbePlugin(plugin); } void Player::LoadDecoderPlugin(const std::shared_ptr<Plugin>& plugin) { return impl->LoadDecoderPlugin(plugin); } void Player::LoadOutputPlugin(const std::shared_ptr<Plugin>& plugin) { return impl->LoadOutputPlugin(plugin); } void Player::UnloadPlugin(const std::string& path) { return impl->UnloadPlugin(path); } void Player::UnloadPlugin() { return impl->UnloadPlugin(); } vector<string> Player::SupportedSuffixes() const { return impl->SupportedSuffixes(); } int Player::BufferCount() const { return impl->BufferCount(); } void Player::SetBufferCount(int count) { return impl->SetBufferCount(count); } int Player::Volume() const { return impl->Volume(); } void Player::SetVolume(int level) { return impl->SetVolume(level); } ErrorCode Player::Open(const string& path) { return impl->Open(path); } void Player::Close() { return impl->Close(); } string Player::FileName() const { return impl->FileName(); } void Player::Play() { return impl->Play(); } void Player::Play(uint64_t msBegin, uint64_t msEnd) { return impl->Play(msBegin, msEnd); } void Player::Pause() { return impl->Pause(); } void Player::Resume() { return impl->Resume(); } void Player::SeekTime(uint64_t msPos) { return impl->SeekTime(msPos); } void Player::SeekPercent(double percent) { return impl->SeekPercent(percent); } void Player::PauseDecoder() { return impl->PauseDecoder(); } void Player::ResumeDecoder() { return impl->ResumeDecoder(); } int32_t Player::BitRate() const { return impl->BitRate(); } int32_t Player::SamleRate() const { return impl->SamleRate(); } uint64_t Player::Duration() const { return impl->Duration(); } uint64_t Player::RangeBegin() const { return impl->RangeBegin(); } uint64_t Player::RangeEnd() const { return impl->RangeEnd(); } uint64_t Player::RangeDuration() const { return impl->RangeDuration(); } uint64_t Player::OffsetMs() const { return impl->OffsetMs(); } uint64_t Player::CurrentMs() const { return impl->CurrentMs(); } enum AudioMode Player::AudioMode() const { return impl->AudioMode(); } Signal<void(void)>* Player::SigFinished() { return impl->SigFinished(); } } // namespace mous
17.756944
75
0.698084
bsdelf
bc6a7359892790e93dc8e01384d37d3adf1c82bf
4,859
cpp
C++
geopdf/src/ossimGeoPdfInfo.cpp
martidi/ossim-plugins
7dfb14d3fb87ce954fd13d41bd78d26cddc9f9c8
[ "MIT" ]
null
null
null
geopdf/src/ossimGeoPdfInfo.cpp
martidi/ossim-plugins
7dfb14d3fb87ce954fd13d41bd78d26cddc9f9c8
[ "MIT" ]
null
null
null
geopdf/src/ossimGeoPdfInfo.cpp
martidi/ossim-plugins
7dfb14d3fb87ce954fd13d41bd78d26cddc9f9c8
[ "MIT" ]
1
2019-11-02T11:01:58.000Z
2019-11-02T11:01:58.000Z
//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: Ogr Info object. // //---------------------------------------------------------------------------- // $Id: ossimGeoPdfInfo.cpp 20935 2012-05-18 14:19:30Z dburken $ #include <iostream> #include <iomanip> #include <sstream> #include <cstring> // for memset //PoDoFo includes #include <podofo/doc/PdfMemDocument.h> #include <podofo/base/PdfString.h> //ossim includes #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimKeywordlist.h> #include "ossimGeoPdfInfo.h" // Static trace for debugging static ossimTrace traceDebug("ossimGeoPdfInfo:debug"); static ossimTrace traceDump("ossimGeoPdfInfo:dump"); // This will dump offsets. ossimGeoPdfInfo::ossimGeoPdfInfo() : ossimInfoBase(), theFile(), m_PdfMemDocument(NULL) { } ossimGeoPdfInfo::~ossimGeoPdfInfo() { if (m_PdfMemDocument != NULL) { delete m_PdfMemDocument; m_PdfMemDocument = 0; } } bool ossimGeoPdfInfo::open(const ossimFilename& file) { theFile = file; if (isOpen()) { PoDoFo::PdfError::EnableDebug(false); //do not print out debug info m_PdfMemDocument = new PoDoFo::PdfMemDocument(theFile.c_str()); if (m_PdfMemDocument == NULL) { return false; } return true; } return false; } bool ossimGeoPdfInfo::isOpen() { ossimString ext = theFile.ext().downcase(); if(ext == "pdf") { return true; } else { return false; } } std::ostream& ossimGeoPdfInfo::print(std::ostream& out) const { static const char MODULE[] = "ossimGeoPdfInfo::print"; int count = m_PdfMemDocument->GetPageCount(); PoDoFo::PdfString author = m_PdfMemDocument->GetInfo()->GetAuthor(); PoDoFo::PdfString creator = m_PdfMemDocument->GetInfo()->GetCreator(); PoDoFo::PdfString title = m_PdfMemDocument->GetInfo()->GetTitle(); PoDoFo::PdfString subject = m_PdfMemDocument->GetInfo()->GetSubject(); PoDoFo::PdfString keywords = m_PdfMemDocument->GetInfo()->GetKeywords(); PoDoFo::PdfString producer = m_PdfMemDocument->GetInfo()->GetProducer(); ossimString createDate; ossimString modifyDate; PoDoFo::PdfObject* obj = m_PdfMemDocument->GetInfo()->GetObject(); if (obj->IsDictionary()) { PoDoFo::PdfDictionary pdfDictionary = obj->GetDictionary(); PoDoFo::TKeyMap keyMap = pdfDictionary.GetKeys(); PoDoFo::TKeyMap::iterator it = keyMap.begin(); while (it != keyMap.end()) { ossimString refName = ossimString(it->first.GetName()); PoDoFo::PdfObject* refObj = it->second; std::string objStr; refObj->ToString(objStr); if (refName == "CreationDate") { createDate = ossimString(objStr); createDate = createDate.substitute("(", "", true).trim(); createDate = createDate.substitute(")", "", true).trim(); createDate = createDate.substitute("D:", "", true).trim(); } else if (refName == "ModDate") { modifyDate = ossimString(objStr); modifyDate = modifyDate.substitute("(", "", true).trim(); modifyDate = modifyDate.substitute(")", "", true).trim(); modifyDate = modifyDate.substitute("D:", "", true).trim(); } it++; } } try { m_PdfMemDocument->FreeObjectMemory(obj); } catch (...) { } ossimString authorStr = author.GetString(); ossimString creatorStr = creator.GetString(); ossimString titleStr = title.GetString(); ossimString producerStr = producer.GetString(); ossimString subjectStr = subject.GetString(); ossimString keywordsStr = keywords.GetString(); ossimString prefix = "geopdf."; out << prefix << "pagecount: " << ossimString::toString(count).c_str() << "\n"; if (!authorStr.empty()) { out << prefix << "author: " << authorStr.c_str() << "\n"; } if (!creatorStr.empty()) { out << prefix << "creator: " << creatorStr.c_str() << "\n"; } if (!titleStr.empty()) { out << prefix << "title: " << titleStr.c_str() << "\n"; } if (!producerStr.empty()) { out << prefix << "producer: " << producerStr.c_str() << "\n"; } if (!subjectStr.empty()) { out << prefix << "subject: " << subjectStr.c_str() << "\n"; } if (!keywordsStr.empty()) { out << prefix << "keywords: " << keywordsStr.c_str() << "\n"; } if (!createDate.empty()) { out << prefix << "creationdate: " << createDate.c_str() << "\n"; } if (!modifyDate.empty()) { out << prefix << "modificationdate: " << modifyDate.c_str() << "\n"; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Entered...\n"; } return out; }
24.054455
79
0.603211
martidi
bc73f65cbe8cc38613c797e4b423c5726673d8ec
1,090
hpp
C++
IbeoLux/src/Additional/Convert/ConvertException.hpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
IbeoLux/src/Additional/Convert/ConvertException.hpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
IbeoLux/src/Additional/Convert/ConvertException.hpp
MechLabEngineering/SICKRPi-Scanner
19d7603a7bee444c8cfbd646f9773178ecf2e188
[ "MIT" ]
null
null
null
/** * @file ConvertException.hpp * * Enthält die Exceptionklassen für die verschiedenen Konvertierungen. * * @author Christian Blumberg * @date 2012-06-04 */ #ifndef CONVERTEXCEPTION_H_ #define CONVERTEXCEPTION_H_ #include <exception> namespace convert { /** @brief allgemeine Exception. * * Die allgemeinste Exception, die bei einer Konvertierung auftreten kann. Von ihr erben alle KindExceptions. */ class ConvertException : public std::exception {}; /** @brief Wertebereich überschritten bei Konvertierung. * * Die Exception wird dann geworfen, wenn eine Umwandlung nicht stattfinden kann, weil der Wertebereich des angegebenen Datentyps in den konvertiert werden soll nicht ausreicht. */ class ConvertOutOfRangeException : public ConvertException {}; /** @brief übergebener Parameter fehlerhaft. * * Die Exception wird dann geworfen, wenn ein übergebener Parameter eine falsche Syntax aufweist. Z.B. ein leerer String. */ class ConvertInvalidArgumentException : public ConvertException {}; } /* namespace convert */ #endif /* CONVERTEXCEPTION_H_ */
29.459459
178
0.761468
MechLabEngineering
bc74f2be16b58fa8c88975bfddb548ce871a7ea2
21,700
cpp
C++
source/RobotController/RobotControllerGUI/GeneratedFiles/RelWithDebInfo/moc_MainWindowProgram.cpp
xxzl0130/ProgrammingExperience
4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd
[ "MIT" ]
1
2020-09-08T02:54:11.000Z
2020-09-08T02:54:11.000Z
source/RobotController/RobotControllerGUI/GeneratedFiles/RelWithDebInfo/moc_MainWindowProgram.cpp
xxzl0130/ProgrammingExperience
4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd
[ "MIT" ]
1
2020-09-08T02:53:54.000Z
2020-09-23T00:55:35.000Z
source/RobotController/RobotControllerGUI/GeneratedFiles/RelWithDebInfo/moc_MainWindowProgram.cpp
xxzl0130/ProgrammingExperience
4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'MainWindowProgram.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "commonHeader.h" #include "../../MainWindowProgram.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'MainWindowProgram.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindowProgram_t { QByteArrayData data[94]; char stringdata0[1554]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindowProgram_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindowProgram_t qt_meta_stringdata_MainWindowProgram = { { QT_MOC_LITERAL(0, 0, 17), // "MainWindowProgram" QT_MOC_LITERAL(1, 18, 14), // "commandRenamed" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 10), // "addCommand" QT_MOC_LITERAL(4, 45, 28), // "ProgramItemBase::ProgramType" QT_MOC_LITERAL(5, 74, 4), // "type" QT_MOC_LITERAL(6, 79, 33), // "refreshAbsolutePointPositionT..." QT_MOC_LITERAL(7, 113, 16), // "refreshDeltaInfo" QT_MOC_LITERAL(8, 130, 30), // "onInsertCommandNextRadioButton" QT_MOC_LITERAL(9, 161, 30), // "onInsertCommandPrevRadioButton" QT_MOC_LITERAL(10, 192, 11), // "saveProgram" QT_MOC_LITERAL(11, 204, 11), // "loadProgram" QT_MOC_LITERAL(12, 216, 16), // "setAbsolutePoint" QT_MOC_LITERAL(13, 233, 17), // "showAbsolutePoint" QT_MOC_LITERAL(14, 251, 21), // "setRelativePointStart" QT_MOC_LITERAL(15, 273, 22), // "showRelativePointStart" QT_MOC_LITERAL(16, 296, 20), // "setRelativePointGoal" QT_MOC_LITERAL(17, 317, 21), // "showRelativePointGoal" QT_MOC_LITERAL(18, 339, 16), // "pointTypeChanged" QT_MOC_LITERAL(19, 356, 5), // "index" QT_MOC_LITERAL(20, 362, 15), // "moveTypeChanged" QT_MOC_LITERAL(21, 378, 23), // "jointSharedSpeedChanged" QT_MOC_LITERAL(22, 402, 4), // "text" QT_MOC_LITERAL(23, 407, 23), // "jointSharedAccelChanged" QT_MOC_LITERAL(24, 431, 17), // "sharedToolChanged" QT_MOC_LITERAL(25, 449, 16), // "setUseSharedTool" QT_MOC_LITERAL(26, 466, 11), // "setNoFillet" QT_MOC_LITERAL(27, 478, 9), // "setFillet" QT_MOC_LITERAL(28, 488, 15), // "setFilletRadius" QT_MOC_LITERAL(29, 504, 6), // "radius" QT_MOC_LITERAL(30, 511, 19), // "setUseSharedSetting" QT_MOC_LITERAL(31, 531, 17), // "jointSpeedChanged" QT_MOC_LITERAL(32, 549, 17), // "jointAccelChanged" QT_MOC_LITERAL(33, 567, 15), // "pointVarChanged" QT_MOC_LITERAL(34, 583, 6), // "itemUp" QT_MOC_LITERAL(35, 590, 8), // "itemDown" QT_MOC_LITERAL(36, 599, 10), // "itemDelete" QT_MOC_LITERAL(37, 610, 16), // "popWindowTypeMsg" QT_MOC_LITERAL(38, 627, 18), // "popWindowTypeError" QT_MOC_LITERAL(39, 646, 20), // "popWindowTypeWarning" QT_MOC_LITERAL(40, 667, 20), // "setStopWithPopWindow" QT_MOC_LITERAL(41, 688, 16), // "previewPopWindow" QT_MOC_LITERAL(42, 705, 20), // "popWindowTextChanged" QT_MOC_LITERAL(43, 726, 18), // "commentTextChanged" QT_MOC_LITERAL(44, 745, 9), // "setNoWait" QT_MOC_LITERAL(45, 755, 11), // "setWaitTime" QT_MOC_LITERAL(46, 767, 15), // "waitTimeChanged" QT_MOC_LITERAL(47, 783, 4), // "time" QT_MOC_LITERAL(48, 788, 14), // "setWaitDigital" QT_MOC_LITERAL(49, 803, 20), // "waitDigitalInChanged" QT_MOC_LITERAL(50, 824, 25), // "waitDigitalInLevelChanged" QT_MOC_LITERAL(51, 850, 13), // "setWaitAnalog" QT_MOC_LITERAL(52, 864, 19), // "waitAnalogInChanged" QT_MOC_LITERAL(53, 884, 24), // "waitAnalogCompareChanged" QT_MOC_LITERAL(54, 909, 24), // "waitAnalogInLevelChanged" QT_MOC_LITERAL(55, 934, 5), // "value" QT_MOC_LITERAL(56, 940, 9), // "setWaitFx" QT_MOC_LITERAL(57, 950, 13), // "waitFxChanged" QT_MOC_LITERAL(58, 964, 15), // "addBlankCommand" QT_MOC_LITERAL(59, 980, 14), // "addMoveCommand" QT_MOC_LITERAL(60, 995, 15), // "addPointCommand" QT_MOC_LITERAL(61, 1011, 14), // "addWaitCommand" QT_MOC_LITERAL(62, 1026, 13), // "addSetCommand" QT_MOC_LITERAL(63, 1040, 13), // "addPopCommand" QT_MOC_LITERAL(64, 1054, 14), // "addStopCommand" QT_MOC_LITERAL(65, 1069, 17), // "addCommentCommand" QT_MOC_LITERAL(66, 1087, 12), // "addPointPrev" QT_MOC_LITERAL(67, 1100, 12), // "addPointNext" QT_MOC_LITERAL(68, 1113, 24), // "programTreeSelectChanged" QT_MOC_LITERAL(69, 1138, 16), // "QTreeWidgetItem*" QT_MOC_LITERAL(70, 1155, 6), // "widget" QT_MOC_LITERAL(71, 1162, 15), // "jump2StructPage" QT_MOC_LITERAL(72, 1178, 8), // "setNoSet" QT_MOC_LITERAL(73, 1187, 16), // "setDigitalOutput" QT_MOC_LITERAL(74, 1204, 18), // "setDigitalOutputFx" QT_MOC_LITERAL(75, 1223, 15), // "setAnalogOutput" QT_MOC_LITERAL(76, 1239, 17), // "setAnalogOutputFx" QT_MOC_LITERAL(77, 1257, 6), // "setVar" QT_MOC_LITERAL(78, 1264, 7), // "setLoad" QT_MOC_LITERAL(79, 1272, 7), // "setTool" QT_MOC_LITERAL(80, 1280, 20), // "setDigitalOutChanged" QT_MOC_LITERAL(81, 1301, 25), // "setDigitalOutLevelChanged" QT_MOC_LITERAL(82, 1327, 26), // "setDigitalOutFxCombChanged" QT_MOC_LITERAL(83, 1354, 22), // "setDigitalOutFxChanged" QT_MOC_LITERAL(84, 1377, 19), // "setAnalogOutChanged" QT_MOC_LITERAL(85, 1397, 24), // "setAnalogOutLevelChanged" QT_MOC_LITERAL(86, 1422, 25), // "setAnalogOutFxCombChanged" QT_MOC_LITERAL(87, 1448, 21), // "setAnalogOutFxChanged" QT_MOC_LITERAL(88, 1470, 13), // "setVarChanged" QT_MOC_LITERAL(89, 1484, 15), // "setVarFxChanged" QT_MOC_LITERAL(90, 1500, 14), // "setLoadChanged" QT_MOC_LITERAL(91, 1515, 14), // "setToolChanged" QT_MOC_LITERAL(92, 1530, 18), // "programNameChanged" QT_MOC_LITERAL(93, 1549, 4) // "name" }, "MainWindowProgram\0commandRenamed\0\0" "addCommand\0ProgramItemBase::ProgramType\0" "type\0refreshAbsolutePointPositionTable\0" "refreshDeltaInfo\0onInsertCommandNextRadioButton\0" "onInsertCommandPrevRadioButton\0" "saveProgram\0loadProgram\0setAbsolutePoint\0" "showAbsolutePoint\0setRelativePointStart\0" "showRelativePointStart\0setRelativePointGoal\0" "showRelativePointGoal\0pointTypeChanged\0" "index\0moveTypeChanged\0jointSharedSpeedChanged\0" "text\0jointSharedAccelChanged\0" "sharedToolChanged\0setUseSharedTool\0" "setNoFillet\0setFillet\0setFilletRadius\0" "radius\0setUseSharedSetting\0jointSpeedChanged\0" "jointAccelChanged\0pointVarChanged\0" "itemUp\0itemDown\0itemDelete\0popWindowTypeMsg\0" "popWindowTypeError\0popWindowTypeWarning\0" "setStopWithPopWindow\0previewPopWindow\0" "popWindowTextChanged\0commentTextChanged\0" "setNoWait\0setWaitTime\0waitTimeChanged\0" "time\0setWaitDigital\0waitDigitalInChanged\0" "waitDigitalInLevelChanged\0setWaitAnalog\0" "waitAnalogInChanged\0waitAnalogCompareChanged\0" "waitAnalogInLevelChanged\0value\0setWaitFx\0" "waitFxChanged\0addBlankCommand\0" "addMoveCommand\0addPointCommand\0" "addWaitCommand\0addSetCommand\0addPopCommand\0" "addStopCommand\0addCommentCommand\0" "addPointPrev\0addPointNext\0" "programTreeSelectChanged\0QTreeWidgetItem*\0" "widget\0jump2StructPage\0setNoSet\0" "setDigitalOutput\0setDigitalOutputFx\0" "setAnalogOutput\0setAnalogOutputFx\0" "setVar\0setLoad\0setTool\0setDigitalOutChanged\0" "setDigitalOutLevelChanged\0" "setDigitalOutFxCombChanged\0" "setDigitalOutFxChanged\0setAnalogOutChanged\0" "setAnalogOutLevelChanged\0" "setAnalogOutFxCombChanged\0" "setAnalogOutFxChanged\0setVarChanged\0" "setVarFxChanged\0setLoadChanged\0" "setToolChanged\0programNameChanged\0" "name" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindowProgram[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 82, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 424, 2, 0x0a /* Public */, 3, 1, 425, 2, 0x0a /* Public */, 6, 0, 428, 2, 0x0a /* Public */, 7, 0, 429, 2, 0x0a /* Public */, 8, 0, 430, 2, 0x09 /* Protected */, 9, 0, 431, 2, 0x09 /* Protected */, 10, 0, 432, 2, 0x09 /* Protected */, 11, 0, 433, 2, 0x09 /* Protected */, 12, 0, 434, 2, 0x09 /* Protected */, 13, 0, 435, 2, 0x09 /* Protected */, 14, 0, 436, 2, 0x09 /* Protected */, 15, 0, 437, 2, 0x09 /* Protected */, 16, 0, 438, 2, 0x09 /* Protected */, 17, 0, 439, 2, 0x09 /* Protected */, 18, 1, 440, 2, 0x09 /* Protected */, 20, 1, 443, 2, 0x09 /* Protected */, 21, 1, 446, 2, 0x09 /* Protected */, 23, 1, 449, 2, 0x09 /* Protected */, 24, 1, 452, 2, 0x09 /* Protected */, 25, 0, 455, 2, 0x09 /* Protected */, 26, 0, 456, 2, 0x09 /* Protected */, 27, 0, 457, 2, 0x09 /* Protected */, 28, 1, 458, 2, 0x09 /* Protected */, 30, 0, 461, 2, 0x09 /* Protected */, 31, 1, 462, 2, 0x09 /* Protected */, 32, 1, 465, 2, 0x09 /* Protected */, 33, 1, 468, 2, 0x09 /* Protected */, 34, 0, 471, 2, 0x09 /* Protected */, 35, 0, 472, 2, 0x09 /* Protected */, 36, 0, 473, 2, 0x09 /* Protected */, 37, 0, 474, 2, 0x09 /* Protected */, 38, 0, 475, 2, 0x09 /* Protected */, 39, 0, 476, 2, 0x09 /* Protected */, 40, 0, 477, 2, 0x09 /* Protected */, 41, 0, 478, 2, 0x09 /* Protected */, 42, 0, 479, 2, 0x09 /* Protected */, 43, 0, 480, 2, 0x09 /* Protected */, 44, 0, 481, 2, 0x09 /* Protected */, 45, 0, 482, 2, 0x09 /* Protected */, 46, 1, 483, 2, 0x09 /* Protected */, 48, 0, 486, 2, 0x09 /* Protected */, 49, 1, 487, 2, 0x09 /* Protected */, 50, 1, 490, 2, 0x09 /* Protected */, 51, 0, 493, 2, 0x09 /* Protected */, 52, 1, 494, 2, 0x09 /* Protected */, 53, 1, 497, 2, 0x09 /* Protected */, 54, 1, 500, 2, 0x09 /* Protected */, 56, 0, 503, 2, 0x09 /* Protected */, 57, 1, 504, 2, 0x09 /* Protected */, 58, 0, 507, 2, 0x09 /* Protected */, 59, 0, 508, 2, 0x09 /* Protected */, 60, 0, 509, 2, 0x09 /* Protected */, 61, 0, 510, 2, 0x09 /* Protected */, 62, 0, 511, 2, 0x09 /* Protected */, 63, 0, 512, 2, 0x09 /* Protected */, 64, 0, 513, 2, 0x09 /* Protected */, 65, 0, 514, 2, 0x09 /* Protected */, 66, 0, 515, 2, 0x09 /* Protected */, 67, 0, 516, 2, 0x09 /* Protected */, 68, 1, 517, 2, 0x09 /* Protected */, 71, 0, 520, 2, 0x09 /* Protected */, 72, 0, 521, 2, 0x09 /* Protected */, 73, 0, 522, 2, 0x09 /* Protected */, 74, 0, 523, 2, 0x09 /* Protected */, 75, 0, 524, 2, 0x09 /* Protected */, 76, 0, 525, 2, 0x09 /* Protected */, 77, 0, 526, 2, 0x09 /* Protected */, 78, 0, 527, 2, 0x09 /* Protected */, 79, 0, 528, 2, 0x09 /* Protected */, 80, 1, 529, 2, 0x09 /* Protected */, 81, 1, 532, 2, 0x09 /* Protected */, 82, 1, 535, 2, 0x09 /* Protected */, 83, 1, 538, 2, 0x09 /* Protected */, 84, 1, 541, 2, 0x09 /* Protected */, 85, 1, 544, 2, 0x09 /* Protected */, 86, 1, 547, 2, 0x09 /* Protected */, 87, 1, 550, 2, 0x09 /* Protected */, 88, 1, 553, 2, 0x09 /* Protected */, 89, 1, 556, 2, 0x09 /* Protected */, 90, 1, 559, 2, 0x09 /* Protected */, 91, 1, 562, 2, 0x09 /* Protected */, 92, 1, 565, 2, 0x09 /* Protected */, // slots: parameters QMetaType::Void, QMetaType::Void, 0x80000000 | 4, 5, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Double, 29, QMetaType::Void, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 47, QMetaType::Void, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Double, 55, QMetaType::Void, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 69, 70, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::Double, 55, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::QString, 22, QMetaType::Void, QMetaType::Double, 55, QMetaType::Void, QMetaType::Int, 19, QMetaType::Void, QMetaType::QString, 93, 0 // eod }; void MainWindowProgram::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindowProgram *_t = static_cast<MainWindowProgram *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->commandRenamed(); break; case 1: _t->addCommand((*reinterpret_cast< ProgramItemBase::ProgramType(*)>(_a[1]))); break; case 2: _t->refreshAbsolutePointPositionTable(); break; case 3: _t->refreshDeltaInfo(); break; case 4: _t->onInsertCommandNextRadioButton(); break; case 5: _t->onInsertCommandPrevRadioButton(); break; case 6: _t->saveProgram(); break; case 7: _t->loadProgram(); break; case 8: _t->setAbsolutePoint(); break; case 9: _t->showAbsolutePoint(); break; case 10: _t->setRelativePointStart(); break; case 11: _t->showRelativePointStart(); break; case 12: _t->setRelativePointGoal(); break; case 13: _t->showRelativePointGoal(); break; case 14: _t->pointTypeChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 15: _t->moveTypeChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 16: _t->jointSharedSpeedChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 17: _t->jointSharedAccelChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 18: _t->sharedToolChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 19: _t->setUseSharedTool(); break; case 20: _t->setNoFillet(); break; case 21: _t->setFillet(); break; case 22: _t->setFilletRadius((*reinterpret_cast< double(*)>(_a[1]))); break; case 23: _t->setUseSharedSetting(); break; case 24: _t->jointSpeedChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 25: _t->jointAccelChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 26: _t->pointVarChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 27: _t->itemUp(); break; case 28: _t->itemDown(); break; case 29: _t->itemDelete(); break; case 30: _t->popWindowTypeMsg(); break; case 31: _t->popWindowTypeError(); break; case 32: _t->popWindowTypeWarning(); break; case 33: _t->setStopWithPopWindow(); break; case 34: _t->previewPopWindow(); break; case 35: _t->popWindowTextChanged(); break; case 36: _t->commentTextChanged(); break; case 37: _t->setNoWait(); break; case 38: _t->setWaitTime(); break; case 39: _t->waitTimeChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 40: _t->setWaitDigital(); break; case 41: _t->waitDigitalInChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 42: _t->waitDigitalInLevelChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 43: _t->setWaitAnalog(); break; case 44: _t->waitAnalogInChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 45: _t->waitAnalogCompareChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 46: _t->waitAnalogInLevelChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 47: _t->setWaitFx(); break; case 48: _t->waitFxChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 49: _t->addBlankCommand(); break; case 50: _t->addMoveCommand(); break; case 51: _t->addPointCommand(); break; case 52: _t->addWaitCommand(); break; case 53: _t->addSetCommand(); break; case 54: _t->addPopCommand(); break; case 55: _t->addStopCommand(); break; case 56: _t->addCommentCommand(); break; case 57: _t->addPointPrev(); break; case 58: _t->addPointNext(); break; case 59: _t->programTreeSelectChanged((*reinterpret_cast< QTreeWidgetItem*(*)>(_a[1]))); break; case 60: _t->jump2StructPage(); break; case 61: _t->setNoSet(); break; case 62: _t->setDigitalOutput(); break; case 63: _t->setDigitalOutputFx(); break; case 64: _t->setAnalogOutput(); break; case 65: _t->setAnalogOutputFx(); break; case 66: _t->setVar(); break; case 67: _t->setLoad(); break; case 68: _t->setTool(); break; case 69: _t->setDigitalOutChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 70: _t->setDigitalOutLevelChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 71: _t->setDigitalOutFxCombChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 72: _t->setDigitalOutFxChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 73: _t->setAnalogOutChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 74: _t->setAnalogOutLevelChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 75: _t->setAnalogOutFxCombChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 76: _t->setAnalogOutFxChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 77: _t->setVarChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 78: _t->setVarFxChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 79: _t->setLoadChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 80: _t->setToolChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 81: _t->programNameChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject MainWindowProgram::staticMetaObject = { { &MainWindowBase::staticMetaObject, qt_meta_stringdata_MainWindowProgram.data, qt_meta_data_MainWindowProgram, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *MainWindowProgram::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindowProgram::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindowProgram.stringdata0)) return static_cast<void*>(this); return MainWindowBase::qt_metacast(_clname); } int MainWindowProgram::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = MainWindowBase::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 82) qt_static_metacall(this, _c, _id, _a); _id -= 82; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 82) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 82; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
44.195519
103
0.621198
xxzl0130
bc83b577104ff2d20a0cb607272c0cf23f48cd9b
14,008
cc
C++
squid/squid3-3.3.8.spaceify/src/ssl/ErrorDetail.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/ssl/ErrorDetail.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/ssl/ErrorDetail.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
#include "squid.h" #include "errorpage.h" #include "ssl/ErrorDetail.h" #if HAVE_MAP #include <map> #endif #if HAVE_CLIMITS #include <climits> #endif struct SslErrorEntry { Ssl::ssl_error_t value; const char *name; }; static const char *SslErrorDetailDefaultStr = "SSL handshake error (%err_name)"; //Use std::map to optimize search typedef std::map<Ssl::ssl_error_t, const SslErrorEntry *> SslErrors; SslErrors TheSslErrors; static SslErrorEntry TheSslErrorArray[] = { {SQUID_X509_V_ERR_CERT_CHANGE, "SQUID_X509_V_ERR_CERT_CHANGE"}, {SQUID_ERR_SSL_HANDSHAKE, "SQUID_ERR_SSL_HANDSHAKE"}, {SQUID_X509_V_ERR_DOMAIN_MISMATCH, "SQUID_X509_V_ERR_DOMAIN_MISMATCH"}, {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT"}, {X509_V_ERR_UNABLE_TO_GET_CRL, "X509_V_ERR_UNABLE_TO_GET_CRL"}, {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE"}, {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, "X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE"}, {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, "X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY"}, {X509_V_ERR_CERT_SIGNATURE_FAILURE, "X509_V_ERR_CERT_SIGNATURE_FAILURE"}, {X509_V_ERR_CRL_SIGNATURE_FAILURE, "X509_V_ERR_CRL_SIGNATURE_FAILURE"}, {X509_V_ERR_CERT_NOT_YET_VALID, "X509_V_ERR_CERT_NOT_YET_VALID"}, {X509_V_ERR_CERT_HAS_EXPIRED, "X509_V_ERR_CERT_HAS_EXPIRED"}, {X509_V_ERR_CRL_NOT_YET_VALID, "X509_V_ERR_CRL_NOT_YET_VALID"}, {X509_V_ERR_CRL_HAS_EXPIRED, "X509_V_ERR_CRL_HAS_EXPIRED"}, {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD"}, {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD"}, {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD"}, {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, "X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD"}, {X509_V_ERR_OUT_OF_MEM, "X509_V_ERR_OUT_OF_MEM"}, {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, "X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT"}, {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN"}, {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY"}, {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE"}, {X509_V_ERR_CERT_CHAIN_TOO_LONG, "X509_V_ERR_CERT_CHAIN_TOO_LONG"}, {X509_V_ERR_CERT_REVOKED, "X509_V_ERR_CERT_REVOKED"}, {X509_V_ERR_INVALID_CA, "X509_V_ERR_INVALID_CA"}, {X509_V_ERR_PATH_LENGTH_EXCEEDED, "X509_V_ERR_PATH_LENGTH_EXCEEDED"}, {X509_V_ERR_INVALID_PURPOSE, "X509_V_ERR_INVALID_PURPOSE"}, {X509_V_ERR_CERT_UNTRUSTED, "X509_V_ERR_CERT_UNTRUSTED"}, {X509_V_ERR_CERT_REJECTED, "X509_V_ERR_CERT_REJECTED"}, {X509_V_ERR_SUBJECT_ISSUER_MISMATCH, "X509_V_ERR_SUBJECT_ISSUER_MISMATCH"}, {X509_V_ERR_AKID_SKID_MISMATCH, "X509_V_ERR_AKID_SKID_MISMATCH"}, {X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, "X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH"}, {X509_V_ERR_KEYUSAGE_NO_CERTSIGN, "X509_V_ERR_KEYUSAGE_NO_CERTSIGN"}, {X509_V_ERR_APPLICATION_VERIFICATION, "X509_V_ERR_APPLICATION_VERIFICATION"}, { SSL_ERROR_NONE, "SSL_ERROR_NONE"}, {SSL_ERROR_NONE, NULL} }; struct SslErrorAlias { const char *name; const Ssl::ssl_error_t *errors; }; static const Ssl::ssl_error_t hasExpired[] = {X509_V_ERR_CERT_HAS_EXPIRED, SSL_ERROR_NONE}; static const Ssl::ssl_error_t notYetValid[] = {X509_V_ERR_CERT_NOT_YET_VALID, SSL_ERROR_NONE}; static const Ssl::ssl_error_t domainMismatch[] = {SQUID_X509_V_ERR_DOMAIN_MISMATCH, SSL_ERROR_NONE}; static const Ssl::ssl_error_t certUntrusted[] = {X509_V_ERR_INVALID_CA, X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, X509_V_ERR_CERT_UNTRUSTED, SSL_ERROR_NONE }; static const Ssl::ssl_error_t certSelfSigned[] = {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_ERROR_NONE}; // The list of error name shortcuts for use with ssl_error acls. // The keys without the "ssl::" scope prefix allow shorter error // names within the SSL options scope. This is easier than // carefully stripping the scope prefix in Ssl::ParseErrorString(). static SslErrorAlias TheSslErrorShortcutsArray[] = { {"ssl::certHasExpired", hasExpired}, {"certHasExpired", hasExpired}, {"ssl::certNotYetValid", notYetValid}, {"certNotYetValid", notYetValid}, {"ssl::certDomainMismatch", domainMismatch}, {"certDomainMismatch", domainMismatch}, {"ssl::certUntrusted", certUntrusted}, {"certUntrusted", certUntrusted}, {"ssl::certSelfSigned", certSelfSigned}, {"certSelfSigned", certSelfSigned}, {NULL, NULL} }; // Use std::map to optimize search. typedef std::map<std::string, const Ssl::ssl_error_t *> SslErrorShortcuts; SslErrorShortcuts TheSslErrorShortcuts; static void loadSslErrorMap() { assert(TheSslErrors.empty()); for (int i = 0; TheSslErrorArray[i].name; ++i) { TheSslErrors[TheSslErrorArray[i].value] = &TheSslErrorArray[i]; } } static void loadSslErrorShortcutsMap() { assert(TheSslErrorShortcuts.empty()); for (int i = 0; TheSslErrorShortcutsArray[i].name; ++i) TheSslErrorShortcuts[TheSslErrorShortcutsArray[i].name] = TheSslErrorShortcutsArray[i].errors; } Ssl::ssl_error_t Ssl::GetErrorCode(const char *name) { //TODO: use a std::map? for (int i = 0; TheSslErrorArray[i].name != NULL; ++i) { if (strcmp(name, TheSslErrorArray[i].name) == 0) return TheSslErrorArray[i].value; } return SSL_ERROR_NONE; } Ssl::Errors * Ssl::ParseErrorString(const char *name) { assert(name); const Ssl::ssl_error_t ssl_error = GetErrorCode(name); if (ssl_error != SSL_ERROR_NONE) return new Ssl::Errors(ssl_error); if (xisdigit(*name)) { const long int value = strtol(name, NULL, 0); if (SQUID_SSL_ERROR_MIN <= value && value <= SQUID_SSL_ERROR_MAX) return new Ssl::Errors(value); fatalf("Too small or too bug SSL error code '%s'", name); } if (TheSslErrorShortcuts.empty()) loadSslErrorShortcutsMap(); const SslErrorShortcuts::const_iterator it = TheSslErrorShortcuts.find(name); if (it != TheSslErrorShortcuts.end()) { // Should not be empty... assert(it->second[0] != SSL_ERROR_NONE); Ssl::Errors *errors = new Ssl::Errors(it->second[0]); for (int i =1; it->second[i] != SSL_ERROR_NONE; ++i) { errors->push_back_unique(it->second[i]); } return errors; } fatalf("Unknown SSL error name '%s'", name); return NULL; // not reached } const char *Ssl::GetErrorName(Ssl::ssl_error_t value) { if (TheSslErrors.empty()) loadSslErrorMap(); const SslErrors::const_iterator it = TheSslErrors.find(value); if (it != TheSslErrors.end()) return it->second->name; return NULL; } const char * Ssl::GetErrorDescr(Ssl::ssl_error_t value) { return ErrorDetailsManager::GetInstance().getDefaultErrorDescr(value); } Ssl::ErrorDetail::err_frm_code Ssl::ErrorDetail::ErrorFormatingCodes[] = { {"ssl_subject", &Ssl::ErrorDetail::subject}, {"ssl_ca_name", &Ssl::ErrorDetail::ca_name}, {"ssl_cn", &Ssl::ErrorDetail::cn}, {"ssl_notbefore", &Ssl::ErrorDetail::notbefore}, {"ssl_notafter", &Ssl::ErrorDetail::notafter}, {"err_name", &Ssl::ErrorDetail::err_code}, {"ssl_error_descr", &Ssl::ErrorDetail::err_descr}, {"ssl_lib_error", &Ssl::ErrorDetail::err_lib_error}, {NULL,NULL} }; /** * The subject of the current certification in text form */ const char *Ssl::ErrorDetail::subject() const { if (!broken_cert) return "[Not available]"; static char tmpBuffer[256]; // A temporary buffer X509_NAME_oneline(X509_get_subject_name(broken_cert.get()), tmpBuffer, sizeof(tmpBuffer)); return tmpBuffer; } // helper function to be used with Ssl::matchX509CommonNames static int copy_cn(void *check_data, ASN1_STRING *cn_data) { String *str = (String *)check_data; if (!str) // no data? abort return 0; if (str->defined()) str->append(", "); str->append((const char *)cn_data->data, cn_data->length); return 1; } /** * The list with certificates cn and alternate names */ const char *Ssl::ErrorDetail::cn() const { if (!broken_cert) return "[Not available]"; static String tmpStr; ///< A temporary string buffer tmpStr.clean(); Ssl::matchX509CommonNames(broken_cert.get(), &tmpStr, copy_cn); return tmpStr.termedBuf(); } /** * The issuer name */ const char *Ssl::ErrorDetail::ca_name() const { if (!broken_cert) return "[Not available]"; static char tmpBuffer[256]; // A temporary buffer X509_NAME_oneline(X509_get_issuer_name(broken_cert.get()), tmpBuffer, sizeof(tmpBuffer)); return tmpBuffer; } /** * The certificate "not before" field */ const char *Ssl::ErrorDetail::notbefore() const { if (!broken_cert) return "[Not available]"; static char tmpBuffer[256]; // A temporary buffer ASN1_UTCTIME * tm = X509_get_notBefore(broken_cert.get()); Ssl::asn1timeToString(tm, tmpBuffer, sizeof(tmpBuffer)); return tmpBuffer; } /** * The certificate "not after" field */ const char *Ssl::ErrorDetail::notafter() const { if (!broken_cert) return "[Not available]"; static char tmpBuffer[256]; // A temporary buffer ASN1_UTCTIME * tm = X509_get_notAfter(broken_cert.get()); Ssl::asn1timeToString(tm, tmpBuffer, sizeof(tmpBuffer)); return tmpBuffer; } /** * The string representation of the error_no */ const char *Ssl::ErrorDetail::err_code() const { static char tmpBuffer[64]; // We can use the GetErrorName but using the detailEntry is faster, // so try it first. const char *err = detailEntry.name.termedBuf(); // error details not loaded yet or not defined in error_details.txt, // try the GetErrorName... if (!err) err = GetErrorName(error_no); if (!err) { snprintf(tmpBuffer, 64, "%d", (int)error_no); err = tmpBuffer; } return err; } /** * A short description of the error_no */ const char *Ssl::ErrorDetail::err_descr() const { if (error_no == SSL_ERROR_NONE) return "[No Error]"; if (const char *err = detailEntry.descr.termedBuf()) return err; return "[Not available]"; } const char *Ssl::ErrorDetail::err_lib_error() const { if (lib_error_no != SSL_ERROR_NONE) return ERR_error_string(lib_error_no, NULL); else return "[No Error]"; } /** * Converts the code to a string value. Supported formating codes are: * * Error meta information: * %err_name: The name of a high-level SSL error (e.g., X509_V_ERR_*) * %ssl_error_descr: A short description of the SSL error * %ssl_lib_error: human-readable low-level error string by ERR_error_string(3SSL) * * Certificate information extracted from broken (not necessarily peer!) cert * %ssl_cn: The comma-separated list of common and alternate names * %ssl_subject: The certificate subject * %ssl_ca_name: The certificate issuer name * %ssl_notbefore: The certificate "not before" field * %ssl_notafter: The certificate "not after" field * \retval the length of the code (the number of characters will be replaced by value) */ int Ssl::ErrorDetail::convert(const char *code, const char **value) const { *value = "-"; for (int i=0; ErrorFormatingCodes[i].code!=NULL; ++i) { const int len = strlen(ErrorFormatingCodes[i].code); if (strncmp(code,ErrorFormatingCodes[i].code, len)==0) { ErrorDetail::fmt_action_t action = ErrorFormatingCodes[i].fmt_action; *value = (this->*action)(); return len; } } return 0; } /** * It uses the convert method to build the string errDetailStr using * a template message for the current SSL error. The template messages * can also contain normal error pages formating codes. * Currently the error template messages are hard-coded */ void Ssl::ErrorDetail::buildDetail() const { char const *s = NULL; char const *p; char const *t; int code_len = 0; if (ErrorDetailsManager::GetInstance().getErrorDetail(error_no, request.raw(), detailEntry)) s = detailEntry.detail.termedBuf(); if (!s) s = SslErrorDetailDefaultStr; assert(s); while ((p = strchr(s, '%'))) { errDetailStr.append(s, p - s); code_len = convert(++p, &t); if (code_len) errDetailStr.append(t); else errDetailStr.append("%"); s = p + code_len; } errDetailStr.append(s, strlen(s)); } const String &Ssl::ErrorDetail::toString() const { if (!errDetailStr.defined()) buildDetail(); return errDetailStr; } Ssl::ErrorDetail::ErrorDetail( Ssl::ssl_error_t err_no, X509 *cert, X509 *broken): error_no (err_no), lib_error_no(SSL_ERROR_NONE) { if (cert) peer_cert.resetAndLock(cert); if (broken) broken_cert.resetAndLock(broken); else broken_cert.resetAndLock(cert); detailEntry.error_no = SSL_ERROR_NONE; } Ssl::ErrorDetail::ErrorDetail(Ssl::ErrorDetail const &anErrDetail) { error_no = anErrDetail.error_no; request = anErrDetail.request; if (anErrDetail.peer_cert.get()) { peer_cert.resetAndLock(anErrDetail.peer_cert.get()); } if (anErrDetail.broken_cert.get()) { broken_cert.resetAndLock(anErrDetail.broken_cert.get()); } detailEntry = anErrDetail.detailEntry; lib_error_no = anErrDetail.lib_error_no; }
31.337808
130
0.698387
spaceify
bc851415eb6e085b42b5e526a2901403e79cd9c4
500
hpp
C++
foundation/pro/include/pro/log/debug.hpp
xleakOfficial/xmax-mainchain
16bb71da7f4c9f7c897d1de7b4e88b721d20cfdf
[ "MIT" ]
14
2018-06-16T04:49:50.000Z
2021-04-10T03:18:40.000Z
foundation/pro/include/pro/log/debug.hpp
xleakOfficial/xmax-mainchain
16bb71da7f4c9f7c897d1de7b4e88b721d20cfdf
[ "MIT" ]
null
null
null
foundation/pro/include/pro/log/debug.hpp
xleakOfficial/xmax-mainchain
16bb71da7f4c9f7c897d1de7b4e88b721d20cfdf
[ "MIT" ]
7
2018-06-14T10:15:32.000Z
2020-11-06T17:07:09.000Z
/** * @file * @copyright defined in xmax/LICENSE */ #pragma once namespace pro { /** * ouput a msg to console * @param[in] char* content of msg */ void _debug_output(const char* ouput); /** * ouput a msg to console in a line * @param[in] char* content of msg */ void _debug_output_line(const char* ouput); /** * ouput a msg to console */ #define debug_output(x) _debug_output(x); /** * ouput a msg with line code to console */ #define debug_output_line(x) _debug_output_line(x) }
17.241379
50
0.67
xleakOfficial
bc90d411a58b49272fccf8a06f815a34a17da3bc
216
cpp
C++
src/babs_ecs_tests.cpp
misnor/babsecs
a8d1dc1f2a0fa5bd03563be125c8e6d90e81495f
[ "Apache-2.0" ]
null
null
null
src/babs_ecs_tests.cpp
misnor/babsecs
a8d1dc1f2a0fa5bd03563be125c8e6d90e81495f
[ "Apache-2.0" ]
16
2019-07-27T00:27:37.000Z
2021-09-12T16:43:58.000Z
src/babs_ecs_tests.cpp
misnor/babsecs
a8d1dc1f2a0fa5bd03563be125c8e6d90e81495f
[ "Apache-2.0" ]
null
null
null
#include "doctest.h" #include "babs_ecs.hpp" TEST_CASE("Confirming symlink babs_ecs -> ECSManager works") { babs_ecs::ECSManager ecs; babs_ecs::Entity e = ecs.CreateEntity(); REQUIRE(e.UUID == 1); }
15.428571
60
0.675926
misnor
bc91c8d9c597cff54f6a84b1680f9458bd162806
335
hpp
C++
osx-main/inc/m4c0/osx/main.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/inc/m4c0/osx/main.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/inc/m4c0/osx/main.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
#pragma once #include "m4c0/objc/mtk_view.hpp" #include "m4c0/objc/ns_event.hpp" namespace m4c0::osx { class delegate { public: virtual void start(const objc::mtk_view * view) = 0; virtual void on_event(const objc::ns_event * e) = 0; virtual void stop() = 0; }; int main(int argc, char ** argv, delegate * d); }
20.9375
56
0.656716
m4c0
bca0e0986fd75ad575dd819364d3ad08d9a8af91
2,025
cpp
C++
src/SpriteEdit/SpriteEditView.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
3
2021-03-28T00:11:48.000Z
2022-01-12T13:10:52.000Z
src/SpriteEdit/SpriteEditView.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
src/SpriteEdit/SpriteEditView.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
// SpriteEditView.cpp : implementation of the CSpriteEditView class // #include "stdafx.h" #include "SpriteEdit.h" #include "SpriteEditDoc.h" #include "SpriteEditView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CSpriteEditView IMPLEMENT_DYNCREATE(CSpriteEditView, CView) BEGIN_MESSAGE_MAP(CSpriteEditView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) END_MESSAGE_MAP() // CSpriteEditView construction/destruction CSpriteEditView::CSpriteEditView() { // TODO: add construction code here } CSpriteEditView::~CSpriteEditView() { } BOOL CSpriteEditView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CSpriteEditView drawing void CSpriteEditView::OnDraw(CDC* /*pDC*/) { CSpriteEditDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } // CSpriteEditView printing BOOL CSpriteEditView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CSpriteEditView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CSpriteEditView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CSpriteEditView diagnostics #ifdef _DEBUG void CSpriteEditView::AssertValid() const { CView::AssertValid(); } void CSpriteEditView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CSpriteEditDoc* CSpriteEditView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSpriteEditDoc))); return (CSpriteEditDoc*)m_pDocument; } #endif //_DEBUG // CSpriteEditView message handlers
20.25
84
0.725432
segafan
bca1956fbf29c6987aa220186307632abedd123f
3,556
cpp
C++
3282 Tree/main.cpp
sqc1999/BZOJ
eff99fe97dbb4c59e650c54f343a2365eebd1d99
[ "MIT" ]
1
2016-07-18T12:05:57.000Z
2016-07-18T12:05:57.000Z
3282 Tree/main.cpp
sqc1999/BZOJ
eff99fe97dbb4c59e650c54f343a2365eebd1d99
[ "MIT" ]
null
null
null
3282 Tree/main.cpp
sqc1999/BZOJ
eff99fe97dbb4c59e650c54f343a2365eebd1d99
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #include <cstdarg> #include <cctype> using namespace std; const int N = 3e5; struct splay_node { static splay_node *nul; struct constructor { constructor() { nul = new splay_node; nul->l = nul->r = nul->p = nul; } }; static constructor ctor; splay_node *l, *r, *p; bool rev; int val, sum; splay_node() :l(nul), r(nul), p(nul), rev(false), val(), sum() {} bool is_root() { return p == nul || p->l != this&&p->r != this; } void reverse() { if (this == nul) return; swap(l, r); rev ^= 1; } void push_down() { if (!rev) return; l->reverse(); r->reverse(); rev = false; } void maintain() { sum = l->sum^r->sum^val; } void update(int x) { val = x; maintain(); } void transplant(splay_node *x) { x->p = p; if (p->l == this) p->l = x; else if (p->r == this) p->r = x; } void left_rotate() { splay_node *x = r; r = x->l; r->p = this; transplant(x); x->l = this; p = x; maintain(); x->maintain(); } void right_rotate() { splay_node *x = l; l = x->r; l->p = this; transplant(x); x->r = this; p = x; maintain(); x->maintain(); } void splay() { static splay_node *st[N]; int k = 0; splay_node *t = this; while (!t->is_root()) { st[k++] = t; t = t->p; } st[k++] = t; while (k > 0) st[--k]->push_down(); while (!is_root()) { if (p->is_root()) if (p->l == this) p->right_rotate(); else p->left_rotate(); else { splay_node *x = p->p; if (p->l == this) if (x->l == p) x->right_rotate(), p->right_rotate(); else p->right_rotate(), x->left_rotate(); else if (x->r == p) x->left_rotate(), p->left_rotate(); else p->left_rotate(), x->right_rotate(); } } } }; splay_node::constructor splay_node::ctor; splay_node *splay_node::nul; void access(splay_node *n) { splay_node *x = n, *y = splay_node::nul; while (x != splay_node::nul) { x->splay(); x->r = y; x->maintain(); y = x; x = x->p; } n->splay(); } void change_root(splay_node *x) { access(x); x->reverse(); } splay_node *find_root(splay_node *x) { while (x->p != splay_node::nul) x = x->p; return x; } void extract(splay_node *x, splay_node *y) { change_root(x); access(y); } void link(splay_node *x, splay_node *y) { change_root(y); y->p = x; access(y); } void cut(splay_node *x, splay_node *y) { extract(x, y); y->l = x->p = splay_node::nul; y->maintain(); } bool connected(splay_node *x, splay_node *y) { return find_root(x) == find_root(y); } void read(int n, ...) { va_list li; va_start(li, n); while (n--) { int &x = *va_arg(li, int *), ch; x = 0; do ch = getchar(); while (!isdigit(ch)); do { (x *= 10) += ch - '0'; ch = getchar(); } while (isdigit(ch)); } va_end(li); } splay_node a[N]; int main() { int n, m; read(2, &n, &m); for (int i = 0; i < n; i++) { int x; read(1, &x); access(a + i); (a + i)->update(x); } for (int i = 0; i < m; i++) { int op, x, y; read(3, &op, &x, &y); if (op == 0) { extract(a + x - 1, a + y - 1); printf("%d\n", (a + y - 1)->sum); } else if (op == 1) { if (!connected(a + x - 1, a + y - 1)) link(a + x - 1, a + y - 1); } else if (op == 2) { if (connected(a + x - 1, a + y - 1)) cut(a + x - 1, a + y - 1); } else if (op == 3) { access(a + x - 1); (a + x - 1)->update(y); } } }
18.520833
90
0.495219
sqc1999
bca910f2df9d33f4349d93a72df17536c0ccb3b3
1,284
hpp
C++
modules/fs/include/fs/file_entry.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
29
2016-01-27T09:43:44.000Z
2020-03-12T04:16:02.000Z
modules/fs/include/fs/file_entry.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
20
2016-01-22T15:59:33.000Z
2016-10-28T10:22:45.000Z
modules/fs/include/fs/file_entry.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
6
2016-02-11T14:09:04.000Z
2018-03-17T00:18:35.000Z
#ifndef AVERSIVE_FS_FILE_ENTRY_HPP #define AVERSIVE_FS_FILE_ENTRY_HPP #include "entry.hpp" #include "filesystem.hpp" #include "path_list.hpp" namespace Aversive { namespace fs { class FileEntry : public Entry, public FileSystem, public PathList<FileEntry> { private: File _file; public: template<class Stream> FileEntry(const char* name, Stream& stream) : Entry(name), _file(stream) { } template<class OutputStream, class InputStream> FileEntry(const char* name, OutputStream& ostream, InputStream& istream) : Entry(name), _file(ostream, istream) { } File open(const char* p) { unsigned int len = strlen(this->_name); if(len != strlen(p+1)) { return File(); } if(strcmp(p+1, this->_name) != 0) { return File(); } return _file; } public: unsigned int size(void) { return 1; } }; template<> class Path<FileEntry> : public BasePath<FileEntry> { public: inline Path(FileEntry& entry, unsigned int index) : BasePath<FileEntry>(entry, index) { } inline unsigned int size(void) const { return 1; } inline const char* operator[](unsigned int i) { if(_index == 0 && i == 0) { return this->_entry.name(); } return 0; } }; } } #endif//AVERSIVE_FS_FILE_ENTRY_HPP
18.342857
74
0.653427
aversiveplusplus
bcb7e1b4cc6d93356a490c44f1e8d94bf1afb0f8
1,330
hpp
C++
include/vbte/compute/context.hpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
include/vbte/compute/context.hpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
include/vbte/compute/context.hpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
#pragma once #include <CL/cl.hpp> #include <GL/glew.h> namespace vbte { namespace compute { class buffer; class kernel; class shared_buffer; } } namespace vbte { namespace compute { class context { private: cl::Context default_context_; cl::Device default_device_; cl::CommandQueue command_queue_; public: context(bool shared = false); ~context() = default; context(const context&) = delete; context& operator=(const context&) = delete; context(context&&) = delete; context& operator=(context&&) = delete; void enqueue_write_buffer(buffer& buffer, bool blocking, size_t size, const void* data); cl::Event enqueue_read_buffer(buffer& buffer, bool blocking, size_t size, void* data); void enqueue_acquire_gl_buffer(shared_buffer& buffer); void enqueue_release_gl_buffer(shared_buffer& buffer); cl::Event enqueue_kernel(kernel& kernel, const cl::NDRange& global_range, const cl::NDRange& local_range, const cl::NDRange& offset = cl::NullRange); auto& get() noexcept { return default_context_; } auto& device() noexcept { return default_device_; } auto& command_queue() noexcept { return command_queue_; } void begin() const noexcept { glFinish(); } void end() const noexcept { command_queue_.finish(); } }; } }
22.166667
152
0.691729
Berling
bcb99a49438eb7eeb7a99182e052f67cec9db7d6
19,547
cpp
C++
src/MagnumPlugins/StanfordImporter/Test/StanfordImporterTest.cpp
bowling-allie/magnum-plugins
40181647a0725a255dbbc53d59dd261dff3a6f14
[ "MIT" ]
null
null
null
src/MagnumPlugins/StanfordImporter/Test/StanfordImporterTest.cpp
bowling-allie/magnum-plugins
40181647a0725a255dbbc53d59dd261dff3a6f14
[ "MIT" ]
null
null
null
src/MagnumPlugins/StanfordImporter/Test/StanfordImporterTest.cpp
bowling-allie/magnum-plugins
40181647a0725a255dbbc53d59dd261dff3a6f14
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/Containers/Array.h> #include <Corrade/Containers/Optional.h> #include <Corrade/TestSuite/Tester.h> #include <Corrade/Utility/DebugStl.h> #include <Corrade/Utility/Directory.h> #include <Magnum/Math/Color.h> #include <Magnum/Math/Vector3.h> #include <Magnum/Trade/AbstractImporter.h> #include <Magnum/Trade/MeshData3D.h> #include "configure.h" namespace Magnum { namespace Trade { namespace Test { namespace { struct StanfordImporterTest: TestSuite::Tester { explicit StanfordImporterTest(); void invalidSignature(); void formatInvalid(); void formatUnsupported(); void formatMissing(); void formatTooLate(); void unknownLine(); void unknownElement(); void unexpectedProperty(); void invalidVertexProperty(); void invalidVertexType(); void invalidFaceProperty(); void invalidFaceType(); void invalidFaceSizeType(); void invalidFaceIndexType(); void incompleteVertex(); void incompleteFace(); void fileDoesNotExist(); void fileTooShort(); void invalidFaceSize(); void openFile(); void openData(); void empty(); void colors(); void unaligned(); void bigEndian(); void crlf(); void ignoredVertexComponents(); void ignoredFaceComponents(); void openTwice(); void importTwice(); /* Explicitly forbid system-wide plugin dependencies */ PluginManager::Manager<AbstractImporter> _manager{"nonexistent"}; }; StanfordImporterTest::StanfordImporterTest() { addTests({&StanfordImporterTest::invalidSignature, &StanfordImporterTest::formatInvalid, &StanfordImporterTest::formatUnsupported, &StanfordImporterTest::formatMissing, &StanfordImporterTest::formatTooLate, &StanfordImporterTest::unknownLine, &StanfordImporterTest::unknownElement, &StanfordImporterTest::unexpectedProperty, &StanfordImporterTest::invalidVertexProperty, &StanfordImporterTest::invalidVertexType, &StanfordImporterTest::invalidFaceProperty, &StanfordImporterTest::invalidFaceType, &StanfordImporterTest::invalidFaceSizeType, &StanfordImporterTest::invalidFaceIndexType, &StanfordImporterTest::incompleteVertex, &StanfordImporterTest::incompleteFace, &StanfordImporterTest::fileDoesNotExist, &StanfordImporterTest::fileTooShort, &StanfordImporterTest::invalidFaceSize, &StanfordImporterTest::openFile, &StanfordImporterTest::openData, &StanfordImporterTest::empty, &StanfordImporterTest::colors, &StanfordImporterTest::unaligned, &StanfordImporterTest::bigEndian, &StanfordImporterTest::crlf, &StanfordImporterTest::ignoredVertexComponents, &StanfordImporterTest::ignoredFaceComponents, &StanfordImporterTest::openTwice, &StanfordImporterTest::importTwice}); /* Load the plugin directly from the build tree. Otherwise it's static and already loaded. */ #ifdef STANFORDIMPORTER_PLUGIN_FILENAME CORRADE_INTERNAL_ASSERT(_manager.load(STANFORDIMPORTER_PLUGIN_FILENAME) & PluginManager::LoadState::Loaded); #endif } void StanfordImporterTest::invalidSignature() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-signature.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid file signature bla\n"); } void StanfordImporterTest::formatInvalid() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "format-invalid.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid format line format binary_big_endian 1.0 extradata\n"); } void StanfordImporterTest::formatUnsupported() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "format-unsupported.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): unsupported file format ascii 1.0\n"); } void StanfordImporterTest::formatMissing() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "format-missing.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): missing format line\n"); } void StanfordImporterTest::formatTooLate() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "format-too-late.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): expected format line, got element face 1\n"); } void StanfordImporterTest::unknownLine() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "unknown-line.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): unknown line heh\n"); } void StanfordImporterTest::unknownElement() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "unknown-element.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): unknown element edge\n"); } void StanfordImporterTest::unexpectedProperty() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "unexpected-property.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): unexpected property line\n"); } void StanfordImporterTest::invalidVertexProperty() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-vertex-property.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid vertex property line property float x extradata\n"); } void StanfordImporterTest::invalidVertexType() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-vertex-type.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid vertex component type float16\n"); } void StanfordImporterTest::invalidFaceProperty() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-face-property.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid face property line property float x extradata\n"); } void StanfordImporterTest::invalidFaceType() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-face-type.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid face component type float16\n"); } void StanfordImporterTest::invalidFaceSizeType() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-face-size-type.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid face size type int128\n"); } void StanfordImporterTest::invalidFaceIndexType() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-face-index-type.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): invalid face index type int128\n"); } void StanfordImporterTest::incompleteVertex() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "incomplete-vertex.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): incomplete vertex specification\n"); } void StanfordImporterTest::incompleteFace() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "incomplete-face.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): incomplete face specification\n"); } void StanfordImporterTest::fileDoesNotExist() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(!importer->openFile("nonexistent.ply")); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::openFile(): cannot open file nonexistent.ply\n"); } void StanfordImporterTest::fileTooShort() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "short-file.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): file is too short\n"); } void StanfordImporterTest::invalidFaceSize() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); std::ostringstream out; Error redirectError{&out}; CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "invalid-face-size.ply"))); CORRADE_VERIFY(!importer->mesh3D(0)); CORRADE_COMPARE(out.str(), "Trade::StanfordImporter::mesh3D(): unsupported face size 5\n"); } /* First face is quad, second is triangle. 0--3--4 |\ | / | \|/ 1--2 */ const std::vector<UnsignedInt> Indices{0, 1, 2, 0, 2, 3, 3, 2, 4}; const std::vector<Vector3> Positions{ {1.0f, 3.0f, 2.0f}, {1.0f, 1.0f, 2.0f}, {3.0f, 3.0f, 2.0f}, {3.0f, 1.0f, 2.0f}, {5.0f, 3.0f, 9.0f} }; const std::vector<Color4> Colors{ {0.8f, 0.2f, 0.399222f}, {0.6f, 0.666667f, 0.996887f}, {0.0f, 0.0666667f, 0.93048f}, {0.733333f, 0.866667f, 0.133593f}, {0.266667f, 0.333333f, 0.465629f} }; void StanfordImporterTest::openFile() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "common.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(!mesh->hasColors()); } void StanfordImporterTest::openData() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openData(Utility::Directory::read(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "common.ply")))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(!mesh->hasColors()); } void StanfordImporterTest::empty() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "empty.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_VERIFY(!mesh->isIndexed()); CORRADE_VERIFY(mesh->positions(0).empty()); } void StanfordImporterTest::colors() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "colors.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(mesh->hasColors()); CORRADE_COMPARE(mesh->colors(0), Colors); } void StanfordImporterTest::unaligned() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "unaligned.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), (std::vector<UnsignedInt>{ 0x01234567, 0x89abcdef, 0x01234567, 0x01234567, 0x89abcdef, 0x01234567 })); CORRADE_COMPARE(mesh->positions(0), (std::vector<Vector3>{ {Float(0x12), Float(0x3456789a), 12345678901234567890.0f}, {Float(0xbc), Float(0xdef01234), 98765432109876543210.0f} })); } void StanfordImporterTest::bigEndian() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "big-endian.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(mesh->hasColors()); CORRADE_COMPARE(mesh->colors(0), Colors); } void StanfordImporterTest::crlf() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "crlf.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(!mesh->hasColors()); } void StanfordImporterTest::ignoredVertexComponents() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "ignored-vertex-components.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(!mesh->hasColors()); } void StanfordImporterTest::ignoredFaceComponents() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "ignored-face-components.ply"))); auto mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->indices(), Indices); CORRADE_COMPARE(mesh->positions(0), Positions); CORRADE_VERIFY(!mesh->hasColors()); } void StanfordImporterTest::openTwice() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "common.ply"))); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "common.ply"))); /* Shouldn't crash, leak or anything */ } void StanfordImporterTest::importTwice() { Containers::Pointer<AbstractImporter> importer = _manager.instantiate("StanfordImporter"); CORRADE_VERIFY(importer->openFile(Utility::Directory::join(STANFORDIMPORTER_TEST_DIR, "common.ply"))); /* Verify that everything is working the same way on second use */ { Containers::Optional<Trade::MeshData3D> mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->positions(0), Positions); } { Containers::Optional<Trade::MeshData3D> mesh = importer->mesh3D(0); CORRADE_VERIFY(mesh); CORRADE_COMPARE(mesh->positions(0), Positions); } } }}}} CORRADE_TEST_MAIN(Magnum::Trade::Test::StanfordImporterTest)
40.137577
132
0.728398
bowling-allie
bcc056cd984d5fea6f448def9c6a7416d312f9ab
1,731
cpp
C++
src/Config.cpp
pezcode/Cluster
2e5d7a1bea0493ff3554dc329b83db950cb49eff
[ "MIT" ]
243
2019-11-21T11:35:43.000Z
2022-03-13T11:56:25.000Z
src/Config.cpp
pezcode/Cluster
2e5d7a1bea0493ff3554dc329b83db950cb49eff
[ "MIT" ]
7
2020-01-24T15:07:23.000Z
2021-06-04T04:33:09.000Z
src/Config.cpp
pezcode/Cluster
2e5d7a1bea0493ff3554dc329b83db950cb49eff
[ "MIT" ]
18
2019-11-21T11:35:49.000Z
2022-02-09T20:06:14.000Z
#include "Config.h" #include <bx/commandline.h> #include "Renderer/Renderer.h" Config::Config() : writeLog(true), logFile("Cluster.log"), renderer(bgfx::RendererType::Count), // default renderer, chosen by platform renderPath(Cluster::RenderPath::Clustered), tonemappingMode(Renderer::TonemappingMode::ACES), multipleScattering(true), whiteFurnace(false), profile(true), vsync(false), sceneFile("assets/models/Sponza/Sponza.gltf"), customScene(false), lights(1), maxLights(3000), movingLights(false), fullscreen(false), showUI(true), showConfigWindow(true), showLog(false), showStatsOverlay(false), overlays({ true, true, true, true }), showBuffers(false), debugVisualization(false) { } void Config::readArgv(int argc, char* argv[]) { // argv must outlive Config // we store pointers into argv for the scene file bx::CommandLine cmdLine(argc, argv); if(cmdLine.hasArg("noop")) renderer = bgfx::RendererType::Noop; else if(cmdLine.hasArg("gl")) renderer = bgfx::RendererType::OpenGL; else if(cmdLine.hasArg("vk")) renderer = bgfx::RendererType::Vulkan; // missing required features //else if(cmdLine.hasArg("d3d9")) // renderer = bgfx::RendererType::Direct3D9; else if(cmdLine.hasArg("d3d11")) renderer = bgfx::RendererType::Direct3D11; else if(cmdLine.hasArg("d3d12")) renderer = bgfx::RendererType::Direct3D12; // not tested //else if(cmdLine.hasArg("mtl")) // renderer = bgfx::RendererType::Metal; const char* scene = cmdLine.findOption("scene"); if(scene) { sceneFile = scene; customScene = true; } }
27.919355
80
0.649913
pezcode
bcc24ea20aa53be8adc810359c0791135d4d58ae
439
cpp
C++
cpp_sandbox/wxw_attempt/wxwidgets_practice.cpp
kjgonzalez/codefiles
b86f25182d1b5553a331f8721dd06b51fa157c3e
[ "MIT" ]
null
null
null
cpp_sandbox/wxw_attempt/wxwidgets_practice.cpp
kjgonzalez/codefiles
b86f25182d1b5553a331f8721dd06b51fa157c3e
[ "MIT" ]
10
2019-10-01T20:48:15.000Z
2020-04-14T18:21:09.000Z
cpp_sandbox/wxw_attempt/wxwidgets_practice.cpp
kjgonzalez/codefiles
b86f25182d1b5553a331f8721dd06b51fa157c3e
[ "MIT" ]
null
null
null
/* date: 200205 objective: try to make a simple gui with buttons, and will build up from there NOTES: * don't need an "int main" thing need a class that represents what the application is. "pixel game engine" ??? stat | description ???? | ??? ???? | ??? ???? | ??? ???? | ??? ???? | ??? ???? | ??? */ #include <iostream> #include <wx/wx.h> class cApp : public wxApp{ public: cApp(); ~cApp(); public: virtual bool OnInit }
14.633333
78
0.585421
kjgonzalez
bcc4576d45258fcbc2ba1a95851fc8e32d457201
394
hpp
C++
pieces/Exception.hpp
ismo-karkkainen/specificjson
e948881dad57d79908a31c73f92ed4a34f2f026b
[ "UPL-1.0" ]
null
null
null
pieces/Exception.hpp
ismo-karkkainen/specificjson
e948881dad57d79908a31c73f92ed4a34f2f026b
[ "UPL-1.0" ]
null
null
null
pieces/Exception.hpp
ismo-karkkainen/specificjson
e948881dad57d79908a31c73f92ed4a34f2f026b
[ "UPL-1.0" ]
null
null
null
class Exception : public std::exception { private: const char* reason; public: Exception(const char* Reason) : reason(Reason) { } const char* what() const throw() { return reason; } }; class ContextException : public Exception { private: char context[64]; public: ContextException(const Exception& E, const char* Begin, const char* Current, const char* End); };
20.736842
65
0.675127
ismo-karkkainen
3449eb11e34cd9099368b15ec6f150de155dd4bb
111
cpp
C++
Graph Algorithms/BFS.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
2
2019-10-20T03:13:35.000Z
2020-06-23T16:23:35.000Z
Graph Algorithms/BFS.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
2
2019-10-01T16:02:25.000Z
2020-01-30T18:28:38.000Z
Graph Algorithms/BFS.cpp
moinak878/Data-Structures-and-Algorithms-
75692d39c50e57121f12eb8175aa2de13c13196d
[ "MIT" ]
5
2020-01-30T17:08:21.000Z
2020-10-01T13:48:22.000Z
#include <vector> #include <iostream> using namespace std; //graphs adjacency list given int main(){ }
12.333333
29
0.684685
moinak878
344ac20976c6d0485ffe4afa041a10e829c3c82e
1,448
cpp
C++
Source_/HeroDebugModule/Private/HeroDebuggerCategory_OwnedTag.cpp
JiaqiJin/RPGPrototype_ue4
e328798e880089841c0bfea1e25abee045dbf447
[ "MIT" ]
2
2021-09-25T19:34:12.000Z
2021-09-29T10:52:55.000Z
Source_/HeroDebugModule/Private/HeroDebuggerCategory_OwnedTag.cpp
JiaqiJin/RPGPrototype_ue4
e328798e880089841c0bfea1e25abee045dbf447
[ "MIT" ]
null
null
null
Source_/HeroDebugModule/Private/HeroDebuggerCategory_OwnedTag.cpp
JiaqiJin/RPGPrototype_ue4
e328798e880089841c0bfea1e25abee045dbf447
[ "MIT" ]
null
null
null
#include "HeroDebuggerCategory_OwnedTag.h" #if WITH_GAMEPLAY_DEBUGGER #include "AbilitySystemComponent.h" #include "AbilitySystemGlobals.h" #include "GameplayEffect.h" #include "GameplayAbilitySpec.h" #include "GameplayDebugger.h" #include "GameplayTagContainer.h" HeroDebuggerCategory_OwnedTag::HeroDebuggerCategory_OwnedTag() { bShowOnlyWithDebugActor = false; } /** Creates an instance of this category - will be used on module startup to include our category in the Editor */ TSharedRef<FGameplayDebuggerCategory> HeroDebuggerCategory_OwnedTag::MakeInstance() { return MakeShareable(new HeroDebuggerCategory_OwnedTag()); } /** Collects the data we would like to print */ void HeroDebuggerCategory_OwnedTag::CollectData(class APlayerController* OwnerPC, class AActor* DebugActor) { UAbilitySystemComponent* AbilityComp = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(OwnerPC); if (AbilityComp) { static FGameplayTagContainer OwnerTags; OwnerTags.Reset(); AbilityComp->GetOwnedGameplayTags(OwnerTags); for (const FGameplayTag& Tag : OwnerTags) { OwnedTags.AddUnique(Tag.ToString()); } } } /** Displays the data we collected in the CollectData function */ void HeroDebuggerCategory_OwnedTag::DrawData(class APlayerController* OwnerPC, class FGameplayDebuggerCanvasContext& CanvasContext) { if (OwnerPC) { for (FString Tags : OwnedTags) { CanvasContext.Print(FColor::Yellow, Tags); } } } #endif
28.392157
131
0.791436
JiaqiJin
3457529236d584234fa2924ecfd856fdc6388cf9
531
cpp
C++
GeeksForGeeks/Detect cycle in an undirected graph.cpp
DSC-IIITKota/coding-platform
f596f3e2677c353a4723633ddb3b499df8791037
[ "MIT" ]
null
null
null
GeeksForGeeks/Detect cycle in an undirected graph.cpp
DSC-IIITKota/coding-platform
f596f3e2677c353a4723633ddb3b499df8791037
[ "MIT" ]
null
null
null
GeeksForGeeks/Detect cycle in an undirected graph.cpp
DSC-IIITKota/coding-platform
f596f3e2677c353a4723633ddb3b499df8791037
[ "MIT" ]
1
2020-12-04T12:46:52.000Z
2020-12-04T12:46:52.000Z
bool helper(int node, int parent, vector<bool> &visited, vector<int> g[]){ visited[node] = true; for(auto i : g[node]){ if(!visited[i]){ if(helper(i, node, visited, g)) return true; } else if(i!=parent || i==node) return true; } return false; } bool isCyclic(vector<int> g[], int V) { vector<bool> visited(V, false); for(int i=0;i<V;i++){ if(!visited[i] && helper(i, -1, visited, g)) return true; } return false; }
24.136364
74
0.504708
DSC-IIITKota
346c3e99e424048708e943c89a9f5b91abd3a83c
213
hpp
C++
third-party/sprawl/include/sprawl/common/noncopyable.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
third-party/sprawl/include/sprawl/common/noncopyable.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
third-party/sprawl/include/sprawl/common/noncopyable.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
#pragma once namespace sprawl { class noncopyable; } class sprawl::noncopyable { public: noncopyable() {} private: noncopyable(const noncopyable& other); noncopyable& operator=(const noncopyable& other); };
13.3125
50
0.746479
3Jade
346d2bf5d56aec1140d7113b1d67bb22a1eb9492
2,554
hpp
C++
libEPLViz/src/mainWidgets/PluginSelectorWidget.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
3
2017-01-23T13:29:21.000Z
2021-03-08T17:40:42.000Z
libEPLViz/src/mainWidgets/PluginSelectorWidget.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
4
2017-03-26T12:56:08.000Z
2017-08-18T20:32:37.000Z
libEPLViz/src/mainWidgets/PluginSelectorWidget.hpp
epl-viz/EPL-Viz
80d790110113f83da6845ce124997d13bfd45270
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017, EPL-Vizards * 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 EPL-Vizards 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 EPL-Vizards 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 PluginSelectorWidget.hpp */ #pragma once #include "MainWindow.hpp" #include "PythonPlugin.hpp" #include <QCheckBox> #include <QDir> #include <QFile> #include <QListWidget> #include <QMap> #include <QMessageBox> namespace EPL_Viz { class PluginSelectorWidget : public QListWidget { Q_OBJECT private: bool recording = false; EPL_DataCollect::PluginManager *pluginManager = nullptr; MainWindow * main = nullptr; QString pluginPath; QList<QString> plugins; public: PluginSelectorWidget(QWidget *parent = nullptr); ~PluginSelectorWidget() = default; void setMainWindow(MainWindow *mw); private: void addItem(QString plugin); /*private slots: void changeState(int state);*/ public slots: void loadPlugins(EPL_DataCollect::CaptureInstance *ci); void setPlugins(QMap<QString, QString> map); void updatePluginFolder(); void reset(); void savePlugins(); }; }
34.513514
82
0.723962
epl-viz
346e17f4393de3cb209d82fc6647b18cc5cf1b36
2,271
cpp
C++
introduction_to_cpp_programming/Statistics/statistics.cpp
CalciumCat/cpp-playground
21cc96e00f4bea768bbc3cb3f6f820ca81eab973
[ "MIT" ]
null
null
null
introduction_to_cpp_programming/Statistics/statistics.cpp
CalciumCat/cpp-playground
21cc96e00f4bea768bbc3cb3f6f820ca81eab973
[ "MIT" ]
null
null
null
introduction_to_cpp_programming/Statistics/statistics.cpp
CalciumCat/cpp-playground
21cc96e00f4bea768bbc3cb3f6f820ca81eab973
[ "MIT" ]
null
null
null
/* statistics.cpp contains functions that calculate the average and standard deviation of 1, 2, 3 or 4 real values */ #include<iostream> #include<cmath> #include "statistics.h" using namespace std; /* Function to calculate the average of one number */ double average(double first){ return first; } /* Function to calculate the average of two numbers */ double average(double first, double second){ double mean; mean = (first + second)/2; return mean; } /* Function to calculate the average of three numbers */ double average(double first, double second, double third){ double mean; mean = (first + second + third)/3; return mean; } /* Function to calculate the average of four numbers */ double average(double first, double second, double third, double fourth){ double mean; mean = (first + second + third + fourth)/4; return mean; } /* Function to calculate the standard deviation of one number */ double standard_deviation(double first) { return 0; } /* Function to calculate the standard deviation of two numbers. */ double standard_deviation(double first, double second) { double first_arg, second_arg; double mean; mean = average(first, second); first_arg = (first - mean)*(first - mean); second_arg = (second - mean)*(second - mean); return sqrt(average(first_arg, second_arg)); } /* Function to calculate the standard deviation of three numbers. */ double standard_deviation(double first, double second, double third) { double first_arg, second_arg, third_arg; double mean; mean = average(first, second, third); first_arg = (first - mean)*(first -mean); second_arg = (second - mean)*(second - mean); third_arg = (third - mean)*(third - mean); return sqrt(average(first_arg, second_arg, third_arg)); } /* Function to calculate the standard deviation of four numbers. */ double standard_deviation(double first, double second, double third, double fourth) { double first_arg, second_arg, third_arg, fourth_arg; double mean; mean = average(first, second, third, fourth); first_arg = (first - mean)*(first -mean); second_arg = (second - mean)*(second - mean); third_arg = (third - mean)*(third - mean); fourth_arg = (fourth - mean)*(fourth - mean); return sqrt(average(first_arg, second_arg, third_arg, fourth_arg)); }
28.746835
85
0.726112
CalciumCat
347bd0f8d9e4b13ec2b4100dcdd1dcd221aefefe
1,067
cpp
C++
ext/n7zip/streams/out_stream.cpp
yagisumi/node-n7zip
d9648a99734115cead0c148fba6b0729a77eda1b
[ "MIT" ]
null
null
null
ext/n7zip/streams/out_stream.cpp
yagisumi/node-n7zip
d9648a99734115cead0c148fba6b0729a77eda1b
[ "MIT" ]
1
2020-10-16T17:26:54.000Z
2020-10-16T17:26:54.000Z
ext/n7zip/streams/out_stream.cpp
yagisumi/node-n7zip
d9648a99734115cead0c148fba6b0729a77eda1b
[ "MIT" ]
null
null
null
#include "out_stream.h" #include "../reader/extract_worker.h" namespace n7zip { OutStream::OutStream(UInt32 index, ExtractWorker* worker, UInt32 limit) : m_index(index) , m_worker(worker) { TRACE_THIS("+ OutStream"); if (limit > MIN_LIMIT) { m_limit = limit; } m_buffer = std::make_unique<OutBufferData>(m_index, m_length); } OutStream::~OutStream() { TRACE_THIS("- OutStream"); } STDMETHODIMP OutStream::Write(const void* data, UInt32 size, UInt32* processedSize) { TRACE_THIS("[OutStream::Write] size: %u", size); if (m_buffer) { m_buffer->append((const char*)data, size); *processedSize = size; m_length += size; if (m_length >= m_limit) { m_worker->post_buffer(std::move(purge())); m_buffer = std::make_unique<OutBufferData>(m_index, m_length); } return S_OK; } else { *processedSize = 0; return E_FAIL; } } std::unique_ptr<OutBufferData> OutStream::purge() { return std::move(m_buffer); } void OutStream::set_done(Int32 result) { m_buffer->set_done(result); } } // namespace n7zip
19.759259
71
0.671978
yagisumi
3488c980390ca04d2093e567051f18001e437889
698
cpp
C++
PETCS/Advanced/ccc12s5.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Advanced/ccc12s5.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
PETCS/Advanced/ccc12s5.cpp
dl4us/Competitive-Programming-1
d42fab3bd68168adbe4b5f594f19ee5dfcd1389b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int MAX = 30; int R, C, K, dp[MAX][MAX]; bool cat[MAX][MAX]; int main() { cin.tie(0)->sync_with_stdio(0); #ifndef ONLINE_JUDGE freopen("../../input.txt", "r", stdin); freopen("../../output.txt", "w", stdout); #endif cin >> R >> C >> K; for(int i = 0, r, c; i < K; i++) { cin >> r >> c; cat[r][c] = true; } dp[1][1] = 1; for(int i = 1; i <= R; i++) { for(int j = 1; j <= C; j++) { if(cat[i][j] or (i == 1 and j == 1)) { continue; } dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } cout << dp[R][C] << "\n"; return 0; }
24.928571
50
0.406877
dl4us
34974bf01c6e284c51a6e036a32a9838985c1f88
1,951
cpp
C++
midisong.cpp
shikolad/PianoPractice
9d705f2064dcc5499f2a7feb1975164523912249
[ "MIT" ]
null
null
null
midisong.cpp
shikolad/PianoPractice
9d705f2064dcc5499f2a7feb1975164523912249
[ "MIT" ]
null
null
null
midisong.cpp
shikolad/PianoPractice
9d705f2064dcc5499f2a7feb1975164523912249
[ "MIT" ]
null
null
null
#include "midisong.h" #include <QFile> #include <QDataStream> MidiSong::MidiSong(QObject *parent) : QObject(parent) { } MidiSong::~MidiSong() { } void MidiSong::addTrack(MidiTrack *track){ trackList.append(track); } MidiSong *MidiSong::loadFromFile(QString filePath){ QFile file; file.setFileName(filePath); if (!file.open(QIODevice::ReadOnly)){ return NULL; //todo handle error } QDataStream stream(&file); stream.setByteOrder(QDataStream::BigEndian); //header chunk reading const int headerMagic = 0x4d546864;//"MThd" string quint32 file_magic; stream >> file_magic; if (headerMagic != file_magic){ //todo not a midi file } quint32 headerSize; stream >> headerSize; if (headerSize != 6){ //todo non standart midi file } qint16 format, trackNumber, division; stream >> format; stream >> trackNumber; stream >> division; MidiSong *song = new MidiSong(); while (!stream.atEnd()){ MidiTrack *track = new MidiTrack(song); stream >> (*track); song->addTrack(track); } file.close(); return song; } QList<MidiEvent*> MidiSong::getMidiEvents(qint32 time){ QList<MidiEvent*> result; foreach (MidiTrack *track, trackList) { QList<MidiEvent*> events = track->getEvents(time); foreach (MidiEvent *ev, events) { result.push_front(ev); } } return result; } qint32 MidiSong::getNextDelta(qint32 time){ qint32 nextDelta = -1; if (!trackList.isEmpty()){ QVector<MidiTrack*>::iterator iterator = trackList.begin() + 1; nextDelta = (*iterator)->getNextDelta(time); iterator++; while (iterator != trackList.end()) { qint32 tmp = (*iterator)->getNextDelta(time); if ((tmp < nextDelta) && (tmp != -1)) nextDelta = tmp; } } return nextDelta; }
21.206522
71
0.604818
shikolad
34a5062f7bfd22d0b9dbce3a722ddb2caf970d13
2,255
cpp
C++
src/coloc_node.cpp
saihv/coloc
260e78eb34b1b86928ac0bd3ddf29072325c7a2e
[ "MIT" ]
7
2018-10-24T05:12:48.000Z
2021-12-28T08:08:17.000Z
src/coloc_node.cpp
saihv/coloc
260e78eb34b1b86928ac0bd3ddf29072325c7a2e
[ "MIT" ]
1
2019-02-21T10:13:11.000Z
2019-02-24T18:30:05.000Z
src/coloc_node.cpp
saihv/coloc
260e78eb34b1b86928ac0bd3ddf29072325c7a2e
[ "MIT" ]
4
2018-10-31T04:02:04.000Z
2021-04-23T07:41:16.000Z
#include "coloc/coloc.hpp" using namespace openMVG; void readCalibData(std::pair <int, int>& imageSize, std::vector<Mat3>& K, std::vector<Vec3>& dist, std::string& fileName, unsigned int& numDrones) { std::ifstream calibData; calibData.open(fileName); std::string line; std::vector<double> values; std::getline(calibData, line); std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { values.push_back(std::stod(cell)); } imageSize.first = values[0]; imageSize.second = values[1]; values.clear(); uint rows = 0; while (rows < numDrones) { std::getline(calibData, line); std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { values.push_back(std::stod(cell)); } Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > copiedMatrix(&values[0]); K.push_back(copiedMatrix); values.clear(); ++rows; } rows = 0; while (rows < numDrones) { std::getline(calibData, line); std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { values.push_back(std::stod(cell)); } Eigen::Vector3d copiedMatrix = Eigen::Map<Eigen::Vector3d>(&values[0], 3, 1); dist.push_back(copiedMatrix); values.clear(); ++rows; } } int main(int argc, char **argv) { #ifdef USE_ROS ros::init(argc, argv, "coloc"); ros::NodeHandle nh; #endif unsigned int numDrones = 2; Mat3 tempK; Vec3 tempdist; std::pair <int, int> imageSize; std::vector <Mat3> K; std::vector <Vec3> dist; std::string imageFolder = "/home/sai/sampleColoc/"; std::string calibFilename = imageFolder + "calib.txt"; readCalibData(imageSize, K, dist, calibFilename, numDrones); DetectorOptions Dopts; MatcherOptions Mopts; Dopts.width = imageSize.first; Dopts.height = imageSize.second; Dopts.maxkp = 5000; Dopts.scale_factor = 1.2; Dopts.scale_levels = 8; Dopts.thresh = 40; Mopts.distRatio = 0.8; Mopts.maxkp = 5000; Mopts.thresh = 60; coloc::colocParams params(K, dist, 'E', std::make_pair(imageSize.first, imageSize.second), imageFolder, Dopts, Mopts); int nStart = 0; ColoC coloc(numDrones, nStart, params, Dopts, Mopts); coloc.mainThread(); return 0; }
23.489583
146
0.680266
saihv
34a52666fb7f98df5a07fc1ff2bd56dca263a605
1,240
cpp
C++
source/graphics/hal/vulkan/vulkanpipelinestatemanager.cpp
lukaklar/Khan-Engine
2496366759649d282d725fa637b25fb1e0d4fdfa
[ "Apache-2.0" ]
null
null
null
source/graphics/hal/vulkan/vulkanpipelinestatemanager.cpp
lukaklar/Khan-Engine
2496366759649d282d725fa637b25fb1e0d4fdfa
[ "Apache-2.0" ]
null
null
null
source/graphics/hal/vulkan/vulkanpipelinestatemanager.cpp
lukaklar/Khan-Engine
2496366759649d282d725fa637b25fb1e0d4fdfa
[ "Apache-2.0" ]
null
null
null
#include "graphics/precomp.h" #ifdef KH_GFXAPI_VULKAN #include "graphics/hal/vulkan/vulkanpipelinestatemanager.hpp" namespace Khan { void VulkanPipelineStateManager::Create(VkDevice device) { // TODO: Load pipeline cache m_PipelineCache = VK_NULL_HANDLE; } void VulkanPipelineStateManager::Destroy(VkDevice device) { // TODO: Save and destroy pipeline cache for (auto& it : m_GraphicsPipelineCache) { VulkanPipelineState& pipelineState = *it.second; vkDestroyPipeline(device, pipelineState.m_Pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineState.m_PipelineLayout, nullptr); for (VkDescriptorSetLayout descriptorSetLayout : pipelineState.m_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); } } for (auto& it : m_ComputePipelineCache) { VulkanPipelineState& pipelineState = *it.second; vkDestroyPipeline(device, pipelineState.m_Pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineState.m_PipelineLayout, nullptr); for (VkDescriptorSetLayout descriptorSetLayout : pipelineState.m_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); } } } } #endif // KH_GFXAPI_VULKAN
27.555556
88
0.779032
lukaklar
34a89aa4a8ce1d5355c55b9a53baf54a7c93f94f
2,903
cpp
C++
SRM615/AmebaDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM615/AmebaDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
SRM615/AmebaDiv1.cpp
CanoeFZH/SRM
02e3eeaa6044b14640e450725f68684e392009cb
[ "MIT" ]
null
null
null
// BEGIN CUT HERE // END CUT HERE #include <sstream> #include <cstdio> #include <cstdlib> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <map> #include <string> #include <set> #include <algorithm> using namespace std; class AmebaDiv1 { public: int count(vector <int> X) { set <int> S, xS; for (auto &x: X) { xS.insert(x); } for (int i = 0; i < X.size(); i++) { set <int> possibleSet; possibleSet.insert(X[i]); for (int j = i - 1; j >= 0; j--) { if (possibleSet.find(X[j]) != possibleSet.end()) { possibleSet.erase(X[j]); } if (possibleSet.find(2 * X[j]) != possibleSet.end()) { possibleSet.insert(X[j]); } } if (possibleSet.size() != 0) { S.insert(X[i]); if (xS.find(2 * X[i]) != xS.end()){ S.erase(2 * X[i]); } } } return S.size(); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {3,2,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(0, Arg1, count(Arg0)); } void test_case_1() { int Arr0[] = {2,2,2,2,2,2,4,2,2,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(1, Arg1, count(Arg0)); } void test_case_2() { int Arr0[] = {1,2,4,8,16,32,64,128,256,1024,2048}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 11; verify_case(2, Arg1, count(Arg0)); } void test_case_3() { int Arr0[] = {854,250,934,1000,281,250,281,467,854,562,934,1000,854,500,562}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; verify_case(3, Arg1, count(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main(){ AmebaDiv1 ___test; ___test.run_test(-1); return 0; } // END CUT HERE
40.887324
308
0.512573
CanoeFZH
34ab57be203613de1a4e9556f905b46a39c5c211
41,087
cpp
C++
source/dataIO/dataio_silo_utility.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
4
2020-08-20T11:31:22.000Z
2020-12-05T13:30:03.000Z
source/dataIO/dataio_silo_utility.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
null
null
null
source/dataIO/dataio_silo_utility.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
4
2020-08-20T14:33:19.000Z
2022-03-07T10:29:34.000Z
/// \file dataio_silo_utility.cpp /// \author Jonathan Mackey /// /// This is code for analysing silo data files in serial mode; /// written so that a single function will determine if the file is /// serial or parallel and read in the data regardless. It gets the /// parameters for the grid from the header. /// /// /// - 2010-02-02 JM: Added support for N procs to read data written /// by M procs, where N not equal to M. /// - 2010-02-03 JM: Fixed all the bugs in yesterday's work (as far /// as i could find). /// - 2010-04-27 JM: renamed 'ngroups' to 'groupsize', and updated /// logic so the last file can have fewer domains. /// - 2010.11.15 JM: replaced endl with c-style newline chars. /// - 2011.03.02 JM: Better handling of tracer variables (up to /// MAX_NVAR now). /// - 2012.05.17 JM: Fixed bug in how pllel_read_any_data() dealt /// with silo databases where files don't all have the same number /// of meshes. /// - 2013.02.19 JM: Got rid of dataio_utility class, and moved its /// functions into file_status class, which now has its own file. /// Renamed file to dataio_silo_utility.cpp from dataio_utility.cc /// - 2015.01.15 JM: Added new include statements for new PION version. /// - 2015.03.26 JM: updated for pion v0.2 /// - 2015.06.13 JM: started updating to work with void* pointers for /// coordinates and data variables (they can be float or double). /// - 2016.03.18 JM: updated to work better with large grids and with /// FLOAT and DOUBLE data (no buggy integer positions anymore...). /// - 2016.04.04 JM: fixed bug in get_quadmesh_integer_extents() for /// xmin/xmax<0. #include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/mem_manage.h" #include "tools/timer.h" #ifdef TESTING #include "tools/command_line_interface.h" #endif // TESTING #include "dataIO/dataio_silo_utility.h" #include <iostream> #include <sstream> using namespace std; //#define TEST_SILO_IO /********************************************************/ /*************** dataio_silo_utility ********************/ /********************************************************/ dataio_silo_utility::dataio_silo_utility( class SimParams &SimPM, ///< pointer to simulation parameters std::string dtype, ///< FLOAT or DOUBLE for files. class MCMDcontrol *p ) : dataio_silo_pllel(SimPM, dtype,p) { #ifdef TEST_SILO_IO cout <<"Setting up utility Silo I/O class.\n"; #endif return; } // ################################################################## // ################################################################## int dataio_silo_utility::SRAD_get_nproc_numfiles( string fname, int *np, int *nf ) { int err=0; // // open file // #ifdef TEST_SILO_IO cout <<"opening file: "<<fname<<"\n"; #endif DBfile *dbfile = 0; dbfile = DBOpen(fname.c_str(), DB_UNKNOWN, DB_READ); if (!dbfile) rep.error("open silo file failed.",dbfile); // // read nproc, numfiles from header // DBSetDir(dbfile,"/header"); int nproc=0, numfiles=0; //, groupsize=0; err += DBReadVar(dbfile,"MPI_nproc",&nproc); err += DBReadVar(dbfile,"NUM_FILES",&numfiles); if (err) { #ifdef TEST_SILO_IO cout <<"must be serial file -- failed to find NUM_FILES and MPI_nproc\n"; cout <<"continuing assuming serial file....\n"; #endif //rep.error("error reading params from file",fname); nproc=1; numfiles=1; //groupsize=1; } else { #ifdef TEST_SILO_IO cout <<"\tRead nproc="<<nproc<<"\tand numfiles="<<numfiles<<"\n"; #endif // groupsize = nproc/numfiles; //nproc = nproc; } DBClose(dbfile); dbfile=0; string::size_type pos = fname.find("_0000"); if (pos==string::npos) { cout <<"didn't find _0000 in file, so we are reading serial file\n"; err = 1; } *np = nproc; *nf = numfiles; #ifdef TEST_SILO_IO cout <<"dataio_silo_utility::SRAD_get_nproc_numfiles returning "<<err<<"\n"; #endif return err; } // ################################################################## // ################################################################## bool dataio_silo_utility::SRAD_point_on_my_domain( const cell *c, ///< pointer to cell class SimParams &SimPM, ///< pointer to simulation parameters class MCMDcontrol *filePM ///< pointer to class with nproc. ) { // // Assume point is on domain, and set to false if found to be off. // bool on=true; double dpos[SimPM.ndim]; CI.get_dpos(c,dpos); for (int i=0; i<SimPM.ndim; i++) { if (dpos[i]<filePM->LocalXmin[i]) on=false; if (dpos[i]>filePM->LocalXmax[i]) on=false; } return on; } // ################################################################## // ################################################################## int dataio_silo_utility::SRAD_read_var2grid( DBfile *dbfile, ///< pointer to silo file. class GridBaseClass *ggg, ///< pointer to data. const string variable, ///< variable name to read. const long int npt, ///< number of cells expected. class SimParams &SimPM, ///< pointer to simulation parameters class MCMDcontrol *filePM ///< pointer to class with nproc. ) { // // The dbfile pointer should already be in the directory containing // the named variable to read, so it's ok to bug out if we don't // find it. // DBquadvar *silodata=0; silodata = DBGetQuadvar(dbfile,variable.c_str()); if (!silodata) { rep.error("dataio_silo::read_variable2grid() failed to read variable", variable); } if (silodata->nels != npt) { rep.error("dataio_silo::read_variable2grid() wrong number of cells", silodata->nels-SimPM.Ncell); } // // Check that datatype is what we are expecting! If not, then // delete data arrays, reset datatype, and re-create data arrays. // if (silodata->datatype != silo_dtype) { #ifdef TEST_SILO_IO cout <<"\n\tSRAD_read_var2grid() quadvar has type="<<silodata->datatype; cout <<" but expecting type="<<silo_dtype<<"\n"; cout <<"\t... resetting datatype for this file.\n"; cout <<" DB_INT=16, DB_SHORT=17, DB_LONG=18, DB_FLOAT=19, "; cout <<"DB_DOUBLE=20, DB_CHAR=21, DB_LONG_LONG=22, DB_NOTYPE=25\n\n"; #endif delete_data_arrays(); silo_dtype = silodata->datatype; create_data_arrays(SimPM); } // // Create a pointer to the data in the silo stuct DBquadvar. This // is a void pointer, so I have to reinterpret it to get data that // PION can understand. // void **data = silodata->vals; float **fdata=0; double **ddata=0; if (silo_dtype==DB_FLOAT) { fdata = reinterpret_cast<float **>(data); } else { ddata = reinterpret_cast<double **>(data); } if (variable=="Velocity" || variable=="MagneticField") { int v1,v2,v3; bool B=false; double norm = 1.0/sqrt(4.0*M_PI); if (variable=="Velocity") {v1=VX;v2=VY;v3=VZ;} else {v1=BX;v2=BY;v3=BZ; B=true;} // cout <<"name: "<<silodata->name<<"\tnels="<<silodata->nels<<"\n"; // cout <<"ndims: "<<silodata->ndims<<"\tnvals: "<<silodata->nvals<<"\n"; //cout <<"reading variable "<<variable<<" into element "<<v1<<" of state vec.\n"; cell *c=ggg->FirstPt(); long int ct=0; do { if (SRAD_point_on_my_domain(c, SimPM, filePM)) { // cout <<"ct="<<ct<<"\t and ncell="<<npt<<"\n"; if (silo_dtype==DB_FLOAT) { c->P[v1] = fdata[0][ct]; c->P[v2] = fdata[1][ct]; c->P[v3] = fdata[2][ct]; ct++; } else { c->P[v1] = ddata[0][ct]; c->P[v2] = ddata[1][ct]; c->P[v3] = ddata[2][ct]; ct++; } #ifdef NEW_B_NORM if (B) { // scale values from CGS to code units. c->P[v1] *= norm; c->P[v2] *= norm; c->P[v3] *= norm; } #endif } } while ( (c=ggg->NextPt(c))!=0 ); if (ct != npt) rep.error("wrong number of points read for vector variable",ct-npt); } // vector variable else { int v1=0; bool B=false; if (variable=="Density") v1=RO; else if (variable=="Pressure") v1=PG; else if (variable=="VelocityX") v1=VX; else if (variable=="VelocityY") v1=VY; else if (variable=="VelocityZ") v1=VZ; else if (variable=="MagneticFieldX") {v1=BX; B=true;} else if (variable=="MagneticFieldY") {v1=BY; B=true;} else if (variable=="MagneticFieldZ") {v1=BZ; B=true;} else if (variable=="glmPSI") v1=SI; // // Now loop over up to MAX_NVAR tracers... // else if (variable.substr(0,2)=="Tr") { int itr = atoi(variable.substr(2,3).c_str()); if (!isfinite(itr) || itr<0 || itr>=MAX_NVAR) { rep.error("Bad diffuse Column-density identifier.",variable); } v1 = SimPM.ftr +itr; } else rep.error("what var to read???",variable); //cout <<"reading variable "<<variable<<" into element "<<v1<<" of state vec.\n"; // // First get to start cell in local domain: // enum direction posdir[3] = {XP,YP,ZP}; cell *start=ggg->FirstPt(); long int ct=0; for (int i=0;i<SimPM.ndim;i++) { while (CI.get_dpos(start,i) < filePM->LocalXmin[i]) start = ggg->NextPt(start,posdir[i]); } // // Now use NG for-loops to only go through cells in the local domain. // We assume we go through x-dir column first, then along y, and finally Z // class cell *cx=start, *cy=start, *cz=start; double norm = 1.0/sqrt(4.0*M_PI); if (SimPM.ndim<3) filePM->LocalNG[ZZ]=1; if (SimPM.ndim<2) filePM->LocalNG[YY]=1; for (int k=0; k<filePM->LocalNG[ZZ]; k++) { cy=cz; for (int j=0; j<filePM->LocalNG[YY]; j++) { cx = cy; for (int i=0; i<filePM->LocalNG[XX]; i++) { if (!SRAD_point_on_my_domain(cx, SimPM, filePM)) rep.error("FAST READ IS IN THE WRONG PLACE!!!",cx->pos[XX]); if (silo_dtype==DB_FLOAT) { cx->P[v1] = fdata[0][ct]; } else { cx->P[v1] = ddata[0][ct]; } #ifdef NEW_B_NORM // scale values from CGS to code units. if (B) { //cout <<"SRAD_read_var2grid: scaling B var "<<v1; //cout <<" by "<<norm<<"\n"; cx->P[v1] *= norm; } #endif ct++; cx = ggg->NextPt(cx,posdir[XX]); } if (SimPM.ndim>1) cy = ggg->NextPt(cy,posdir[YY]); } if (SimPM.ndim>2) cz = ggg->NextPt(cz,posdir[ZZ]); } if (ct != npt) { rep.error("wrong number of points read for scalar variable",ct-npt); } } // scalar variable // cout <<"Read variable "<<variable<<"\n"; DBFreeQuadvar(silodata); //silodata=0; fdata=0; ddata=0; return 0; } // ################################################################## // ################################################################## void dataio_silo_utility::set_pllel_filename( std::string &fname, ///< filename const int ifile ///< file number to replace name with. ) { // // If we have a parallel file, Parse filename, and replace file number // with new ifile, store in name 'fname'. // ostringstream temp; temp.fill('0'); string::size_type pos = fname.find("_0000"); if (pos==string::npos) { cout <<"didn't find _0000 in file, but claim we are reading pllel file!\n"; rep.error("not a parallel i/o filename!",fname); } else { temp.str("");temp<<"_";temp.width(4);temp<<ifile; fname.replace(pos,5,temp.str()); //cout <<"\tNew fname: "<<fname<<"\n"; temp.str(""); } return; } // ################################################################## // ################################################################## int dataio_silo_utility::serial_read_any_data( string firstfile, ///< file to read from class SimParams &SimPM, ///< pointer to simulation parameters vector<class GridBaseClass *> &cg ///< address of vector of grid pointers. ) { class GridBaseClass *ggg = cg[0]; if (!ggg) rep.error("null pointer to computational grid!",ggg); // // Read file data onto grid; this may be serial or parallel, so we // need to decide first. // int nproc=0, numfiles=0, groupsize=0; int err = SRAD_get_nproc_numfiles(firstfile, &nproc, &numfiles); // // Set up a MCMDcontrol class for iterating over the quadmeshes // class MCMDcontrol filePM; filePM.set_nproc(nproc); if (err) { // // must be reading serial file, so use serial ReadData() function: // groupsize = 1; err = dataio_silo::ReadData(firstfile,cg, SimPM); rep.errorTest("Failed to read serial data",0,err); } else { // // must be reading parallel file, so want to read in every subdomain onto grid. // Use local functions for this. // // groupsize is decided interestingly by PMPIO (silo): if numfiles divided nproc // evenly then groupsize is nproc/numfiles, but if not then groupsize is // ((int) (nproc/numfiles))+1, I guess so the last files has at least one fewer // domain rather than at least one more domain. // groupsize = nproc/numfiles; if ((nproc%numfiles) !=0) groupsize++; err = serial_read_pllel_silodata(firstfile, ggg, numfiles, groupsize, SimPM, &filePM); rep.errorTest("Failed to read parallel data",0,err); } // cout <<"read data successfully.\n"; return 0; } // ################################################################## // ################################################################## int dataio_silo_utility::serial_read_pllel_silodata( const string firstfile, ///< filename class GridBaseClass *ggg, ///< pointer to data. const int numfiles, ///< number of files const int groupsize, ///< number of groups class SimParams &SimPM, ///< pointer to simulation parameters class MCMDcontrol *filePM ///< number of processes used to write file. ) { int err=0; int level=0; for (int l=0; l<SimPM.grid_nlevels; l++) { if (ggg==SimPM.levels[l].grid) level=l; //cout <<"saving level "<<level<<"\n"; } // // First loop over all files: // for (int ifile=0; ifile<numfiles; ifile++) { string infile = firstfile; // // Replace filename with new file corresponding to current 'ifile' value. // set_pllel_filename(infile,ifile); DBfile *dbfile = DBOpen(infile.c_str(), DB_UNKNOWN, DB_READ); if (!dbfile) rep.error("open first silo file failed.",dbfile); // // loop over domains within this file. The last file may have fewer // domains, so we set ng to be the minimum of groupsize or all // remaining domains. // int ng=min(filePM->get_nproc()-ifile*groupsize, groupsize); for (int igroup=0; igroup<ng; igroup++) { DBSetDir(dbfile,"/"); // // choose myrank, and decompose domain accordingly. // filePM->set_myrank(ifile*groupsize +igroup); filePM->decomposeDomain(SimPM, SimPM.levels[level]); // // set directory in file. // string mydir; set_dir_in_file(mydir, filePM->get_myrank(), igroup, level); DBSetDir(dbfile, mydir.c_str()); // // set variables to read: (from dataio_silo class) // set_readvars(SimPM); // // now read each variable in turn from the mesh // for (std::vector<string>::iterator i=readvars.begin(); i!=readvars.end(); ++i) { err = SRAD_read_var2grid(dbfile, ggg, (*i), filePM->LocalNcell, SimPM,filePM); if (err) rep.error("error reading variable",(*i)); } } // loop over domains within a file. // // Close this file // DBClose(dbfile); dbfile=0; } // loop over files //cout <<"read parallel data successfully.\n"; return 0; } // ################################################################## // ################################################################## int dataio_silo_utility::ReadData( string firstfile, ///< file to read from vector<class GridBaseClass *> &cg, ///< grid pointers. class SimParams &SimPM ///< pointer to simulation parameters ) { cout <<"(pion-ng mpi) Reading data from file: "<<firstfile<<"\n"; silofile=firstfile; int err=0; // Loop over grid levels, and read data for each level. for (int l=0; l<SimPM.grid_nlevels; l++) { cout <<" reading data on level "<<l<<", nlevels="; cout <<SimPM.grid_nlevels<<"\n"; // for now read a different file for each level in the NG grid. // If more than one level of grid, look for level in filename: string::size_type p; if ((p=silofile.find("_level"))==string::npos && SimPM.grid_nlevels>1) { rep.error("dataio_silo_utility::ReadData() level",silofile); } else if (SimPM.grid_nlevels>1) { ostringstream temp; temp.str(""); temp.width(2); temp.fill('0'); temp << l; silofile.replace(p+6,2,temp.str()); #ifdef TEST_SILO_IO cout <<"p="<<p<<" string="<<temp.str()<<", silofile="; cout <<silofile<<"\n"; #endif } if (!cg[l]) rep.error("dataio_silo_utility::ReadData() null grid!",cg[l]); dataio_silo::gp = cg[l]; mpiPM = &(SimPM.levels[l].MCMD); // // set grid properties for quadmesh: each level of the NG // grid has different zone and node coordinates so we need to // call this each time. // //err = setup_grid_properties(gp, SimPM); //rep.errorTest("IO_silo_utility::ReadData() setup_grid_properties" // ,0, err); // now call the code that works for each level: err = ReadLevelData(silofile,gp,SimPM,l); rep.errorTest("IO_silo_utility:: ReadLevelData",0,err); #ifdef TEST_SILO_IO cout <<"Finished reading data on level "<<l<<" of "; cout <<SimPM.grid_nlevels<<"\n"; #endif } return err; } // ################################################################## // ################################################################## int dataio_silo_utility::ReadLevelData( string firstfile, ///< file to read from class GridBaseClass *cg, ///< grid pointer. class SimParams &SimPM, ///< simulation parameters const int l ///< level in grid hierarchy ) { class GridBaseClass *ggg = cg; if (!ggg) rep.error("null pointer to computational grid!",ggg); int err=0; // // The idea behind this is that a program running on N cores can // read data written by M cores, where N and M can be any positive // integers (possibly powers of 2 for the domain decomposition to // work). // // If we are a parallel program, then mpiPM should be already set, // and the domain decomposition into N sub-domains is already done, // and the grid is set up for this sub-domain. // int nproc=0, numfiles=0, groupsize=0; err = SRAD_get_nproc_numfiles(firstfile, &nproc, &numfiles); if (err) { // // must be reading serial file, so we only want part of the domain // read onto the local grid, so we need a new function to read // this. // groupsize = 1; numfiles = 1; err = parallel_read_serial_silodata(firstfile,ggg, SimPM); rep.errorTest("(silocompare) Failed to read data",0,err); } else { // // must be reading parallel file, so want to read in every // subdomain onto grid. Use local functions for this: // // groupsize is decided interestingly by PMPIO (silo): if numfiles divided nproc // evenly then groupsize is nproc/numfiles, but if not then groupsize is // ((int) (nproc/numfiles))+1 for the first NX domains, and // (nproc/numfiles) for the remainder. Here NX=(nproc%numfiles) // #ifdef TEST_SILO_IO cout <<"READING PLLEL DATA for level "<<l<<"\n"; #endif groupsize = nproc/numfiles; if ((nproc%numfiles) !=0) groupsize++; // // We should take it in turns reading data. // Try allowing up to 16 simultaneous reads. // int max_reads=16; int nloops=0; if (mpiPM->get_nproc()<max_reads) nloops = 1; else { nloops = mpiPM->get_nproc()/max_reads; if (mpiPM->get_nproc()%max_reads !=0) { nloops+=1; // this shouldn't happen, but anyway... cout <<"Nproc not a power of 2! This will cause trouble.\n"; rep.error("dataio_silo_utility::ReadLevelData()", mpiPM->get_nproc()); } } clk.start_timer("readdata"); double tsf=0; #ifdef TEST_SILO_IO cout <<"READING PLLEL DATA: "<<mpiPM->get_myrank()<<" "; cout <<mpiPM->get_nproc()<<" "<< numfiles <<" "<< groupsize; cout <<" "<< l <<"\n"; #endif for (int count=0; count<nloops; count++) { if ( (mpiPM->get_myrank()+nloops)%nloops == count) { #ifdef TEST_SILO_IO cout <<"!READING DATA!!... myrank="<<mpiPM->get_myrank()<<" i="<<count; #endif err = parallel_read_parallel_silodata(firstfile, ggg, SimPM, numfiles, groupsize, nproc, l); rep.errorTest("Failed to read parallel data",0,err); } else { #ifdef TEST_SILO_IO cout <<"waiting my turn... myrank="<<mpiPM->get_myrank()<<" i="<<count; #endif } COMM->barrier("pllel_file_read"); tsf=clk.time_so_far("readdata"); #ifdef TEST_SILO_IO cout <<"\t time = "<<tsf<<" secs."<<"\n"; #endif } clk.stop_timer("readdata"); } #ifdef TEST_SILO_IO cout <<"read data successfully.\n"; #endif return 0; } // ################################################################## // ################################################################## int dataio_silo_utility::parallel_read_serial_silodata( string firstfile, ///< file to read from class GridBaseClass *ggg, ///< pointer to data. class SimParams &SimPM ///< pointer to simulation parameters ) { int err=0; // // This is quite simple -- the local domain reads in a subset of the // uniform grid in the file. // DBfile *dbfile = DBOpen(firstfile.c_str(), DB_UNKNOWN, DB_READ); if (!dbfile) rep.error("open first silo file failed.",dbfile); int ftype = DBGetDriverType(dbfile); if (ftype==DB_HDF5) { //cout <<"READING HDF5 FILE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; // // Not sure if we need this for reading, but set it anyway. // int friendly=DBGetFriendlyHDF5Names(); DBSetFriendlyHDF5Names(friendly); } // // Set variables to read based on what equations we are using (this // is read from the header previously) // err = set_readvars(SimPM); if (err) rep.error("failed to set readvars in ReadData",err); string qm_dir("/"); DBSetDir(dbfile, qm_dir.c_str()); string qm_name="UniformGrid"; // // Get max and min quadmesh positions (integers) // int mesh_iXmin[ndim], mesh_iXmax[ndim]; get_quadmesh_integer_extents(dbfile, ggg, SimPM, qm_dir, qm_name, mesh_iXmin, mesh_iXmax); //if (err) rep.error("Failed to get quadmesh extents!",qm_dir); // // now read each variable in turn from the mesh, using the parallel // read function. // for (std::vector<string>::iterator i=readvars.begin(); i!=readvars.end(); ++i) { err = PP_read_var2grid(dbfile, ggg, SimPM, (*i), SimPM.Ncell, mesh_iXmin, mesh_iXmax); if (err) rep.error("dataio_silo::ReadData() error reading variable",(*i)); } DBSetDir(dbfile,"/"); DBClose(dbfile); dbfile=0; return err; } // ################################################################## // ################################################################## int dataio_silo_utility::parallel_read_parallel_silodata( string firstfile, ///< file to read from class GridBaseClass *ggg, ///< pointer to data. class SimParams &SimPM, ///< simulation parameters const int numfiles, ///< number of files const int groupsize, ///< number of groups const int nmesh, ///< number of domains in file. const int l ///< level in grid hierarchy ) { int err=0; // // We need a MCMDcontrol struct to mimic the struct used to write the file. // class MCMDcontrol filePM; filePM.set_nproc(nmesh); // // First loop over all files: // for (int ifile=0; ifile<numfiles; ifile++) { string infile = firstfile; // // Replace filename with new file corresponding to current 'ifile' value. // set_pllel_filename(infile,ifile); DBfile *dbfile = DBOpen(infile.c_str(), DB_UNKNOWN, DB_READ); if (!dbfile) rep.error("open first silo file failed.",dbfile); // // loop over domains within this file. The number of domains per file is // not constant if (R=nproc%numfiles)!=0. One extra domain is added to the // first R files. If R==0, then we can ignore this, since all files have // ng=groupsize domains // int R = nmesh%numfiles; if (R<0) R+= numfiles; int ng=0; if (R!=0) { if (ifile<R) ng=groupsize; else ng=groupsize-1; } else { ng=groupsize; } //int ng=min(nmesh-ifile*groupsize, groupsize); for (int igroup=0; igroup<ng; igroup++) { DBSetDir(dbfile,"/"); // // choose myrank, and decompose domain accordingly. // This is complicated by the first R files having one more file per // group than the rest (but only if R!=0). // if (R!=0) { if (ifile<R) filePM.set_myrank(ifile*groupsize +igroup); else filePM.set_myrank((R*groupsize) +(ifile-R)*(groupsize-1) +igroup); } else { filePM.set_myrank(ifile*groupsize +igroup); } filePM.decomposeDomain(SimPM, SimPM.levels[l]); //mpiPM = &(filePM); //err = setup_grid_properties(gp, SimPM); //rep.errorTest("IO_silo_utility::p_r_pd() setup_grid_properties" // ,0,err); // // set directory in file. // string qm_dir; set_dir_in_file(qm_dir, filePM.get_myrank(), igroup, l); DBSetDir(dbfile, qm_dir.c_str()); // // Set mesh_name from rank. quadmesh is in the current directory // and called "unigridXXXX" where XXXX=filePM.myrank // string qm_name; mesh_name(filePM.get_myrank(),qm_name); #ifdef TEST_SILO_IO cout <<"got mesh name= "<<qm_name<<" in mesh dir= "; cout <<qm_dir<<"\n"; #endif // // Get max and min quadmesh positions (integers) // int mesh_iXmin[ndim], mesh_iXmax[ndim]; get_quadmesh_integer_extents(dbfile, ggg, SimPM, qm_dir, qm_name, mesh_iXmin, mesh_iXmax); if (err) rep.error("Failed to get quadmesh extents!",qm_dir); // // Get max and min grid positions (integers) // int localmin[ndim], localmax[ndim]; for (int v=0;v<ndim;v++) { localmin[v] = ggg->iXmin(static_cast<axes>(v)); localmax[v] = ggg->iXmax(static_cast<axes>(v)); } // // See if quadmesh intersects local domain at all. // bool get_data=true; for (int v=0;v<ndim;v++) { if ( (mesh_iXmax[v]<=localmin[v]) || (mesh_iXmin[v]>=localmax[v]) ) get_data=false; } if (!get_data) { #ifdef TEST_SILO_IO cout <<"*** skipping mesh "<<qm_name<<" because not on local domain.\n"; #endif } else { #ifdef TEST_SILO_IO cout <<"**** reading mesh "<<qm_name<<" because it is on local domain.\n"; rep.printVec("mesh_iXmin",mesh_iXmin,ndim); rep.printVec("mesh_iXmax",mesh_iXmax,ndim); rep.printVec("local iXmin",localmin,ndim); rep.printVec("local iXmax",localmax,ndim); #endif // // set variables to read: (from dataio_silo class) // set_readvars(SimPM); // // now read each variable in turn from the mesh, using the // parallel-parallel read function // for (std::vector<string>::iterator i=readvars.begin(); i!=readvars.end(); ++i) { err = PP_read_var2grid(dbfile, ggg, SimPM, (*i), filePM.LocalNcell, mesh_iXmin, mesh_iXmax); if (err) rep.error("error reading variable",(*i)); } // loop over variables. } } // loop over domains within a file. DBClose(dbfile); dbfile=0; } // loop over files return 0; } // ################################################################## // ################################################################## void dataio_silo_utility::get_quadmesh_extents( DBfile *dbfile, ///< pointer to silo file. const string mesh_dir, ///< directory of mesh const string qm_name, ///< name of mesh double *mesh_xmin, ///< Xmin for mesh (output) double *mesh_xmax, ///< Xmax for mesh (output) class SimParams &SimPM ///< pointer to simulation parameters ) { // // Make sure we're in the right dir // DBSetDir(dbfile, mesh_dir.c_str()); // // Now get the mesh from the file. // DBquadmesh *qm=0; qm = DBGetQuadmesh(dbfile,qm_name.c_str()); if (!qm) rep.error("failed to get quadmesh",qm_name); // // Check that datatype is what we are expecting! If not, then // delete data arrays, reset datatype, and re-create data arrays. // if (qm->datatype != silo_dtype) { #ifdef TEST_SILO_IO cout <<"\n\tget_quadmesh_extents() quadvar has type="<<qm->datatype; cout <<" but expecting type="<<silo_dtype<<"\n"; cout <<"\t... resetting datatype for this file.\n"; cout <<" DB_INT=16, DB_SHORT=17, DB_LONG=18, DB_FLOAT=19, "; cout <<"DB_DOUBLE=20, DB_CHAR=21, DB_LONG_LONG=22, DB_NOTYPE=25\n\n"; #endif delete_data_arrays(); silo_dtype = qm->datatype; create_data_arrays(SimPM); } #ifdef TESTING cout.setf( ios_base::scientific ); cout.precision(15); #endif // TESTING if (silo_dtype==DB_FLOAT) { float *fqmmin = qm->min_extents; float *fqmmax = qm->max_extents; for (int v=0;v<ndim;v++) { mesh_xmin[v] = fqmmin[v]; mesh_xmax[v] = fqmmax[v]; #ifdef TESTING cout <<"dir: "<<v<<"\t min="<<mesh_xmin[v]<<" and max="; cout <<mesh_xmax[v]<<"\n"; #endif // TESTING } } else { double *dqmmin = reinterpret_cast<double *>(qm->min_extents); double *dqmmax = reinterpret_cast<double *>(qm->max_extents); for (int v=0;v<ndim;v++) { mesh_xmin[v] = dqmmin[v]; mesh_xmax[v] = dqmmax[v]; #ifdef TESTING cout <<"dir: "<<v<<"\t min="<<mesh_xmin[v]<<" and max="; cout <<mesh_xmax[v]<<"\n"; #endif // TESTING } } DBFreeQuadmesh(qm); //qm=0; return; } // ################################################################## // ################################################################## void dataio_silo_utility::get_quadmesh_integer_extents( DBfile *dbfile, ///< pointer to silo file. class GridBaseClass *ggg, ///< pointer to data. class SimParams &SimPM, ///< pointer to simulation parameters const string mesh_dir, ///< directory of mesh const string qm_name, ///< name of mesh int *iXmin, ///< integer Xmin for mesh (output) int *iXmax ///< integer Xmax for mesh (output) ) { // // First get the double precision extents // double mesh_xmin[ndim], mesh_xmax[ndim]; get_quadmesh_extents(dbfile, mesh_dir, qm_name, mesh_xmin, mesh_xmax, SimPM); // // Now use the cell interface to get the integer extents (Note that // this will fail and bug out if the global grid class isn't set up, // since that defines the coordinate system). // if (silo_dtype == DB_FLOAT) { // // we need an extra buffer here to put the variable on the +ve // side of the cell border. Have to do it a bit carefully, // because the xmin/xmax values can be > or < 0. // double buffer = 0.0; for (int v=0;v<ndim;v++) { buffer=std::min(1.0e-5,0.1/ggg->SIM_iRange(static_cast<axes>(v))); if (mesh_xmin[v] < 0.0) mesh_xmin[v] *= (1.0-buffer); else mesh_xmin[v] *= (1.0+buffer); if (mesh_xmax[v] < 0.0) mesh_xmax[v] *= (1.0-buffer); else mesh_xmax[v] *= (1.0+buffer); } } CI.get_ipos_vec(mesh_xmin, iXmin); CI.get_ipos_vec(mesh_xmax, iXmax); #ifdef TESTING rep.printVec("get_quadmesh_integer_extents: mesh_Xmin",mesh_xmin,ndim); rep.printVec("get_quadmesh_integer_extents: mesh_Xmax",mesh_xmax,ndim); rep.printVec("get_quadmesh_integer_extents: iXmin",iXmin,ndim); rep.printVec("get_quadmesh_integer_extents: iXmax",iXmax,ndim); #endif // TESTING return; } // ################################################################## // ################################################################## int dataio_silo_utility::PP_read_var2grid( DBfile *dbfile, ///< pointer to silo file. class GridBaseClass *ggg, ///< pointer to data. class SimParams &SimPM, ///< pointer to simulation parameters const string variable, ///< variable name to read. const long int, ///< number of cells expected (defunct!) const int *iXmin, ///< integer Xmin for mesh const int *iXmax ///< integer Xmax for mesh ) { // // The dbfile pointer should already be in the directory containing // the named variable to read, so it's ok to bug out if we don't // find it. // DBquadvar *qv=0; qv = DBGetQuadvar(dbfile,variable.c_str()); if (!qv) rep.error("dataio_silo::read_variable2grid() failed to read variable",variable); // // Check that datatype is what we are expecting! If not, then // delete data arrays, reset datatype, and re-create data arrays. // if (qv->datatype != silo_dtype) { #ifdef TEST_SILO_IO cout <<"\n\tPP_read_var2grid() quadvar has type="<<qv->datatype; cout <<" but expecting type="<<silo_dtype<<"\n"; cout <<"\t... resetting datatype for this file.\n"; cout <<" DB_INT=16, DB_SHORT=17, DB_LONG=18, DB_FLOAT=19, "; cout <<"DB_DOUBLE=20, DB_CHAR=21, DB_LONG_LONG=22, DB_NOTYPE=25\n\n"; #endif delete_data_arrays(); silo_dtype = qv->datatype; create_data_arrays(SimPM); } // // So now part of the quadmesh intersects the local domain, so we // run through the data and pick out the ones we want. Silo stores // the data in a big 1D array with elements stored in the order // D[NY*NY*iz+NX*iy+ix], so we go along x-columns, then y, then z. // // // Set a pointer to the data in the quadmesh // void **data = qv->vals; float **fdata=0; double **ddata=0; if (silo_dtype==DB_FLOAT) { fdata = reinterpret_cast<float **>(data); } else { ddata = reinterpret_cast<double **>(data); } // // Set variables to read, first check for vector and then scalar // data // int v1=-1, v2=-1, v3=-1; bool B=false; if (variable=="Velocity" || variable=="MagneticField") { if (variable=="Velocity") {v1=VX;v2=VY;v3=VZ;} else {v1=BX;v2=BY;v3=BZ; B=true;} } else { if (variable=="Density") v1=RO; else if (variable=="Pressure") v1=PG; else if (variable=="VelocityX") v1=VX; else if (variable=="VelocityY") v1=VY; else if (variable=="VelocityZ") v1=VZ; else if (variable=="MagneticFieldX") {v1=BX; B=true;} else if (variable=="MagneticFieldY") {v1=BY; B=true;} else if (variable=="MagneticFieldZ") {v1=BZ; B=true;} else if (variable=="glmPSI") v1=SI; // // Now loop over up to MAX_NVAR tracers... // else if (variable.substr(0,2)=="Tr") { int itr = atoi(variable.substr(2,3).c_str()); if (!isfinite(itr) || itr<0 || itr>=MAX_NVAR) { rep.error("Bad diffuse Column-density identifier.",variable); } v1 = SimPM.ftr +itr; } else rep.error("what var to read???",variable); } // // Get to first cell in the quadmesh/grid intersection region. // cell *c=ggg->FirstPt(); for (int v=0;v<ndim;v++) { #ifdef TESTING cout <<"c->pos[v]="<<c->pos[v]<<" : iXmin[v]="<<iXmin[v]<<"\n"; #endif enum direction posdir = static_cast<direction>(2*v+1); while (c!=0 && c->pos[v]<iXmin[v]) { c=ggg->NextPt(c,posdir); } if (!c) { rep.error("Went off end of grid looking for starting cell", iXmin[v]-ggg->FirstPt()->pos[v]); } } // // Get the starting indices for the quadmesh -- the starting cell is // at least dx/2 greater than iXmin in every direction, and the // difference is an odd number for cell-size=2, so this integer // division will always get the right answer, since all compilers // round down for integer division of positive numbers. // int dx = ggg->idx(); int qm_start[ndim]; int qm_ix[ndim], qm_NX[ndim]; for (int v=0;v<ndim;v++) { qm_start[v] = (c->pos[v]-iXmin[v])/dx; #ifdef TEST_SILO_IO cout <<"\t\tv="<<v<<" start="<<qm_start[v]<<" pos="; cout <<c->pos[v]<< ", xmin="<<iXmin[v]<<" dims="<<qv->dims[v]; cout <<", var = "<<variable<<"\n"; #endif qm_ix[v] = qm_start[v]; // // Get number of elements in each direction for this subdomain. // Can read it from the quadvar struct or else we could get it // from mpiPM->localNG[] I suppose... N.B. qv->dims is the number // of data entries in each direction (by contrast quadmesh has // qm->dims[] = num.nodes = qv->dims[]+1). // qm_NX[v] = qv->dims[v]; } class cell *cx=c, *cy=c, *cz=c; long int ct=0; long int qv_index=0; double norm = 1.0/sqrt(4.0*M_PI); while (cz!=0) { // // Trace an x-y plane in the current z-plane. // Set index, and reset the y-index counter // qm_ix[YY] = qm_start[YY]; cy = cz; while (cy!=0) { // // Trace an x-column starting at the mesh start point. // cx = cy; // // Get to starting index [NX*NY*iz+NX*iy+ix] // qv_index = 0; if (ndim>2) qv_index += qm_NX[XX]*qm_NX[YY]*qm_ix[ZZ]; if (ndim>1) qv_index += qm_NX[XX]*qm_ix[YY]; qm_ix[XX] = qm_start[XX]; qv_index += qm_ix[XX]; while ((cx!=0) && cx->pos[XX]<iXmax[XX]) { #ifdef TEST_SILO_IO //rep.printVec("cpos",cx->pos,ndim); //rep.printVec("P",cx->P,SimPM.nvar); #endif // // Different pointers if float or double. // if (silo_dtype==DB_FLOAT) { cx->P[v1] = fdata[0][qv_index]; if (v2>0) cx->P[v2] = fdata[1][qv_index]; if (v3>0) cx->P[v3] = fdata[2][qv_index]; } else { cx->P[v1] = ddata[0][qv_index]; if (v2>0) cx->P[v2] = ddata[1][qv_index]; if (v3>0) cx->P[v3] = ddata[2][qv_index]; } #ifdef NEW_B_NORM if (B) { //cout <<"PP_read_var2grid: scaling B var "<<v1; //cout <<" val="<< cx->P[v1]<<" by "<<norm<<"\n"; cx->P[v1] *= norm; if (v2>0) cx->P[v2] *= norm; if (v2>0) cx->P[v3] *= norm; } #endif cx = ggg->NextPt(cx,XP); qv_index++; qm_ix[XX] ++; ct++; } // x-column if (ndim>1) { // // move to next x-column in YP direction, if it exists, and if // it is on the mesh domain. Also increment qm_ix[YY] to // indicate this. // cy = ggg->NextPt(cy,YP); if (cy!=0 && cy->pos[YY]>iXmax[YY]) cy = 0; qm_ix[YY] ++; } else { // // ndim==1, so we want to break out of the y-dir loop // cy = 0; } } // y-loop if (ndim>2) { // // move to next XY-plane in the ZP direction, if it exists and // if it is on the mesh domain. Also increment the qm_ix[ZZ] // counter. // cz = ggg->NextPt(cz,ZP); if (cz!=0 && cz->pos[ZZ]>iXmax[ZZ]) cz = 0; qm_ix[ZZ] ++; } else { // // ndim<=2, so we want to break out of the z-dir loop // cz = 0; } } // z-loop. #ifdef TEST_SILO_IO cout <<"Read variable "<<variable<<", got "<<ct<<" cells\n"; #endif DBFreeQuadvar(qv); //qv=0; data=0; fdata=0; ddata=0; return 0; } // ################################################################## // ################################################################## /********************************************************/ /*************** dataio_silo_utility ********************/ /********************************************************/
30.639075
90
0.560761
jfbucas
34af0db0e62fa70c384f9a59d3d093fc3b0aa016
927
hpp
C++
includeH/setup.hpp
mangoldk/AdvIonChannelMMOptimizer
c86f0564ef3419a46d5ffa0bed89ca4747090fae
[ "BSD-3-Clause" ]
1
2021-08-18T09:29:17.000Z
2021-08-18T09:29:17.000Z
includeH/setup.hpp
silvalab/AdvIonChannelMMOptimizer
c86f0564ef3419a46d5ffa0bed89ca4747090fae
[ "BSD-3-Clause" ]
null
null
null
includeH/setup.hpp
silvalab/AdvIonChannelMMOptimizer
c86f0564ef3419a46d5ffa0bed89ca4747090fae
[ "BSD-3-Clause" ]
null
null
null
#ifndef SETUP_HPP_ #define SETUP_HPP_ #include <iostream> #include "MarkovChannel.hpp" #include <string> #include <sstream> #include "math.hpp" #include "restart.hpp" #include <vector> #include <limits.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> class Setup{ private: int N; int times; int model; std::string version; public: std::vector<ProtocolParameter> protos; std::vector<ProtocolParameter> valids; std::vector<std::vector<int>> edges; std::vector<int> roots; Setup(char*,char*,char*,char*,char*,char*,char*); ~Setup(); void load_protocols(char *protolst, std::vector<ProtocolParameter>& p); void extract_model_params(std::ifstream& model_list); std::string getexepath(); std::string get_model_pwd_and_create_storage_directories(); int get_N() {return N;} int get_times() {return times;} int get_model() {return model;} std::string get_version() {return version;} }; #endif
23.175
72
0.730313
mangoldk
34b4ab14d82536fd27f5dcf8e900c358ea14aadb
3,183
hpp
C++
Source/Jobrocket/Job.hpp
jacobmilligan/JobRocket
8f6a505c6e4e8fe0f13720dd93d8248ca0572b22
[ "MIT" ]
1
2020-09-18T16:51:57.000Z
2020-09-18T16:51:57.000Z
Source/Jobrocket/Job.hpp
jacobmilligan/JobRocket
8f6a505c6e4e8fe0f13720dd93d8248ca0572b22
[ "MIT" ]
null
null
null
Source/Jobrocket/Job.hpp
jacobmilligan/JobRocket
8f6a505c6e4e8fe0f13720dd93d8248ca0572b22
[ "MIT" ]
null
null
null
// // Job.hpp // Jobrocket // // -------------------------------------------------------------- // // Created by // Jacob Milligan on 9/12/2017 // Copyright (c) 2016 Jacob Milligan. All rights reserved. // #pragma once #include "Jobrocket/Detail/Apply.hpp" #include "Jobrocket/Detail/AtomicCounter.hpp" #include <tuple> #include <thread> namespace jobrocket { class JobPool; /// Abstract base class used to call the function regardless of arguments struct JobFunctionBase { virtual void execute() = 0; }; /// Holds a jobs function pointer and argument tuple, applying the /// arguments to the function and calling it when `execute()` is called. template <typename Fn, typename... Args> struct JobFunction : JobFunctionBase { Fn function_ptr; std::tuple<Args...> arg_tuple; explicit JobFunction(Fn function, Args&&... args) : function_ptr(function), arg_tuple(std::tuple<Args...>(args...)) {} constexpr uint32_t size() { return sizeof(JobFunction<Fn, Args...>); } void execute() override { detail::apply(function_ptr, arg_tuple); } }; /// A job is a function pointer and series of arguments to the function as well as providing a link /// back to its thread-local allocating pool and `JobGroup` counter. struct Job { /// Represents the state of a job at any given time enum class State { unknown, ready, running, completed }; /// The source pool from which the job was allocated and should be free'd from JobPool* source_pool; /// The jobs current running state State state; /// Pointer to the counter belonging to a `JobGroup` if the job belongs to one detail::AtomicCounter* group_counter; /// The id of the worker that the job was allocated from uint32_t worker_alloc; /// Size of all members, used to offset the function buffer static constexpr size_t data_size = sizeof(source_pool) + sizeof(state) + sizeof(group_counter) + sizeof(worker_alloc); /// Buffer holding the `JobFunction` and associated arguments uint8_t function[64 - data_size]{}; Job() : state(State::unknown), group_counter(nullptr), worker_alloc(0), source_pool(nullptr) {} Job(const size_t size, void* job_function, const uint32_t allocating_worker) : state(State::unknown), group_counter(nullptr), worker_alloc(allocating_worker), source_pool(nullptr) { memcpy(function, job_function, size); state = State::ready; } /// Runs the jobs function void execute() { state = State::running; reinterpret_cast<JobFunctionBase*>(function)->execute(); state = State::completed; } }; /// Makes a new job on the stack without a `JobPool` template <typename Fn, typename... Args> Job make_unmanaged_job(Fn function, Args&& ... args) { auto data = JobFunction<Fn, Args...>(function, std::forward<Args>(args)...); return Job(data.size(), &data, 0); } inline bool is_ready(Job* job) { return job != nullptr && job->state == jobrocket::Job::State::ready; } }
26.525
99
0.638391
jacobmilligan
34b5920b6f66b364cde26fde95950fd3637fda29
774
cpp
C++
tests/format-io-tests/angular_momentum-tests/angular_momentum-tests.cpp
LoliGothick/mitama-dimensional
46b9ae3764bd472da9ed5372afd82e6b5d542543
[ "MIT" ]
34
2019-01-18T11:51:02.000Z
2021-09-17T02:46:43.000Z
tests/format-io-tests/angular_momentum-tests/angular_momentum-tests.cpp
LoliGothick/mitama-dimensional
46b9ae3764bd472da9ed5372afd82e6b5d542543
[ "MIT" ]
11
2019-02-10T23:12:07.000Z
2019-05-06T21:05:09.000Z
tests/format-io-tests/angular_momentum-tests/angular_momentum-tests.cpp
LoliGothick/mitama-dimensional
46b9ae3764bd472da9ed5372afd82e6b5d542543
[ "MIT" ]
5
2019-02-27T11:53:20.000Z
2021-03-20T21:59:59.000Z
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <mitama/dimensional/systems/si/derived_units/angular_momentum.hpp> #include <mitama/dimensional/systems/si/quantity.hpp> #include "../format_io_common.hpp" TEST_CASE("angular_momentum format test", "[quantity][abbreviation]") { REQUIRE(fmt(1 | systems::si::angular_momentum_t{}) == "1 [N m s]"); } TEST_CASE("angular_momentum quantifier format test", "[quantity][abbreviation]") { REQUIRE(fmt(1 | systems::si::angular_momentum) == "1 [N m s]"); } TEST_CASE("angular_momentum type test", "[quantity][abbreviation]") { REQUIRE(mitama::is_same_dimensional_v<std::decay_t<decltype(1|systems::si::angular_momentum)>, mitama::systems::si::quantity_t<std::decay_t<decltype(meter<2>*kilograms*second<-1>)>>>); }
48.375
186
0.745478
LoliGothick
34b6cb642b80758dae5f969e7f38914459304d51
5,897
cpp
C++
src/Ext/WeaponType/Hooks.Wave.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
4
2021-04-24T04:34:06.000Z
2021-09-19T13:55:33.000Z
src/Ext/WeaponType/Hooks.Wave.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
null
null
null
src/Ext/WeaponType/Hooks.Wave.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
2
2021-08-17T14:44:45.000Z
2021-09-19T11:02:04.000Z
#include "Body.h" #include "../Techno/Body.h" #include <HouseClass.h> #include <WaveClass.h> // custom beam styles // 6FF5F5, 6 DEFINE_HOOK(6FF5F5, TechnoClass_Fire, 6) { GET(TechnoClass* const, pThis, ESI); GET(WeaponTypeClass* const, pSource, EBX); GET(TechnoClass* const, pTarget, EDI); auto const pData = WeaponTypeExt::ExtMap.Find(pSource); if(!pData->IsWave()) { return 0; } GET_BASE(byte, idxWeapon, 0xC); TechnoExt::ExtMap.Find(pThis)->idxSlot_Wave = idxWeapon; if(!pData->Wave_IsLaser && !pData->Wave_IsBigLaser) { return 0; } REF_STACK(CoordStruct const, crdSrc, 0x44); REF_STACK(CoordStruct const, crdTgt, 0x88); auto const type = pData->Wave_IsBigLaser ? WaveType::BigLaser : WaveType::Laser; auto const pWave = GameCreate<WaveClass>( crdSrc, crdTgt, pThis, type, pTarget); WeaponTypeExt::WaveExt[pWave] = pData; pThis->Wave = pWave; return 0x6FF650; } // 75E963, 6 DEFINE_HOOK(75E963, WaveClass_CTOR, 6) { GET(WaveClass *, Wave, ESI); GET(WaveType, Type, ECX); if(Type == WaveType::Laser || Type == WaveType::BigLaser) { return 0; } GET(WeaponTypeClass *, Weapon, EBX); if(Weapon) { WeaponTypeExt::ExtData *pData = WeaponTypeExt::ExtMap.Find(Weapon); WeaponTypeExt::WaveExt[Wave] = pData; } return 0; } /* // 75EB87, 0A // fsdblargh, a single instruction spanning 10 bytes XPORT_FUNC(WaveClass_CTOR2) { GET(WaveClass *, Wave, ESI); RET_UNLESS(CONTAINS(WeaponTypeExt::WaveExt, Wave)); WeaponTypeExt::WeaponTypeClassData *pData = WeaponTypeExt::WaveExt[Wave]; // Wave->set_WaveIntensity(pData->Wave_InitialIntensity); return 0x75EB91; } */ // 763226, 6 DEFINE_HOOK(763226, WaveClass_DTOR, 6) { GET(WaveClass *, Wave, EDI); WeaponTypeExt::WaveExt.erase(Wave); return 0; } // 760F50, 6 // complete replacement for WaveClass::Update DEFINE_HOOK(760F50, WaveClass_Update, 6) { GET(WaveClass *, pThis, ECX); auto pData = WeaponTypeExt::WaveExt.get_or_default(pThis); const WeaponTypeClass *Weap = pData->OwnerObject(); if(!Weap) { return 0; } int Intensity; if(Weap->AmbientDamage) { CoordStruct coords; // Debug::Log("Damaging Cells for weapon %X (Intensity = %d)\n", pData, pThis->WaveIntensity); for(int i = 0; i < pThis->Cells.Count; ++i) { CellClass *Cell = pThis->Cells.GetItem(i); // Debug::Log("\t(%hd,%hd)\n", Cell->MapCoords.X, Cell->MapCoords.Y); pThis->DamageArea(*Cell->Get3DCoords3(&coords)); } // Debug::Log("Done damaging %X\n", pData); } switch(pThis->Type) { case WaveType::Sonic: pThis->Update_Wave(); Intensity = pThis->WaveIntensity; --Intensity; pThis->WaveIntensity = Intensity; if(Intensity < 0) { pThis->UnInit(); } else { SET_REG32(ECX, pThis); CALL(0x5F3E70); // ObjectClass::Update } break; case WaveType::BigLaser: case WaveType::Laser: Intensity = pThis->LaserIntensity; Intensity -= 6; pThis->LaserIntensity = Intensity; if(Intensity < 32) { pThis->UnInit(); } break; case WaveType::Magnetron: pThis->Update_Wave(); Intensity = pThis->WaveIntensity; --Intensity; pThis->WaveIntensity = Intensity; if(Intensity < 0) { pThis->UnInit(); } else { SET_REG32(ECX, pThis); CALL(0x5F3E70); // ObjectClass::Update } break; } return 0x76101A; } /* // 760FFC, 5 // Alt beams update XPORT_FUNC(WaveClass_UpdateLaser) { GET(WaveClass *, Wave, ESI); Wave->Update_Beam(); RET_UNLESS(CONTAINS(WeaponTypeExt::WaveExt, Wave)); WeaponTypeExt::WeaponTypeClassData *pData = WeaponTypeExt::WaveExt[Wave]; int intense = Wave->get_WaveIntensity() + pData->Wave_IntensityStep; Wave->set_WaveIntensity(intense); return intense >= pData->Wave_FinalIntensity ? 0x761016 : 0x76100C; } */ DEFINE_HOOK(760BC2, WaveClass_Draw2, 9) { GET(WaveClass *, Wave, EBX); GET(WORD *, dest, EBP); return (WeaponTypeExt::ModifyWaveColor(*dest, *dest, Wave->LaserIntensity, Wave)) ? 0x760CAFu : 0u ; } // 760DE2, 6 DEFINE_HOOK(760DE2, WaveClass_Draw3, 9) { GET(WaveClass *, Wave, EBX); GET(WORD *, dest, EDI); return (WeaponTypeExt::ModifyWaveColor(*dest, *dest, Wave->LaserIntensity, Wave)) ? 0x760ECBu : 0u ; } // 75EE57, 7 DEFINE_HOOK(75EE57, WaveClass_Draw_Sonic, 7) { GET_STACK(WaveClass *, Wave, 0x4); GET(WORD*, src, EDI); GET(DWORD, offset, ECX); return (WeaponTypeExt::ModifyWaveColor(src[offset], *src, R->ESI(), Wave)) ? 0x75EF1Cu : 0u ; } // 7601FB, 0B DEFINE_HOOK(7601FB, WaveClass_Draw_Magnetron, 0B) { GET_STACK(WaveClass *, Wave, 0x8); GET(WORD*, src, EBX); GET(DWORD, offset, ECX); return (WeaponTypeExt::ModifyWaveColor(src[offset], *src, R->EBP(), Wave)) ? 0x760285u : 0u ; } // 760286, 5 DEFINE_HOOK(760286, WaveClass_Draw_Magnetron2, 5) { return 0x7602D3; } // 762C5C, 6 DEFINE_HOOK(762C5C, WaveClass_Update_Wave, 6) { GET(WaveClass *, Wave, ESI); TechnoClass *Firer = Wave->Owner; TechnoClass *Target = Wave->Target; if(!Target || !Firer) { return 0x762D57; } auto pData = WeaponTypeExt::WaveExt.get_or_default(Wave); if(!pData) { return 0; } int weaponIdx = TechnoExt::ExtMap.Find(Firer)->idxSlot_Wave; CoordStruct xyzSrc = Firer->GetFLH(weaponIdx, CoordStruct::Empty); CoordStruct xyzTgt = Target->GetCoords__(); // not GetCoords() ! bool reversed = pData->IsWaveReversedAgainst(Target); if(Wave->Type == WaveType::Magnetron) { reversed ? Wave->Draw_Magnetic(xyzTgt, xyzSrc) : Wave->Draw_Magnetic(xyzSrc, xyzTgt); } else { reversed ? Wave->Draw_NonMagnetic(xyzTgt, xyzSrc) : Wave->Draw_NonMagnetic(xyzSrc, xyzTgt); } return 0x762D57; } // 75F38F, 6 DEFINE_HOOK(75F38F, WaveClass_DamageCell, 6) { GET(WaveClass *, Wave, EBP); auto pData = WeaponTypeExt::WaveExt.get_or_default(Wave); R->EDI(R->EAX()); R->EBX(pData->OwnerObject()); return 0x75F39D; } DEFINE_HOOK(7601C7, WaveClass_Draw_Purple, 8) { GET(int, Q, EDX); if(Q > 0x15F90) { Q = 0x15F90; } R->EDX(Q); return 0; }
21.840741
95
0.686959
Otamaa
34bcd4184391ad1f18777b945b389f2dc5902a59
121
cpp
C++
sources/source.cpp
Ko71k/lab-05-stack
037400eed089f0aeab059e6fea91526a045b22b9
[ "MIT" ]
null
null
null
sources/source.cpp
Ko71k/lab-05-stack
037400eed089f0aeab059e6fea91526a045b22b9
[ "MIT" ]
null
null
null
sources/source.cpp
Ko71k/lab-05-stack
037400eed089f0aeab059e6fea91526a045b22b9
[ "MIT" ]
null
null
null
//Copyright 2022 Ko71k <rassmagin.rrr@gmail.com> #include <stdexcept> #include <stack.hpp> auto example() -> void { }
13.444444
48
0.694215
Ko71k
34c7c3831acb508e26bf7799b9d2d103ca8ead86
1,091
cc
C++
src/small-int.cc
xdissent/node-linux-cec
7bb8ce1b434397e809e64bc9ab8ddbc70d4e1bfa
[ "MIT" ]
2
2019-05-13T21:34:33.000Z
2022-03-22T17:39:53.000Z
src/small-int.cc
xdissent/node-linux-cec
7bb8ce1b434397e809e64bc9ab8ddbc70d4e1bfa
[ "MIT" ]
4
2018-11-17T20:56:30.000Z
2022-01-22T06:58:52.000Z
src/small-int.cc
xdissent/node-linux-cec
7bb8ce1b434397e809e64bc9ab8ddbc70d4e1bfa
[ "MIT" ]
null
null
null
#include "small-int.h" #include <napi.h> #define UINT8_MASK 0xffffff00 #define UINT16_MASK 0xffff0000 namespace nodelinuxcec { SmallInt SmallInt::New(napi_env env, uint16_t val) { napi_value value; napi_status status = napi_create_uint32(env, val, &value); if (status != napi_ok) throw Napi::Error::New(env); return SmallInt(env, value); } SmallInt::SmallInt() : Napi::Value() {} SmallInt::SmallInt(napi_env env, napi_value value) : Napi::Value(env, value) {} SmallInt::operator uint8_t() const { return Uint8Value(); } SmallInt::operator uint16_t() const { return Uint16Value(); } uint8_t SmallInt::Uint8Value() const { uint32_t value; napi_status status = napi_get_value_uint32(_env, _value, &value); if (status != napi_ok || value & UINT8_MASK) throw Napi::Error::New(_env); return (uint8_t)value; } uint16_t SmallInt::Uint16Value() const { uint32_t value; napi_status status = napi_get_value_uint32(_env, _value, &value); if (status != napi_ok || value & UINT16_MASK) throw Napi::Error::New(_env); return (uint16_t)value; } } // namespace nodelinuxcec
27.974359
79
0.724106
xdissent
34c9f80dc4dc33c2d94533ff92d114cdc8781de8
397
cpp
C++
source/dodbm/operations/helpers/has_column.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
1
2021-02-19T07:22:21.000Z
2021-02-19T07:22:21.000Z
source/dodbm/operations/helpers/has_column.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
null
null
null
source/dodbm/operations/helpers/has_column.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
null
null
null
#include <dodbm/operations/helpers/has_column.hpp> #include <dodbm/exception.hpp> void dodbm::operations::helpers::has_column::set_column(const std::string& name) { if (name.empty()) { throw dodbm::exception("Operation requires a valid column"); } m_column = name; } const std::string& dodbm::operations::helpers::has_column::get_column() const { return m_column; }
22.055556
80
0.695214
WopsS
34ca7c47c1e3086f5e3d18dc8b4ea166f7b20354
8,093
cpp
C++
src/http/status.cpp
anand-gs/cplusplus
97f9115df1920c811531b053fc8b9fc9b1ad2ed2
[ "MIT" ]
null
null
null
src/http/status.cpp
anand-gs/cplusplus
97f9115df1920c811531b053fc8b9fc9b1ad2ed2
[ "MIT" ]
null
null
null
src/http/status.cpp
anand-gs/cplusplus
97f9115df1920c811531b053fc8b9fc9b1ad2ed2
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////// // // status.cpp // ////////////////////////////////////////////////////// /* LICENSE: BEGIN =============================================================================== @author Shan Anand @email anand.gs@gmail.com @source https://github.com/shan-anand @brief HTTP library implementation in C++ =============================================================================== MIT License Copyright (c) 2017 Shanmuga (Anand) Gunasekaran 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. =============================================================================== LICENSE: END */ #include "http/status.hpp" #include <sstream> #include <stdlib.h> #include <common/convert.hpp> using namespace sid; using namespace sid::http; struct MapStatus { status_code code; std::string description; }; static MapStatus gMapStatus[] = { /*100*/ {status_code::Continue, "Continue"}, /*101*/ {status_code::SwitchingProtocols, "Switching Protocols"}, /*102*/ {status_code::Processing, "Processing"}, /*200*/ {status_code::OK, "OK"}, /*201*/ {status_code::Created, "Created"}, /*202*/ {status_code::Accepted, "Accepted"}, /*203*/ {status_code::NonAuthoritativeInformation, "Non-Authoritative Information"}, /*204*/ {status_code::NoContent, "No Content"}, /*205*/ {status_code::ResetContent, "Reset Content"}, /*206*/ {status_code::PartialContent, "Partial Content"}, /*207*/ {status_code::MultiStatus, "Multi-Status"}, /*208*/ {status_code::AlreadyReported, "AlreadyReported"}, /*226*/ {status_code::IMUsed, "IM Used"}, /*300*/ {status_code::MultipleChoices, "Multiple Choices"}, /*301*/ {status_code::MovedPermanently, "Moved Permanently"}, /*302*/ {status_code::Found, "Found"}, /*303*/ {status_code::SeeOther, "See Other"}, /*304*/ {status_code::NotModified, "Not Modified"}, /*305*/ {status_code::UseProxy, "Use Proxy"}, /*306*/ {status_code::Unused306, "(Unused)"}, /*307*/ {status_code::TemporaryRedirect, "Temporary Redirect"}, /*308*/ {status_code::PermanentRedirect, "Permanent Redirect"}, /*400*/ {status_code::BadRequest, "Bad Request"}, /*401*/ {status_code::Unauthorized, "Unauthorized"}, /*402*/ {status_code::PaymentRequired, "Payment Required"}, /*403*/ {status_code::Forbidden, "Forbidden"}, /*404*/ {status_code::NotFound, "Not Found"}, /*405*/ {status_code::MethodNotAllowed, "Method Not Allowed"}, /*406*/ {status_code::NotAcceptable, "Not Acceptable"}, /*407*/ {status_code::ProxyAuthenticationRequired, "Proxy Authentication Required"}, /*408*/ {status_code::RequestTimeout, "Request Timeout"}, /*409*/ {status_code::Conflict, "Conflict"}, /*410*/ {status_code::Gone, "Gone"}, /*411*/ {status_code::LengthRequired, "Length Required"}, /*412*/ {status_code::PreconditionFailed, "Precondition Failed"}, /*413*/ {status_code::RequestEntityTooLarge, "Request Entity Too Large"}, /*414*/ {status_code::RequestURITooLong, "Request-URI Too Long"}, /*415*/ {status_code::UnsupportedMediaType, "Unsupported Media Type"}, /*416*/ {status_code::RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"}, /*417*/ {status_code::ExpectationFailed, "Expectation Failed"}, /*418*/ {status_code::ImATeaPot, "I'm a Tea Pot"}, /*421*/ {status_code::MisdirectedRequest, "Misdirected Request"}, /*422*/ {status_code::UnprocessableEntity, "Unprocessable Entity"}, /*423*/ {status_code::Locked, "Locked"}, /*424*/ {status_code::FailedDependency, "Failed Dependency"}, /*426*/ {status_code::UpgradeRequired, "Upgrade Required"}, /*428*/ {status_code::PreconditionRequired, "Precondition Required"}, /*429*/ {status_code::TooManyRequests, "Too Many Requests"}, /*431*/ {status_code::RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"}, /*451*/ {status_code::UnavailableForLegalReasons, "Unavailable For Legal Reasons"}, /*500*/ {status_code::InternalServerError, "Internal Server Error"}, /*501*/ {status_code::NotImplemented, "Not Implemented"}, /*502*/ {status_code::BadGateway, "Bad Gateway"}, /*503*/ {status_code::ServiceUnavailable, "Service Unavailable"}, /*504*/ {status_code::GatewayTimeout, "Gateway Timeout"}, /*505*/ {status_code::HTTPVersionNotSupported, "HTTP Version Not Supported"}, /*506*/ {status_code::VariantAlsoNegotiates, "Variant Also Negotiates"}, /*507*/ {status_code::InsufficientStorage, "Insufficient Storage"}, /*508*/ {status_code::LoopDetected, "Loop Detected"}, /*510*/ {status_code::NotExtended, "Not Extended"}, /*511*/ {status_code::NetworkAuthenticationRequired, "Network Authentication Required"} }; status::status() { clear(); } status::status(const status_code& _code) { *this = _code; } //! Clear the object so that it can be reused again void status::clear() { m_code = status_code::OK; // Default the status code to OK } http::status& status::operator=(const status_code& _code) { m_code = _code; return *this; } const std::string& status::message() const { size_t cnt = sizeof(gMapStatus)/sizeof(gMapStatus[0]); for ( size_t i = 0; i < cnt; i++ ) if ( m_code == gMapStatus[i].code ) return gMapStatus[i].description; throw sid::exception("Invalid Status code"); } //! Check whether the current status is a redirect request bool status::is_redirect(redirect_info* predirectInfo) const { bool status = false; redirect_info redirectInfo; switch ( m_code ) { case status_code::MovedPermanently: /*301*/ status = redirectInfo.set(true /*permanent*/, false /*cannot change method*/); break; case status_code::PermanentRedirect: /*308*/ // HTTP method should not change status = redirectInfo.set(true /*permanent*/, true /*can change method*/); break; case status_code::Found: /*302*/ status = redirectInfo.set(false /*temporary*/, false /*cannot change method*/); break; case status_code::TemporaryRedirect: /*307*/ // HTTP method should not change status = redirectInfo.set(false /*temporary*/, true /*can change method*/); break; default: break; } if ( predirectInfo ) *predirectInfo = redirectInfo; return status; } std::string status::to_str() const { std::ostringstream out; out << static_cast<int>(m_code) << " " << this->message(); return out.str(); } /*static*/ http::status status::get(const std::string& _input) { http::status status; size_t pos = _input.find(' '); if ( pos == std::string::npos ) throw sid::exception("Invalid status format"); std::string codeStr = _input.substr(0, pos); int code = sid::to_num<int>(codeStr); if ( code == 0 ) throw sid::exception("Invalid HTTP status code"); status = (status_code) code; bool isFound = false; size_t cnt = sizeof(gMapStatus)/sizeof(gMapStatus[0]); for ( size_t i = 0; i < cnt; i++ ) if ( status.code() == gMapStatus[i].code ) { isFound = true; break; } if ( !isFound ) throw sid::exception(code, std::string("Invalid HTTP status code: ") + codeStr); return status; }
39.671569
98
0.664896
anand-gs
34ccae50fa65539137369018410c7071092dbcfc
1,262
cpp
C++
Deitel/Chapter03/examples/3.17/GradeBook.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter03/examples/3.17/GradeBook.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter03/examples/3.17/GradeBook.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include "GradeBook.hpp" #include <iostream> #include <string> GradeBook::GradeBook(const std::string &name) { setCourseName(name); } // SETTERS // ensure coursename does not exceed 25 chars void GradeBook::setCourseName(const std::string &name) { if (name.length() <= 25) { courseName = name; } if (name.length() > 25) { courseName = name.substr(0, 25); std::cout << "Name \"" << name << "\" exceeds maximum length (25).\n"; std::cout << "Limiting courseName to first 25 characters.\n" << std::endl; } } // GETTERS std::string GradeBook::getCourseName() { return courseName; } // display a welcome message to the GradeBook user void GradeBook::displayMessage() { std::cout << "Welcome to the grade book for\n" << getCourseName() << "!" << std::endl; }
28.681818
88
0.50317
SebastianTirado
34cffd29d194e5ea47d3e19ed1e2001594c51e6d
362
cpp
C++
242_isAnagram.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
242_isAnagram.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
242_isAnagram.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; int S[26] = {0}, T[26] = {0}; for (char c : s) { ++S[c - 'a']; } for (char c : t) { ++T[c - 'a']; } for (int i = 0; i < 25; ++i) { if (S[i] != T[i]) return false; } return true; } };
14.48
38
0.395028
imxiaobo
34d2dcf08894e40d3b26eeea1569447ccd307307
1,675
cpp
C++
reve/dynamic/llreve-dynamic/lib/llreve/dynamic/SerializeTraces.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
20
2016-08-11T19:51:13.000Z
2021-09-02T13:10:58.000Z
reve/dynamic/llreve-dynamic/lib/llreve/dynamic/SerializeTraces.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
9
2016-08-11T11:59:24.000Z
2021-07-16T09:44:28.000Z
reve/dynamic/llreve-dynamic/lib/llreve/dynamic/SerializeTraces.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
7
2017-08-19T14:42:27.000Z
2020-05-20T16:14:13.000Z
/* * This file is part of * llreve - Automatic regression verification for LLVM programs * * Copyright (C) 2016 Karlsruhe Institute of Technology * * The system is published under a BSD license. * See LICENSE (distributed with this file) for details. */ #include "llreve/dynamic/SerializeTraces.h" #include "llreve/dynamic/Interpreter.h" #include "llreve/dynamic/ThreadSafeQueue.h" #include <fstream> #include <iostream> #include <thread> using std::vector; using std::string; using std::make_shared; using std::map; using llvm::Function; Range::RangeIterator Range::begin() { vector<mpz_class> vals(n); if (n == 0) { return RangeIterator(lowerBound, upperBound, vals); } if (lowerBound > upperBound) { return end(); } for (size_t i = 0; i < vals.size(); ++i) { vals[i] = lowerBound; } return RangeIterator(lowerBound, upperBound, vals); } Range::RangeIterator Range::end() { vector<mpz_class> vals(n); if (n == 0) { return RangeIterator(lowerBound, upperBound, vals); } vals[0] = upperBound + 1; for (size_t i = 1; i < vals.size(); ++i) { vals[i] = lowerBound; } return RangeIterator(lowerBound, upperBound, vals); } Range::RangeIterator &Range::RangeIterator::operator++() { mpz_class carry = 1; size_t index = 0; while (carry == 1 && index < vals.size()) { vals[index]++; if (vals[index] == upperBound + 1) { carry = 1; vals[index] = lowerBound; } else { carry = 0; } ++index; } if (carry == 1) { vals[0] = upperBound + 1; } return *this; }
23.591549
66
0.6
mattulbrich
34d6f3ce91882f05394f4de5d917d295fadb5d79
1,439
hpp
C++
src/rdf4cpp/rdf/datatypes/xsd/Integer.hpp
kaimal11/rdf4cpp
c6c38937dc004ecd459ef881dc2cf6217d1cfeae
[ "MIT" ]
null
null
null
src/rdf4cpp/rdf/datatypes/xsd/Integer.hpp
kaimal11/rdf4cpp
c6c38937dc004ecd459ef881dc2cf6217d1cfeae
[ "MIT" ]
null
null
null
src/rdf4cpp/rdf/datatypes/xsd/Integer.hpp
kaimal11/rdf4cpp
c6c38937dc004ecd459ef881dc2cf6217d1cfeae
[ "MIT" ]
null
null
null
/** * @file Registers xsd:integer with DatatypeRegistry */ #ifndef RDF4CPP_XSD_INTEGER_HPP #define RDF4CPP_XSD_INTEGER_HPP #include <rdf4cpp/rdf/datatypes/registry/DatatypeMapping.hpp> #include <rdf4cpp/rdf/datatypes/registry/LiteralDatatypeImpl.hpp> #include <cstdint> #include <ostream> #include <regex> namespace rdf4cpp::rdf::datatypes::registry { /* * Name of the datatype. This is kept so that we won't need to type it over and over again. */ constexpr static registry::ConstexprString xsd_integer{"http://www.w3.org/2001/XMLSchema#integer"}; /** * Defines the mapping between the LiteralDatatype IRI and the C++ datatype. */ template<> struct DatatypeMapping<xsd_integer> { using cpp_datatype = int64_t; }; /** * Specialisation of from_string template function. */ template<> inline LiteralDatatypeImpl<xsd_integer>::cpp_type LiteralDatatypeImpl<xsd_integer>::from_string(std::string_view s) { const std::regex integer_regex("[\\-+]?[0-9]+"); if (std::regex_match(s.data(), integer_regex)) { return std::strtol(s.data(), nullptr, 10); } else { throw std::runtime_error("XSD Parsing Error"); } } } // namespace rdf4cpp::rdf::datatypes::registry namespace rdf4cpp::rdf::datatypes::xsd { /** * Implementation of xsd::integer */ using Integer = registry::LiteralDatatypeImpl<registry::xsd_integer>; } // namespace rdf4cpp::rdf::datatypes::xsd #endif //RDF4CPP_XSD_INTEGER_HPP
26.648148
117
0.728978
kaimal11
34d6f58341493524d49d4648861ea0aa01f9acf6
6,298
cpp
C++
DESIRE-Modules/Physics-PhysX/src/PhysXPhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Modules/Physics-PhysX/src/PhysXPhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Modules/Physics-PhysX/src/PhysXPhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "stdafx_PhysX.h" #include "PhysXPhysicsComponent.h" #include "PhysXPhysics.h" #include "PxMathExt.h" #include "Engine/Core/GameObject.h" #include "Engine/Core/Math/Transform.h" PhysXPhysicsComponent::PhysXPhysicsComponent(GameObject& object) : PhysicsComponent(object) { } PhysXPhysicsComponent::~PhysXPhysicsComponent() { } void PhysXPhysicsComponent::SetEnabled(bool value) { if(IsEnabled() == value) { return; } PhysicsComponent::SetEnabled(value); m_pBody->setActorFlag(physx::PxActorFlag::eDISABLE_SIMULATION, value); } void PhysXPhysicsComponent::SetCollisionLayer(EPhysicsCollisionLayer collisionLayer) { m_collisionLayer = collisionLayer; physx::PxFilterData filterData; filterData.word0 = 1 << static_cast<int32_t>(collisionLayer); filterData.word1 = Modules::Physics->GetMaskForCollisionLayer(collisionLayer); } void PhysXPhysicsComponent::SetCollisionDetectionMode(ECollisionDetectionMode mode) { m_pBody->setRigidBodyFlag(physx::PxRigidBodyFlag::eENABLE_CCD, (mode == ECollisionDetectionMode::Continuous)); } PhysicsComponent::ECollisionDetectionMode PhysXPhysicsComponent::GetCollisionDetectionMode() const { return (m_pBody->getRigidBodyFlags() & physx::PxRigidBodyFlag::eENABLE_CCD) ? ECollisionDetectionMode::Continuous : ECollisionDetectionMode::Discrete; } Array<PhysicsComponent*> PhysXPhysicsComponent::GetActiveCollidingComponents() const { Array<PhysicsComponent*> collisions; ASSERT(false && "TODO"); return collisions; } void PhysXPhysicsComponent::SetBodyType(EBodyType m_pBodyType) { switch(m_pBodyType) { case EBodyType::Static: ASSERT(false && "TODO"); break; case EBodyType::Dynamic: m_pBody->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, false); break; case EBodyType::Kinematic: m_pBody->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, true); break; } } PhysicsComponent::EBodyType PhysXPhysicsComponent::GetBodyType() const { const physx::PxRigidBodyFlags flags = m_pBody->getRigidBodyFlags(); if(flags.isSet(physx::PxRigidBodyFlag::eKINEMATIC)) { return PhysicsComponent::EBodyType::Kinematic; } if(m_pDynamicBody) { PhysicsComponent::EBodyType::Dynamic; } return PhysicsComponent::EBodyType::Static; } void PhysXPhysicsComponent::SetTrigger(bool value) { ASSERT(false && "TODO"); } bool PhysXPhysicsComponent::IsTrigger() const { ASSERT(false && "TODO"); return false; } void PhysXPhysicsComponent::SetMass(float mass) { return m_pBody->setMass(mass); } float PhysXPhysicsComponent::GetMass() const { return m_pBody->getMass(); } Vector3 PhysXPhysicsComponent::GetCenterOfMass() const { m_pBody->getCMassLocalPose(); ASSERT(false && "TODO"); return Vector3::Zero(); } void PhysXPhysicsComponent::SetLinearDamping(float value) { if(m_pDynamicBody) { m_pDynamicBody->setLinearDamping(value); } } float PhysXPhysicsComponent::GetLinearDamping() const { return m_pDynamicBody ? m_pDynamicBody->getLinearDamping() : 0.0f; } void PhysXPhysicsComponent::SetAngularDamping(float value) { if(m_pDynamicBody) { m_pDynamicBody->setAngularDamping(value); } } float PhysXPhysicsComponent::GetAngularDamping() const { return m_pDynamicBody ? m_pDynamicBody->getAngularDamping() : 0.0f; } void PhysXPhysicsComponent::SetLinearVelocity(const Vector3& linearVelocity) { m_pBody->setLinearVelocity(GetPxVec3(linearVelocity)); } Vector3 PhysXPhysicsComponent::GetLinearVelocity() const { return GetVector3(m_pBody->getLinearVelocity()); } void PhysXPhysicsComponent::SetAngularVelocity(const Vector3& angularVelocity) { m_pBody->setAngularVelocity(GetPxVec3(angularVelocity)); } Vector3 PhysXPhysicsComponent::GetAngularVelocity() const { return GetVector3(m_pBody->getAngularVelocity()); } void PhysXPhysicsComponent::AddForce(const Vector3& force, EForceMode mode) { switch(mode) { case EForceMode::Force: m_pBody->addForce(GetPxVec3(force), physx::PxForceMode::eFORCE); break; case EForceMode::Impulse: m_pBody->addForce(GetPxVec3(force), physx::PxForceMode::eIMPULSE); break; } } void PhysXPhysicsComponent::AddForceAtPosition(const Vector3& force, const Vector3& position, EForceMode mode) { switch(mode) { case EForceMode::Force: physx::PxRigidBodyExt::addForceAtPos(*m_pBody, GetPxVec3(force), GetPxVec3(position), physx::PxForceMode::eFORCE); break; case EForceMode::Impulse: physx::PxRigidBodyExt::addForceAtPos(*m_pBody, GetPxVec3(force), GetPxVec3(position), physx::PxForceMode::eIMPULSE); break; } } void PhysXPhysicsComponent::AddTorque(const Vector3& torque, EForceMode mode) { switch(mode) { case EForceMode::Force: m_pBody->addTorque(GetPxVec3(torque), physx::PxForceMode::eFORCE); break; case EForceMode::Impulse: m_pBody->addTorque(GetPxVec3(torque), physx::PxForceMode::eIMPULSE); break; } } void PhysXPhysicsComponent::SetLinearMotionLock(bool axisX, bool axisY, bool axisZ) { if(m_pDynamicBody) { m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_X, axisX); m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Y, axisY); m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_LINEAR_Z, axisZ); } } void PhysXPhysicsComponent::SetAngularMotionLock(bool axisX, bool axisY, bool axisZ) { if(m_pDynamicBody) { m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_X, axisX); m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y, axisY); m_pDynamicBody->setRigidDynamicLockFlag(physx::PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, axisZ); } } bool PhysXPhysicsComponent::IsSleeping() const { return m_pDynamicBody ? m_pDynamicBody->isSleeping() : true; } void PhysXPhysicsComponent::UpdateGameObjectTransform() const { Transform& transform = m_object.GetTransform(); const physx::PxTransform pxTransform = m_pBody->getGlobalPose(); transform.SetPosition(GetVector3(pxTransform.p)); transform.SetRotation(GetQuat(pxTransform.q)); } void PhysXPhysicsComponent::SetTransformFromGameObject() { const Transform& transform = m_object.GetTransform(); physx::PxTransform pxTransform = m_pBody->getGlobalPose(); pxTransform.p = GetPxVec3(transform.GetPosition()); pxTransform.q = GetPxQuat(transform.GetRotation()); m_pBody->setGlobalPose(pxTransform); }
28.116071
151
0.790251
nyaki-HUN
34dbbe56d316b2d1e37540223181a4a889183cae
720
cpp
C++
src/gotobed/Misc.cpp
andrelo1/gotobed-le
68c6e9e222610dd8154b17ca7fe3afb1ac726703
[ "MIT" ]
null
null
null
src/gotobed/Misc.cpp
andrelo1/gotobed-le
68c6e9e222610dd8154b17ca7fe3afb1ac726703
[ "MIT" ]
null
null
null
src/gotobed/Misc.cpp
andrelo1/gotobed-le
68c6e9e222610dd8154b17ca7fe3afb1ac726703
[ "MIT" ]
null
null
null
#include "Misc.h" #include "Offsets.h" namespace Gotobed::Misc { void Init() { // don't show sleep menu SafeWrite16(Offsets::TESFurniture::Activate + 0x0131, 0x14EB); // don't show "serve time" message SafeWrite8(Offsets::TESFurniture::Activate + 0x00E4, 0xEB); // get up using movement keys SafeWrite8(Offsets::PlayerCharacter::Update + 0x01D9, 0x02); // don't allow sleeping in reserved bed SafeWrite8(Offsets::PlayerCharacter::CanSleepWaitHere + 0x018F, 0x00); // don't stop animations when sleeping SafeWrite8(Offsets::AIProcess::SitSleepStateUpdate + 0x01AB, 0xEB); SafeWrite8(Offsets::AIProcess::sub_702120 + 0x00D1, 0xEB); SafeWrite8(Offsets::Actor::FinishLoadGame + 0x017B, 0xEB); } }
34.285714
72
0.733333
andrelo1
34e2e52621ed60b83c268854b0565d99eed0fd01
1,912
cpp
C++
PC_Aula_25/2_Watering Grass/2_Watering_Grass.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
PC_Aula_25/2_Watering Grass/2_Watering_Grass.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
PC_Aula_25/2_Watering Grass/2_Watering_Grass.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <cstdio> #include <iostream> #include <cmath> using namespace std; struct interval{ double a; double b; int index; bool operator < (interval x) const { return a < x.a; } }; double A,B,maxx; int n, it, best; vector<int> cover; bool possible; int main(){ int n,l; double r,w,x; while (cin >> n >> l >> w){ interval intervals[n]; for (int i=0;i<n;i++){ cin >> x >> r; if (r >= w/2){ double p = sqrt(r*r -w*w/4); intervals[i].a = x - p; intervals[i].b = x + p; intervals[i].index = i; } else { intervals[i].a = -1; intervals[i].b = -1; intervals[i].index = i; } } A = 0; B = l; sort(intervals,intervals+n); it = 0; cover.clear(); possible = true; while (intervals[it].b < A){ it++; if (it == n){ possible = false; break; } } if (A == B && possible){ if (intervals[it].a <= A && intervals[it].b >= A) cover.push_back(intervals[it].index); else possible = false;} while (A < B && possible){ if (it == n){ possible = false; break; } maxx = -1; best = -1; while (intervals[it].a <= A){ if (intervals[it].b - A > maxx){ maxx = intervals[it].b - A; best = it; } it++; if (it == n) break; } if (best == -1){ possible = false; break; } cover.push_back(intervals[best].index); A = intervals[best].b; } if (!possible) printf("-1\n"); else{ printf("%lu\n",cover.size()); } } return 0; }
22.494118
61
0.417887
ElizabethYasmin
34e32f4cbc16e9737b6e461b370ca6bd4ff61743
5,052
cpp
C++
src/gui/abstract_gobj.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/gui/abstract_gobj.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/gui/abstract_gobj.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <mathieu.magnaudet@enac.fr> * */ #include "abstract_gobj.h" namespace djnn { bool gui_initialized = false; UpdateDrawing *UpdateDrawing::_instance; std::once_flag UpdateDrawing::onceFlag; UpdateDrawing::UpdateDrawing () { _auto_refresh = new BoolProperty (this, "auto_refresh", true); _draw_sync = new Spike (this, "draw_sync"); _damaged = new UndelayedSpike (this, "damaged"); _redraw_action = new RedrawAction (this, "redraw_action"); _update_auto_refresh_action = new AutoRefreshAction (this, "auto_refresh_action"); Graph::instance ().add_output_node (_redraw_action); _redraw_when_damaged = new Coupling (_damaged, ACTIVATION, _draw_sync, ACTIVATION); Graph::instance ().add_edge (_damaged, _draw_sync); _redraw_when_draw_sync = new Coupling (_draw_sync, ACTIVATION, _redraw_action, ACTIVATION); _c_update_auto_refresh = new Coupling (_auto_refresh, ACTIVATION, _update_auto_refresh_action, ACTIVATION); Graph::instance ().add_edge (_auto_refresh, _update_auto_refresh_action); _activation_state = activated; } UpdateDrawing::~UpdateDrawing () { Graph::instance ().remove_edge (_damaged, _draw_sync); Graph::instance ().remove_edge (_auto_refresh, _update_auto_refresh_action); Graph::instance ().remove_output_node (_redraw_action); if (_redraw_when_draw_sync) { delete _redraw_when_draw_sync; _redraw_when_draw_sync = nullptr; } if (_redraw_when_damaged) { delete _redraw_when_damaged; _redraw_when_damaged = nullptr; } if (_redraw_action) { delete _redraw_action; _redraw_action = nullptr; } if (_c_update_auto_refresh) { delete _c_update_auto_refresh; _c_update_auto_refresh = nullptr; } if (_damaged) { delete _damaged; _damaged = nullptr; } if (_draw_sync) { delete _draw_sync; _draw_sync = nullptr; } if (_auto_refresh) { delete _auto_refresh; _auto_refresh = nullptr; } if (_update_auto_refresh_action) { delete _update_auto_refresh_action; _update_auto_refresh_action = nullptr; } } UpdateDrawing* UpdateDrawing::instance () { std::call_once (UpdateDrawing::onceFlag, [] () { _instance = new UpdateDrawing (); }); return _instance; } void UpdateDrawing::activate () { if (_auto_refresh->get_value ()) _redraw_when_damaged->enable (); else _redraw_when_damaged->disable (); } void UpdateDrawing::coupling_activation_hook () { Window *frame = dynamic_cast<Window*> (get_data ()); if (frame == nullptr) return; if (!frame->refresh ()) { _win_list.push_back (frame); frame->set_refresh (true); } } void UpdateDrawing::init () { //Graph::instance ().add_output_node (instance ()); gui_initialized = true; } void UpdateDrawing::clear () { if (gui_initialized) { _instance->set_data (nullptr); _instance->_win_list.clear (); gui_initialized = false; } } void AbstractGObj::activate () { if (_frame == nullptr || _frame->get_state () <= activated) { /* this algorithm is a little bit tricky. We want to find the closest running frame * on the left side of the current object (cur_child). For this, we take its parent (cur_parent) and go through its * children in order to find a frame. If no frame is found when the list iteration process arrived to (cur_child), * then we set (cur_child) to its parent (cur_parent), and (cur_parent) is set to (cur_parent->parent). * May be there is a place for simplification */ bool found = false; Process *cur_parent = _parent; Process *cur_child = this; while (!found && cur_parent != nullptr) { if (cur_parent->get_cpnt_type () == COMPONENT) { Container *cont = dynamic_cast<Container*> (cur_parent); for (auto c : cont->children ()) { if (c == cur_child) break; else if (c->get_cpnt_type () == WINDOW && c->get_state () <= activated) { _frame = dynamic_cast<Window*> (c); found = true; } } } do { cur_child = cur_parent; cur_parent = cur_parent->get_parent (); } while (cur_parent != nullptr && cur_parent->get_cpnt_type () != COMPONENT); } if (!found) { std::cout << "Warning no running frame found\n"; return; } } UpdateDrawing::instance ()->add_window_for_refresh (_frame); UpdateDrawing::instance ()->get_damaged ()->notify_activation (); } void AbstractGObj::deactivate () { if (_frame != nullptr) { UpdateDrawing::instance ()->add_window_for_refresh (_frame); UpdateDrawing::instance ()->get_damaged ()->notify_activation (); } } }
33.236842
122
0.660728
alicemona
34e3e88bc4fd4812c9eaff990cfd749b0ba62cd4
78,861
cpp
C++
src/8086tiny_new.cpp
francescosacco/tinyXT
d0beb4d5d3c8ad37bc0de0d89cbe522a4deb0aa5
[ "MIT" ]
6
2018-01-12T05:55:15.000Z
2022-03-26T14:31:02.000Z
src/8086tiny_new.cpp
francescosacco/tinyXT
d0beb4d5d3c8ad37bc0de0d89cbe522a4deb0aa5
[ "MIT" ]
1
2019-10-08T07:48:01.000Z
2019-12-20T14:53:21.000Z
src/8086tiny_new.cpp
francescosacco/tinyXT
d0beb4d5d3c8ad37bc0de0d89cbe522a4deb0aa5
[ "MIT" ]
2
2021-01-02T16:06:06.000Z
2021-11-04T13:52:40.000Z
// ============================================================================= // File: 8086tiny_new.cpp // // Description: // 8086tiny plus Revision 1.34 // // Modified from 8086tiny to separate hardware emulation into an interface // class and support more 80186/NEC V20 instructions. // Copyright 2014 Julian Olds // // Based on: // 8086tiny: a tiny, highly functional, highly portable PC emulator/VM // Copyright 2013-14, Adrian Cable (adrian.cable@gmail.com) - http://www.megalith.co.uk/8086tiny // // This work is licensed under the MIT License. See included LICENSE.TXT. // #include <time.h> #include <memory.h> #include <stdio.h> #include <windows.h> #include <sys/timeb.h> #include <fcntl.h> #include <conio.h> #include <unistd.h> #ifdef _MSC_VER #include <io.h> #endif #include "8086tiny_interface.h" #include "emulator/XTmemory.h" T8086TinyInterface_t Interface ; #define XFALSE ( ( uint8_t ) 0x00 ) #define XTRUE ( ( uint8_t ) 0x01 ) // Emulator system constants #define REGS_BASE 0xF0000 // 16-bit register decodes #define REG_AX 0 #define REG_CX 1 #define REG_DX 2 #define REG_BX 3 #define REG_SP 4 #define REG_BP 5 #define REG_SI 6 #define REG_DI 7 #define REG_ES 8 #define REG_CS 9 #define REG_SS 10 #define REG_DS 11 #define REG_ZERO 12 #define REG_SCRATCH 13 #define REG_IP 14 #define REG_TMP 15 // 8-bit register decodes #define REG_AL 0 #define REG_AH 1 #define REG_CL 2 #define REG_CH 3 #define REG_DL 4 #define REG_DH 5 #define REG_BL 6 #define REG_BH 7 // FLAGS register decodes #define FLAG_CF 40 #define FLAG_PF 41 #define FLAG_AF 42 #define FLAG_ZF 43 #define FLAG_SF 44 #define FLAG_TF 45 #define FLAG_IF 46 #define FLAG_DF 47 #define FLAG_OF 48 // Lookup tables in the BIOS binary #define TABLE_XLAT_OPCODE 8 #define TABLE_XLAT_SUBFUNCTION 9 #define TABLE_STD_FLAGS 10 #define TABLE_PARITY_FLAG 11 #define TABLE_BASE_INST_SIZE 12 #define TABLE_I_W_SIZE 13 #define TABLE_I_MOD_SIZE 14 #define TABLE_COND_JUMP_DECODE_A 15 #define TABLE_COND_JUMP_DECODE_B 16 #define TABLE_COND_JUMP_DECODE_C 17 #define TABLE_COND_JUMP_DECODE_D 18 #define TABLE_FLAGS_BITFIELDS 19 // Bitfields for TABLE_STD_FLAGS values #define FLAGS_UPDATE_SZP 1 #define FLAGS_UPDATE_AO_ARITH 2 #define FLAGS_UPDATE_OC_LOGIC 4 // Helper macros // [I]MUL/[I]DIV/DAA/DAS/ADC/SBB helpers #define DAA_DAS(op1,op2) set_AF((((scratch_uchar = regs8[REG_AL]) & 0x0F) > 9) || regs8[FLAG_AF]) && (op_result = (regs8[REG_AL] op1 6), set_CF(regs8[FLAG_CF] || (regs8[REG_AL] op2 scratch_uchar))), \ set_CF((regs8[REG_AL] > 0x9f) || regs8[FLAG_CF]) && (op_result = (regs8[REG_AL] op1 0x60)) #define ADC_SBB_MACRO(a) (i_w ? op_dest = *(uint16_t*)&mem[ op_to_addr ], op_result = *(uint16_t*)&mem[ op_to_addr ] a##= regs8[FLAG_CF] + (op_source = *(uint16_t*)&mem[ op_from_addr ]) : (op_dest = mem[ op_to_addr ], op_result = mem[ op_to_addr ] a##= regs8[FLAG_CF] + (op_source = *(uint8_t*)&mem[ op_from_addr ]))), \ set_CF((regs8[FLAG_CF] && (op_result == op_dest)) || (a op_result < a(int)op_dest)), \ set_AF_OF_arith() // Global variable definitions typedef struct STOPCODE_T { uint32_t set_flags_type ; uint8_t raw_opcode_id ; uint8_t xlat_opcode_id ; uint8_t extra ; uint8_t i_mod_size ; } stOpcode_t ; stOpcode_t stOpcode ; uint32_t op_source ; uint32_t op_dest ; uint32_t rm_addr ; uint32_t op_to_addr ; uint32_t op_from_addr ; uint32_t scratch_uint ; uint32_t scratch2_uint ; int op_result , disk[ 3 ] , scratch_int ; uint16_t * regs16 ; uint16_t reg_ip ; uint16_t seg_override ; uint16_t i_data0 ; uint16_t i_data1 ; uint16_t i_data2 ; uint8_t bios_table_lookup[ 20 ][ 256 ] ; uint8_t * regs8 ; uint8_t i_rm ; uint8_t i_w ; uint8_t i_reg ; uint8_t i_mod ; uint8_t i_d ; uint8_t i_reg4bit ; uint8_t rep_mode ; uint8_t seg_override_en ; uint8_t rep_override_en ; uint8_t trap_flag ; uint8_t scratch_uchar ; // Helper functions // Set carry flag int8_t set_CF( int new_CF ) { uint8_t reg ; reg = ( new_CF ) ? XTRUE : XFALSE ; regs8[ FLAG_CF ] = reg ; return( reg ) ; } // Set auxiliary flag int8_t set_AF( int new_AF ) { uint8_t reg ; reg = ( new_AF ) ? XTRUE : XFALSE ; regs8[ FLAG_AF ] = reg ; return( reg ) ; } // Set overflow flag int8_t set_OF( int new_OF ) { uint8_t reg ; reg = ( new_OF ) ? XTRUE : XFALSE ; regs8[ FLAG_OF ] = reg ; return( reg ) ; } // Set auxiliary and overflow flag after arithmetic operations int8_t set_AF_OF_arith( void ) { uint8_t reg ; op_source ^= ( op_dest ^ op_result ) ; reg = op_source & 0x10 ; set_AF( reg ) ; if( op_result == op_dest ) { reg = set_OF( 0 ) ; } else if( i_w ) { // i_w == 1 reg = set_OF( 1 & ( regs8[ FLAG_CF ] ^ op_source >> 15 ) ) ; } else { // i_w == 0 reg = set_OF( 1 & ( regs8[ FLAG_CF ] ^ op_source >> 7 ) ) ; } return( reg ) ; } // Assemble and return emulated CPU FLAGS register in scratch_uint void make_flags( void ) { uint8_t i ; // 8086 has reserved and unused flags set to 1 scratch_uint = 0xF002 ; for( i = 0 ; i < 9 ; i++ ) { scratch_uint += regs8[ FLAG_CF + i ] << bios_table_lookup[ TABLE_FLAGS_BITFIELDS ][ i ] ; } } // Set emulated CPU FLAGS register from regs8[FLAG_xx] values void set_flags( int new_flags ) { uint8_t i ; for( i = 0 ; i < 9 ; i++ ) { regs8[ FLAG_CF + i ] = ( 1 << bios_table_lookup[ TABLE_FLAGS_BITFIELDS ][ i ] & new_flags ) ? XTRUE : XFALSE ; } } // Convert raw opcode to translated opcode index. This condenses a large number of different encodings of similar // instructions into a much smaller number of distinct functions, which we then execute void set_opcode( uint8_t opcode ) { stOpcode.raw_opcode_id = opcode ; stOpcode.xlat_opcode_id = bios_table_lookup[ TABLE_XLAT_OPCODE ][ opcode ] ; stOpcode.extra = bios_table_lookup[ TABLE_XLAT_SUBFUNCTION ][ opcode ] ; stOpcode.i_mod_size = bios_table_lookup[ TABLE_I_MOD_SIZE ][ opcode ] ; stOpcode.set_flags_type = bios_table_lookup[ TABLE_STD_FLAGS ][ opcode ] ; } // Execute INT #interrupt_num on the emulated machine int8_t pc_interrupt( uint8_t interrupt_num ) { // Decode like INT. set_opcode( 0xCD ) ; make_flags() ; i_w = 1 ; // PUSH scratch_uint. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_CS ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_CS ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH reg_ip. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&reg_ip ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // Execute arithmetic/logic operations in emulator memory/registers if( i_w ) { op_dest = *( uint16_t * )&mem[ REGS_BASE + 2 * REG_CS ] ; op_source = *( uint16_t * )&mem[ 4 * interrupt_num + 2 ] ; op_result = op_source ; *( uint16_t * )&mem[ REGS_BASE + 2 * REG_CS ] = op_source ; } else { op_dest = mem[ REGS_BASE + 2 * REG_CS ] ; op_source = *( uint8_t * )&mem[ 4 * interrupt_num + 2 ] ; op_result = op_source ; mem[ REGS_BASE + 2 * REG_CS ] = op_source ; } // Execute arithmetic/logic operations in emulator memory/registers if( i_w ) { op_dest = *( uint16_t * )&reg_ip ; op_source = *( uint16_t * )&mem[ 4 * interrupt_num ] ; op_result = op_source ; *( uint16_t * )&reg_ip = op_source ; } else { op_dest = reg_ip ; op_source = *( uint8_t * )&mem[ 4 * interrupt_num ] ; reg_ip = op_source ; op_result = op_source ; } regs8[ FLAG_IF ] = 0 ; regs8[ FLAG_TF ] = 0 ; return( 0 ) ; } // AAA and AAS instructions - which_operation is +1 for AAA, and -1 for AAS int AAA_AAS(int8_t which_operation) { return( regs16[ REG_AX ] += 262 * which_operation * set_AF( set_CF( ( ( regs8[ REG_AL ] & 0x0F) > 9) || regs8[FLAG_AF])), regs8[REG_AL] &= 0x0F); } void Reset( void ) { uint32_t i ; // Fill RAM with 00h. // BIOS area is 64K from F0000h. memset( ( void * ) mem , 0x00 , ( size_t ) RAM_SIZE ) ; for( i = 0 ; i < 3 ; i++ ) { if( disk[ i ] != 0 ) { close( disk[ i ] ) ; disk[ i ] = 0 ; } } if( Interface.GetBIOSFilename() != NULL ) { disk[ 2 ] = open( Interface.GetBIOSFilename() , O_BINARY | O_NOINHERIT | O_RDWR ) ; } if( Interface.GetFDImageFilename() != NULL ) { disk[ 1 ] = open( Interface.GetFDImageFilename() , O_BINARY | O_NOINHERIT | O_RDWR ) ; } if( Interface.GetHDImageFilename() != NULL ) { disk[ 0 ] = open( Interface.GetHDImageFilename() , O_BINARY | O_NOINHERIT | O_RDWR ) ; } // Set CX:AX equal to the hard disk image size, if present *( uint32_t * )&regs16[ REG_AX ] = ( disk[ 0 ] ) ? ( lseek( disk[ 0 ] , 0 , 2 ) >> 9 ) : ( 0 ) ; // CS is initialised to F000 regs16[ REG_CS ] = ( REGS_BASE >> 4 ) ; // Load BIOS image into F000:0100, and set IP to 0100 reg_ip = 0x100 ; read( disk[ 2 ] , ( regs8 + 0x100 ) , 0xFF00 ) ; // Initialise CPU state variables seg_override_en = 0 ; rep_override_en = 0 ; // Load instruction decoding helper table vectors for( i = 0 ; i < 20 ; i++ ) { for( int j = 0 ; j < 256 ; j++ ) { bios_table_lookup[ i ][ j ] = regs8[ regs16[ 0x81 + i ] + j ] ; } } } // Emulator entry point #if defined(_WIN32) int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE /* hPrevInstance */, LPSTR /* lpCmdLine */, int /* nCmdShow */) #else int main(int argc, char **argv) #endif { uint8_t * opcode_stream ; #if defined(_WIN32) Interface.SetInstance(hInstance); #endif Interface.Initialise( mem ) ; // regs16 and reg8 point to F000:0, the start of memory-mapped registers regs8 = ( uint8_t * ) ( mem + REGS_BASE ) ; // Base + 000F.0000 regs16 = ( uint16_t * ) ( mem + REGS_BASE ) ; // Base + 000F.0000 // Clear BIOS and disk filed. disk[ 0 ] = 0 ; disk[ 1 ] = 0 ; disk[ 2 ] = 0 ; // Reset, loads initial disk and bios images, clears RAM and sets CS & IP. Reset() ; // Instruction execution loop. bool ExitEmulation = false ; while( !ExitEmulation ) { opcode_stream = mem + 16 * regs16[ REG_CS ] + reg_ip ; // Set up variables to prepare for decoding an opcode. set_opcode( *opcode_stream ) ; /********** * * 7 6 5 4 3 2 1 0 * +-----+-----+-----+-----+-----+-----+-----+-----+ * | | | | | | REG | * +-----+-----+-----+-----+-----+-----+-----+-----+ * \_ _/ \_ _/ * | | * | +---> W * +---------> D * **********/ // Extract i_w and i_d fields from instruction. i_reg4bit = stOpcode.raw_opcode_id & 0x07 ; i_w = ( i_reg4bit & 0x01 ) == 0x01 ; i_d = ( i_reg4bit & 0x02 ) == 0x02 ; // Extract instruction data fields i_data0 = *( int16_t * )&opcode_stream[ 1 ] ; i_data1 = *( int16_t * )&opcode_stream[ 2 ] ; i_data2 = *( int16_t * )&opcode_stream[ 3 ] ; // seg_override_en and rep_override_en contain number of instructions to hold segment override and REP prefix respectively if( seg_override_en ) { seg_override_en-- ; } if( rep_override_en ) { rep_override_en-- ; } // i_mod_size > 0 indicates that opcode uses i_mod/i_rm/i_reg, so decode them if( stOpcode.i_mod_size ) { /********** * * 7 6 5 4 3 2 1 0 * +-----+-----+-----+-----+-----+-----+-----+-----+ * | | | | * +-----+-----+-----+-----+-----+-----+-----+-----+ * \____ ____/ \_______ _______/ \_______ _______/ * | | | * | | +---------> i_rm * | +---------------------------> i_reg * +------------------------------------------> i_mod * **********/ i_mod = ( i_data0 >> 6 ) & 0x03 ; // ##...... i_reg = ( i_data0 >> 3 ) & 0x07 ; // ..###... i_rm = i_data0 & 0x07 ; // .....### if( ( !i_mod && i_rm == 6 ) || ( i_mod == 2 ) ) { i_data2 = *( int16_t * )&opcode_stream[ 4 ] ; } else if( i_mod != 1 ) { i_data2 = i_data1 ; } else // If i_mod is 1, operand is (usually) 8 bits rather than 16 bits { i_data1 = ( int8_t ) i_data1 ; } scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = ( 16 * regs16[ localIndex ] ) + localAddr ; } else { rm_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_rm ) : ( 2 * i_rm + i_rm / 4 ) & 7 ) ) ; } op_to_addr = rm_addr ; op_from_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_reg ) : ( 2 * i_reg + i_reg / 4 ) & 7 ) ) ; if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } } // Instruction execution unit. switch( stOpcode.xlat_opcode_id ) { // Conditional jump (JAE, JNAE, etc.) case 0x00 : // i_w is the invert flag, e.g. i_w == 1 means JNAE, whereas i_w == 0 means JAE scratch_uchar = stOpcode.raw_opcode_id ; scratch_uchar >>= 1 ; scratch_uchar &= 7 ; reg_ip += (int8_t)i_data0 * ( i_w ^ ( regs8[ bios_table_lookup[ TABLE_COND_JUMP_DECODE_A ][ scratch_uchar ] ] || regs8[ bios_table_lookup[ TABLE_COND_JUMP_DECODE_B ][ scratch_uchar ] ] || regs8[ bios_table_lookup[ TABLE_COND_JUMP_DECODE_C ][ scratch_uchar ] ] ^ regs8[ bios_table_lookup[ TABLE_COND_JUMP_DECODE_D ][ scratch_uchar ] ] ) ) ; break ; // MOV reg, imm case 0x01 : i_w = ( stOpcode.raw_opcode_id & 8 ) ? ( XTRUE ) : ( XFALSE ) ; if( i_w ) { *( uint16_t * )&op_dest = *( uint16_t * )&mem[ REGS_BASE + ( 2 * i_reg4bit ) ] ; *( uint16_t * )&op_source = *( uint16_t * )&i_data0 ; *( uint16_t * )&op_result = *( uint16_t * )&i_data0 ; *( uint16_t * )&mem[ REGS_BASE + ( 2 * i_reg4bit ) ] = *( uint16_t * )&i_data0 ; } else { *( uint8_t * )&op_dest = *( uint8_t * )&mem[ REGS_BASE + ( ( 2 * i_reg4bit + i_reg4bit / 4 ) & 0x07 ) ] ; *( uint8_t * )&op_source = *( uint8_t * )&i_data0 ; *( uint8_t * )&op_result = *( uint8_t * )&i_data0 ; *( uint8_t * )&mem[ REGS_BASE + ( ( 2 * i_reg4bit + i_reg4bit / 4 ) & 0x07 ) ] = *( uint8_t * )&i_data0 ; } break ; // PUSH regs16. case 0x03 : i_w = 1 ; op_dest = *( uint16_t * ) &mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * ) &regs16[ i_reg4bit ] ; op_result = op_source ; *( uint16_t * ) &mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // POP regs16. case 0x04 : i_w = 1 ; regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * ) &regs16[ i_reg4bit ] ; op_source = *( uint16_t * ) &( mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( - 2 + regs16[ REG_SP ] ) ] ) ; op_result = op_source ; *( uint16_t * ) &regs16[ i_reg4bit ] = op_source ; break ; // INC|DEC regs16 case 0x02 : i_w = 1 ; i_d = 0 ; i_reg = i_reg4bit ; scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = ( 16 * regs16[ localIndex ] ) + localAddr ; } else { rm_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_rm ) : ( 2 * i_rm + i_rm / 4 ) & 7 ) ) ; } op_to_addr = rm_addr ; op_from_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_reg ) : ( 2 * i_reg + i_reg / 4 ) & 7 ) ); if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } i_reg = stOpcode.extra ; // INC|DEC|JMP|CALL|PUSH case 0x05 : // INC|DEC if( i_reg < 2 ) { uint32_t addr ; addr = REG_ZERO ; addr *= 2 ; addr += REGS_BASE ; if( i_w ) { op_dest = *( uint16_t * )&mem[ op_from_addr ] ; op_source = *( uint16_t * )&mem[ addr ] ; *( uint16_t * )&mem[ op_from_addr ] += 1 - 2 * i_reg + op_source ; op_result = *( uint16_t * )&mem[ op_from_addr ] ; } else { op_dest = mem[ op_from_addr ] ; op_source = *( uint8_t * )&mem[ addr ] ; mem[ op_from_addr ] += 1 - 2 * i_reg + op_source ; op_result = mem[ op_from_addr ] ; } op_source = 1 ; set_AF_OF_arith() ; if( i_w ) { set_OF( op_dest + 1 - i_reg == 1 << 15 ) ; } else { set_OF( op_dest + 1 - i_reg == 1 << 7 ) ; } if( stOpcode.xlat_opcode_id == 0x05 ) { // Decode like ADC. set_opcode( 0x10 ) ; } } else if( i_reg != 6 ) // JMP|CALL { // CALL (far) if( i_reg == 3 ) { // PUSH regs16[ REG_CS ]. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_CS ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } // CALL (near or far) if( i_reg & 0x02 ) { // PUSH ( reg_ip + 2 + i_mod * ( i_mod != 3 ) + 2 * ( !i_mod && i_rm == 6 ) ). i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&reg_ip + 2 + i_mod * ( i_mod != 3 ) + 2 * ( !i_mod && i_rm == 6 ) ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } // JMP|CALL (far) if( i_reg & 0x01 ) { regs16[ REG_CS ] = *( int16_t * )&mem[ op_from_addr + 2 ] ; } if( i_w ) { op_dest = *( uint16_t * )&reg_ip ; op_source = *(uint16_t*)&mem[ op_from_addr ] ; op_result = op_source ; *(uint16_t*)&reg_ip = op_source ; } else { op_dest = reg_ip ; op_source = *(uint8_t*)&mem[ op_from_addr ] ; op_result = op_source ; reg_ip = op_source ; } // Decode like CALL set_opcode( 0x9A ) ; } else // PUSH { // PUSH mem[ rm_addr ]. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&mem[ rm_addr ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } break ; // TEST r/m, imm16 / NOT|NEG|MUL|IMUL|DIV|IDIV reg case 0x06 : op_to_addr = op_from_addr ; switch( i_reg ) { // TEST case 0x00 : // Decode like AND set_opcode( 0x20 ) ; reg_ip += i_w + 1; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&i_data2 ; op_result = *( uint16_t * )&mem[ op_to_addr ] & op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&i_data2 ; op_result = mem[ op_to_addr ] & op_source ; } break ; // NOT case 0x02 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] =~ op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] =~ op_source ; } break ; // NEG case 0x03 : // Execute arithmetic/logic operations. if( i_w ) { op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] =- op_source ; } else { op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] =- op_source ; } op_dest = 0 ; // Decode like SUB set_opcode( 0x28 ) ; set_CF( op_result > op_dest ) ; break ; // MUL case 0x04 : if( i_w ) { int8_t flagRet ; set_opcode( 0x10 ) ; op_result = ( uint16_t ) regs16[ 0 ] ; op_result *= *( uint16_t * )&mem[ rm_addr ] ; regs16[ i_w + 1 ] = op_result >> 16 ; regs16[ REG_AX ] = op_result ; flagRet = set_CF( op_result - ( uint16_t ) op_result ) ; set_OF( flagRet ) ; } else { int8_t flagRet ; set_opcode( 0x10 ) ; op_result = ( uint8_t ) regs8[ 0 ] ; op_result *= *( uint8_t * )&mem[ rm_addr ] ; regs8[ i_w + 1 ] = op_result >> 16 ; regs16[ REG_AX ] = op_result ; flagRet = set_CF( op_result - ( uint8_t ) op_result ) ; set_OF( flagRet ) ; } break ; // IMUL case 0x05 : if( i_w ) { int8_t flagRet ; set_opcode( 0x10 ) ; op_result = ( int16_t ) regs16[ 0 ] ; op_result *= *( int16_t * ) &mem[ rm_addr ] ; regs16[ i_w + 1 ] = op_result >> 16 ; regs16[ REG_AX ] = op_result ; flagRet = set_CF( op_result - ( int16_t ) op_result ) ; set_OF( flagRet ) ; } else { int8_t flagRet ; set_opcode( 0x10 ) ; op_result = ( int8_t ) regs8[ 0 ] ; op_result *= *( int8_t * ) &mem[ rm_addr ] ; regs8[ i_w + 1 ] = op_result >> 16 ; regs16[ REG_AX ] = op_result ; flagRet = set_CF( op_result - ( int8_t ) op_result ) ; set_OF( flagRet ) ; } break ; // DIV case 0x06 : if( i_w ) { scratch_int = *( uint16_t * ) &mem[ rm_addr ] ; if( scratch_int ) { scratch_uint = ( regs16[ 2 ] << 16 ) + regs16[ REG_AX ] ; scratch2_uint = ( uint32_t ) ( scratch_uint ) / scratch_int ; if( scratch2_uint - ( uint16_t ) scratch2_uint ) { pc_interrupt( 0 ) ; } else { regs16[ 0 ] = scratch2_uint ; regs16[ 2 ] = scratch_uint - scratch_int * scratch2_uint ; } } } else { scratch_int = *( uint8_t * ) &mem[ rm_addr ] ; if( scratch_int ) { scratch_uint = ( regs8[ 1 ] << 16 ) + regs16[ REG_AX ] ; scratch2_uint = ( uint16_t ) ( scratch_uint ) / scratch_int ; if( scratch2_uint - ( uint8_t )scratch2_uint ) { pc_interrupt( 0 ) ; } else { regs8[ 0 ] = scratch2_uint ; regs8[ 1 ] = scratch_uint - scratch_int * scratch2_uint ; } } } break ; // IDIV case 0x07 : if( i_w ) { scratch_int = *( int16_t * ) &mem[ rm_addr ] ; if( scratch_int ) { scratch_uint = ( regs16[ 2 ] << 16 ) + regs16[ REG_AX ] ; scratch2_uint = ( int32_t ) ( scratch_uint ) / scratch_int ; if( scratch2_uint - ( int16_t ) scratch2_uint ) { pc_interrupt( 0 ) ; } else { regs16[ 0 ] = scratch2_uint ; regs16[ 2 ] = scratch_uint - scratch_int * scratch2_uint ; } } } else { scratch_int = *( int8_t * ) &mem[ rm_addr ] ; if( scratch_int ) { scratch_uint = ( regs8[ 1 ] << 16 ) + regs16[ REG_AX ] ; scratch2_uint = ( int16_t ) ( scratch_uint ) / scratch_int ; if( scratch2_uint - ( int8_t ) scratch2_uint ) { pc_interrupt( 0 ) ; } else { regs8[ 0 ] = scratch2_uint ; regs8[ 1 ] = scratch_uint - scratch_int * scratch2_uint ; } } } break ; } break ; // ADD|OR|ADC|SBB|AND|SUB|XOR|CMP AL/AX, immed case 0x07 : rm_addr = REGS_BASE ; i_data2 = i_data0 ; i_mod = 3 ; i_reg = stOpcode.extra ; reg_ip-- ; // ADD|OR|ADC|SBB|AND|SUB|XOR|CMP reg, immed case 0x08 : op_to_addr = rm_addr ; i_d |= !i_w ; if( i_d ) { regs16[ REG_SCRATCH ] = ( int8_t ) i_data2 ; } else { regs16[ REG_SCRATCH ] = i_data2 ; } op_from_addr = REGS_BASE + 2 * REG_SCRATCH ; reg_ip += ( !i_d + 1 ) ; stOpcode.extra = i_reg ; set_opcode( 0x08 * i_reg ) ; // ADD|OR|ADC|SBB|AND|SUB|XOR|CMP|MOV reg, r/m case 0x09 : switch( stOpcode.extra ) { // ADD case 0x00 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] += op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] += op_source ; } set_CF( op_result < op_dest ) ; break ; // OR case 0x01 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] |= op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] |= op_source ; } break ; // ADC case 0x02 : ADC_SBB_MACRO( + ) ; break ; // SBB case 0x03 : ADC_SBB_MACRO( - ) ; break ; // AND case 0x04 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] &= op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] &= op_source ; } break ; // SUB case 0x05 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] -= op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] -= op_source ; } set_CF( op_result > op_dest ) ; break ; // XOR case 0x06 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] ^= op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] ^= op_source ; } break ; // CMP case 0x07 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] - op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] - op_source ; } set_CF( op_result > op_dest ) ; break ; // MOV case 0x08 : if( i_w ) { uint16_t aux ; op_dest = *( uint16_t * )&mem[ op_to_addr ] ; aux = *( uint16_t * )&mem[ op_from_addr ] ; op_source = aux ; op_result = aux ; *( uint16_t * )&mem[ op_to_addr ] = aux ; } else { uint8_t aux ; op_dest = mem[ op_to_addr ] ; aux = *( uint8_t * )&mem[ op_from_addr ] ; op_source = aux ; op_result = aux ; mem[ op_to_addr ] = aux ; } break ; } break ; // MOV sreg, r/m | POP r/m | LEA reg, r/m case 0x0A : // MOV if( !i_w ) { i_w = 1, i_reg += 8, scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = ( 16 * regs16[ localIndex ] ) + localAddr ; } else { rm_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_rm ) : ( 2 * i_rm + i_rm / 4 ) & 7 ) ) ; } op_to_addr = rm_addr ; op_from_addr = (REGS_BASE + ( ( i_w ) ? ( 2 * i_reg ) : ( 2 * i_reg + i_reg / 4 ) & 7 ) ) ; if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = op_source ; *( uint16_t * )&mem[ op_to_addr ] = op_source ; } else { op_dest = mem[ op_to_addr ] ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = op_source ; mem[ op_to_addr ] = op_source ; } } else if( !i_d ) // LEA { seg_override_en = 1 ; seg_override = REG_ZERO ; scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = ( 16 * regs16[ localIndex ] ) + localAddr ; } else { rm_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_rm ) : ( 2 * i_rm + i_rm / 4 ) & 7 ) ) ; } op_to_addr = rm_addr ; op_from_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_reg ) : ( 2 * i_reg + i_reg / 4 ) & 7 ) ) ; if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } // MOV if( i_w ) { uint16_t aux ; op_dest = *( uint16_t * )&mem[ op_from_addr ] ; aux = *( uint16_t * )&rm_addr ; op_source = aux ; op_result = aux ; *( uint16_t * )&mem[ op_from_addr ] = aux ; } else { uint8_t aux ; op_dest = mem[ op_from_addr ] ; aux = *( uint8_t * )&rm_addr ; op_source = aux ; op_result = aux ; mem[ op_from_addr ] = aux ; } } else // POP { uint32_t addr ; i_w = 1 ; regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&mem[ rm_addr ] ; addr = 16 ; addr *= regs16[ REG_SS ] ; addr += ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ; op_source = *( uint16_t * )&mem[ addr ] ; op_result = op_source ; *( uint16_t * )&mem[ rm_addr ] = op_source ; } break ; // MOV AL/AX, [loc] case 0x0B : i_mod = 0 ; i_reg = 0 ; i_rm = 6 ; i_data1 = i_data0 ; scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = ( 16 * regs16[ localIndex ] ) + localAddr ; } else { rm_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_rm ) : ( 2 * i_rm + i_rm / 4 ) & 7 ) ) ; } op_to_addr = rm_addr ; op_from_addr = ( REGS_BASE + ( ( i_w ) ? ( 2 * i_reg ) : ( 2 * i_reg + i_reg / 4 ) & 7 ) ) ; if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } // MOV if( i_w ) { uint16_t aux ; op_dest = *( uint16_t * )&mem[ op_from_addr ] ; aux = *( uint16_t * )&mem[ op_to_addr ] ; op_source = aux ; op_result = aux ; *( uint16_t * )&mem[ op_from_addr ] = aux ; } else { uint8_t aux ; op_dest = mem[ op_from_addr ] ; aux = *( uint8_t * )&mem[ op_to_addr ] ; op_source = aux ; op_result = aux ; mem[ op_from_addr ] = aux ; } break ; // ROL|ROR|RCL|RCR|SHL|SHR|???|SAR reg/mem, 1/CL/imm (80186) case 0x0C : // Returns sign bit of an 8-bit or 16-bit operand. if( i_w ) { scratch2_uint = *( int16_t * )&( mem[ rm_addr ] ) ; scratch2_uint >>= 15 ; } else { scratch2_uint = ( mem[ rm_addr ] ) ; scratch2_uint >>= 7 ; } scratch2_uint &= 1 ; if( stOpcode.extra ) { // xxx reg/mem, imm scratch_uint = ( int8_t ) i_data1 ; } else if( i_d ) { // xxx reg/mem, CL scratch_uint = 0x1F & regs8[ REG_CL ] ; } else { // xxx reg/mem, 1 scratch_uint = 0x01 ; } if( scratch_uint ) { if( i_reg < 4 ) // Rotate operations { scratch_uint %= i_reg / 2 + 8 * ( i_w + 1 ) ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&scratch2_uint ; op_source = *( uint16_t * )&mem[ rm_addr ] ; op_result = *( uint16_t * )&scratch2_uint = op_source ; } else { op_dest = scratch2_uint ; op_source = *( uint8_t * )&mem[ rm_addr ] ; op_result = scratch2_uint = op_source ; } } if( i_reg & 1 ) // Rotate/shift right operations { // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ rm_addr ] >>= op_source ; } else { op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch_uint ; op_result = mem[ rm_addr ] >>= op_source ; } } else // Rotate/shift left operations { // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ rm_addr ] <<= op_source ; } else { op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch_uint ; op_result = mem[ rm_addr ] <<= op_source ; } } // Shift operations if( i_reg > 3 ) { // Shift instructions affect SZP stOpcode.set_flags_type = FLAGS_UPDATE_SZP ; } // SHR or SAR if( i_reg > 4 ) { set_CF( op_dest >> ( scratch_uint - 1 ) & 1 ) ; } } switch( i_reg ) { // ROL case 0x00 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch2_uint >> ( 16 - scratch_uint ) ; op_result = *( uint16_t * )&mem[ rm_addr ] += op_source ; // Returns sign bit of an 8-bit or 16-bit operand set_OF( ( 1 & ( *( int16_t * )&( op_result ) ) >> 15 ) ^ set_CF( op_result & 1 ) ) ; } else { op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch2_uint >> ( 8 - scratch_uint ) ; op_result = mem[ rm_addr ] += op_source ; // Returns sign bit of an 8-bit or 16-bit operand set_OF( ( 1 & op_result >> 7 ) ^ set_CF( op_result & 1 ) ) ; } break ; // ROR case 0x01 : scratch2_uint &= ( 1 << scratch_uint ) - 1 ; if( i_w ) { // Execute arithmetic/logic operations. op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch2_uint << ( 16 - scratch_uint ) ; op_result = *( uint16_t * )&mem[ rm_addr ] += op_source ; set_OF( ( 1 & ( *( int16_t * )&op_result * 2 ) >> 15 ) ^ set_CF( 1 & ( *( int16_t * )&( op_result ) ) >> 15 ) ) ; } else { // Execute arithmetic/logic operations. op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch2_uint << ( 8 - scratch_uint ) ; op_result = mem[ rm_addr ] += op_source ; set_OF( ( 1 & ( op_result * 2 ) >> 7 ) ^ set_CF( 1 & ( op_result ) >> 7 ) ) ; } break ; // RCL case 0x02 : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch2_uint >> ( 17 - scratch_uint ) ; op_result = *( uint16_t * )&mem[ rm_addr ] += ( regs8[ FLAG_CF ] << ( scratch_uint - 1 ) ) + op_source ; set_OF( ( 1 & *( int16_t * )&( op_result ) >> 15 ) ^ set_CF( scratch2_uint & 1 << ( 16 - scratch_uint ) ) ) ; } else { op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch2_uint >> ( 9 - scratch_uint ) ; op_result = mem[ rm_addr ] += ( regs8[ FLAG_CF ] << ( scratch_uint - 1 ) ) + op_source ; set_OF( ( ( 1 & op_result ) >> 7 ) ^ set_CF( scratch2_uint & 1 << ( 8 - scratch_uint ) ) ) ; } break ; // RCR case 0x03 : if( i_w ) { // Execute arithmetic/logic operations. op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch2_uint << ( 17 - scratch_uint ) ; op_result = *( uint16_t * )&mem[ rm_addr ] += ( regs8[ FLAG_CF ] << ( 16 - scratch_uint ) ) + op_source ; set_CF( scratch2_uint & 1 << ( scratch_uint - 1 ) ) ; set_OF( ( 1 & *( int16_t * )&( op_result ) >> 15 ) ^ ( 1 & *( int16_t * )&op_result * 2 >> 15 ) ) ; } else { // Execute arithmetic/logic operations. op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch2_uint << ( 9 - scratch_uint ) ; op_result = mem[ rm_addr ] += ( regs8[ FLAG_CF ] << ( 8 - scratch_uint ) ) + op_source ; set_CF( scratch2_uint & 1 << ( scratch_uint - 1 ) ) ; set_OF( ( 1 & op_result >> 7 ) ^ ( 1 & ( op_result * 2 ) >> 7 ) ) ; } break ; // SHL case 0x04 : if( i_w ) { set_OF( ( 1 & *( int16_t * )&( op_result ) >> 15 ) ^ set_CF( ( 1 & *( int16_t * )&op_dest << ( scratch_uint - 1 ) ) >> 15 ) ) ; } else { set_OF( ( 1 & op_result >> 7 ) ^ set_CF( ( 1 & ( op_dest << ( scratch_uint - 1 ) ) >> 7 ) ) ) ; } break ; // SHR case 0x05 : if( i_w ) { set_OF( 1 & *( int16_t * )&( op_dest ) >> 15 ) ; } else { set_OF( ( 1 & ( op_dest ) >> 7 ) ) ; } break ; // SAR case 0x07 : if( !( scratch_uint < 8 * ( i_w + 1 ) ) ) { set_CF( scratch2_uint ) ; } set_OF( 0 ) ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ rm_addr ] ; op_source = *( uint16_t * )&scratch2_uint *= ~( ( ( 1 << 16 ) - 1 ) >> scratch_uint ) ; op_result = *( uint16_t * )&mem[ rm_addr ] += op_source ; } else { op_dest = mem[ rm_addr ] ; op_source = *( uint8_t * )&scratch2_uint *= ~( ( ( 1 << 8 ) - 1 ) >> scratch_uint ) ; op_result = mem[ rm_addr ] += op_source ; } break ; } break ; // LOOPxx|JCZX case 0x0D : regs16[ REG_CX ]-- ; scratch_uint = ( regs16[ REG_CX ] ) ? ( XTRUE ) : ( XFALSE ) ; switch( i_reg4bit ) { // LOOPNZ case 0x00 : scratch_uint &= !regs8[ FLAG_ZF ] ; break ; // LOOPZ case 0x01 : scratch_uint &= regs8[ FLAG_ZF ] ; break ; // JCXXZ case 0x03 : scratch_uint = !++regs16[ REG_CX ] ; break ; } reg_ip += scratch_uint * ( ( int8_t ) i_data0 ) ; break ; // JMP | CALL short/near case 0x0E : reg_ip += 3 - i_d ; if( !i_w ) { if( i_d ) // JMP far { reg_ip = 0 ; regs16[ REG_CS ] = i_data2 ; } else // CALL { // PUSH reg_ip. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&reg_ip ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } } reg_ip += ( i_d && i_w ) ? ( ( int8_t ) i_data0 ) : ( i_data0 ) ; break ; // TEST reg, r/m case 0x0F : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ op_from_addr ] ; op_source = *( uint16_t * )&mem[ op_to_addr ] ; op_result = *( uint16_t * )&mem[ op_from_addr ] & op_source ; } else { op_dest = mem[ op_from_addr ] ; op_source = *( uint8_t * )&mem[ op_to_addr ] ; op_result = mem[ op_from_addr ] & op_source ; } break ; // XCHG AX, regs16 case 0x10 : i_w = 1 ; op_to_addr = REGS_BASE ; op_from_addr = ( REGS_BASE + ( 2 * i_reg4bit ) ) ; // NOP|XCHG reg, r/m case 0x18 : if( op_to_addr != op_from_addr ) { // Execute arithmetic/logic operations. if( i_w ) { op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] ^= op_source ; op_source = *( uint16_t * )&mem[ op_to_addr ] ; op_result = *( uint16_t * )&mem[ op_from_addr ] ^= op_source ; op_dest = *( uint16_t * )&mem[ op_to_addr ] ; op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = *( uint16_t * )&mem[ op_to_addr ] ^= op_source ; } else { op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] ^= op_source ; op_dest = mem[ op_from_addr ] ; op_source = *( uint8_t * )&mem[ op_to_addr ] ; op_result = mem[ op_from_addr ] ^= op_source ; op_source = *( uint8_t * )&mem[ op_from_addr ] ; op_result = mem[ op_to_addr ] ^= op_source ; } } break ; // MOVSx (extra=0)|STOSx (extra=1)|LODSx (extra=2) case 0x11 : scratch2_uint = ( seg_override_en ) ? ( seg_override ) : ( REG_DS ) ; scratch_uint = ( rep_override_en ) ? ( regs16[ REG_CX ] ) : ( 1 ) ; while( scratch_uint ) { uint32_t addrDst ; uint32_t addrSrc ; // Convert segment:offset to linear address. addrSrc = 16 ; addrSrc *= regs16[ scratch2_uint ] ; addrSrc += ( uint16_t ) regs16[ REG_SI ] ; addrDst = 16 ; addrDst *= regs16[ REG_ES ] ; addrDst += ( uint16_t ) regs16[ REG_DI ] ; // MOV if( i_w ) { uint16_t aux ; op_dest = *( uint16_t * )&( mem[ ( stOpcode.extra < 2 ) ? addrDst : REGS_BASE ] ) ; aux = *( uint16_t * )&( mem[ ( stOpcode.extra & 1 ) ? REGS_BASE : addrSrc ] ) ; op_source = aux ; op_result = aux ; *( uint16_t * )&( mem[ ( stOpcode.extra < 2 ) ? addrDst : REGS_BASE ] ) = aux ; } else { uint8_t aux ; op_dest = ( mem[ ( stOpcode.extra < 2 ) ? addrDst : REGS_BASE ] ) ; aux = *( uint8_t * )&( mem[ ( stOpcode.extra & 1 ) ? REGS_BASE : addrSrc ] ) ; op_source = aux ; op_result = aux ; mem[ ( stOpcode.extra < 2 ) ? addrDst : REGS_BASE ] = aux ; } if( ( stOpcode.extra & 0x01 ) == 0x00 ) { regs16[ REG_SI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; } if( ( stOpcode.extra & 0x02 ) == 0x00 ) { regs16[ REG_DI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; } scratch_uint-- ; } if( rep_override_en ) { regs16[ REG_CX ] = 0 ; } break ; // CMPSx (extra=0)|SCASx (extra=1) case 0x12 : scratch2_uint = ( seg_override_en ) ? ( seg_override ) : ( REG_DS ) ; scratch_uint = ( rep_override_en ) ? ( regs16[ REG_CX ] ) : ( 1 ) ; if( scratch_uint ) { while( scratch_uint ) { uint32_t addrSrc ; uint32_t addrDst ; // Convert segment:offset to linear address. addrSrc = 16 ; addrSrc *= regs16[ REG_ES ] ; addrSrc += ( uint16_t ) regs16[ REG_DI ] ; addrDst = 16 ; addrDst *= regs16[ scratch2_uint ] ; addrDst += ( uint16_t ) regs16[ REG_SI ] ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ stOpcode.extra ? REGS_BASE : addrDst ] ; op_source = *( uint16_t * )&mem[ addrSrc ] ; op_result = *( uint16_t * )&mem[ stOpcode.extra ? REGS_BASE : addrDst ] - op_source ; } else { op_dest = mem[ stOpcode.extra ? REGS_BASE : addrDst ] ; op_source = *( uint8_t * )&mem[ addrSrc ] ; op_result = mem[ stOpcode.extra ? REGS_BASE : addrDst ] - op_source ; } if( !stOpcode.extra ) { regs16[ REG_SI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; } regs16[ REG_DI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; if( rep_override_en ) { regs16[ REG_CX ]-- ; if( !( regs16[ REG_CX ] && ( !op_result == rep_mode ) ) ) { scratch_uint = 0 ; } } if( !rep_override_en ) { scratch_uint-- ; } } // Funge to set SZP/AO flags. stOpcode.set_flags_type = ( FLAGS_UPDATE_SZP | FLAGS_UPDATE_AO_ARITH ) ; set_CF( op_result > op_dest ) ; } break ; // RET|RETF|IRET case 0x13 : { uint32_t addr ; i_d = i_w ; i_w = 1 ; regs16[ REG_SP ] += 2 ; addr = 16 ; addr *= regs16[ REG_SS ] ; addr += ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&reg_ip ; op_source = *( uint16_t * )&mem[ addr ] ; op_result = op_source ; *( uint16_t * )&reg_ip = op_source ; } else { op_dest = reg_ip ; op_source = *( uint8_t * )&mem[ addr ] ; op_result = op_source ; reg_ip = op_source ; } } // IRET|RETF|RETF imm16 if( stOpcode.extra ) { i_w = 1 ; regs16[ REG_SP ] += 2 ; // Execute arithmetic/logic operations. op_dest = *( uint16_t * )&regs16[ REG_CS ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ] ; op_result = op_source ; *( uint16_t * )&regs16[ REG_CS ] = op_source ; } if( stOpcode.extra & 0x02 )// IRET { uint32_t addr ; i_w = 1 ; regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&scratch_uint ; addr = 16 ; addr *= regs16[ REG_SS ] ; addr += ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ; op_source = *( uint16_t * )&mem[ addr ] ; op_result = *( uint16_t * )&scratch_uint = op_source ; set_flags( op_result ) ; } else if( !i_d ) // RET|RETF imm16 { regs16[ REG_SP ] += i_data0 ; } break ; // MOV r/m, immed case 0x14 : regs16[ REG_TMP ] = i_data2 ; // MOV if( i_w ) { uint16_t aux ; op_dest = *( uint16_t * )&mem[ op_from_addr ] ; aux = *( uint16_t * )&mem[ REGS_BASE + REG_TMP * 2 ] ; op_source = aux ; op_result = aux ; *( uint16_t * )&mem[ op_from_addr ] = aux ; } else { uint8_t aux ; op_dest = mem[ op_from_addr ] ; aux = *( uint8_t * )&mem[ REGS_BASE + REG_TMP * 2 ] ; op_source = aux ; op_result = aux ; mem[ op_from_addr ] = aux ; } break ; // IN AL/AX, DX/imm8 case 0x15 : scratch_uint = ( stOpcode.extra ) ? ( regs16[ REG_DX ] ) : ( ( uint8_t ) i_data0 ) ; io_ports[ scratch_uint ] = Interface.ReadPort( scratch_uint ) ; if( i_w ) { io_ports[ scratch_uint + 1 ] = Interface.ReadPort( scratch_uint + 1 ) ; // Execute arithmetic/logic operations. op_dest = *( uint16_t * )&regs8[ REG_AL ] ; op_source = *( uint16_t * )&io_ports[ scratch_uint ] ; op_result = op_source ; *( uint16_t * )&regs8[ REG_AL ] = op_source ; } else { // Execute arithmetic/logic operations. op_dest = regs8[ REG_AL ] ; op_source = *( uint8_t * )&io_ports[ scratch_uint ] ; op_result = op_source ; regs8[ REG_AL ] = op_source ; } break ; // OUT DX/imm8, AL/AX case 0x16 : scratch_uint = ( stOpcode.extra ) ? ( regs16[ REG_DX ] ) : ( ( uint8_t ) i_data0 ) ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&io_ports[ scratch_uint ] ; op_source = *( uint16_t * )&regs8[ REG_AL ] ; op_result = op_source ; *( uint16_t * )&io_ports[ scratch_uint ] = op_source ; Interface.WritePort( scratch_uint , io_ports[ scratch_uint ] ) ; Interface.WritePort( scratch_uint + 1 , io_ports[ scratch_uint + 1 ] ) ; } else { op_dest = io_ports[ scratch_uint ] ; op_source = *( uint8_t * )&regs8[ REG_AL ] ; op_result = op_source ; io_ports[ scratch_uint ] = op_source ; Interface.WritePort( scratch_uint , io_ports[ scratch_uint ] ) ; } break ; // REPxx case 0x17 : rep_override_en = 2 ; rep_mode = i_w ; if( seg_override_en ) { seg_override_en++ ; } break ; // PUSH reg case 0x19 : // PUSH regs16[ stOpcode.extra ]. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ stOpcode.extra ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // POP reg case 0x1A : i_w = 1 ; regs16[ REG_SP ] += 2 ; // Execute arithmetic/logic operations. op_dest = *( uint16_t * )&regs16[ stOpcode.extra ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ] ; op_result = op_source ; *( uint16_t * )&regs16[ stOpcode.extra ] = op_source ; break ; // xS: segment overrides case 0x1B : seg_override_en = 2 ; seg_override = stOpcode.extra ; if( rep_override_en ) { rep_override_en++ ; } break ; // DAA/DAS case 0x1C : i_w = 0 ; if( stOpcode.extra ) { // extra = 1 for DAS. DAA_DAS( -= , > ) ; } else { // extra = 0 for DAA. DAA_DAS( += , < ) ; } break ; // AAA/AAS case 0x1D : op_result = AAA_AAS( stOpcode.extra - 1 ) ; break ; // CBW case 0x1E : if( i_w ) { regs8[ REG_AH ] = -( 1 & *( int16_t * )&( regs8[ REG_AL ] ) >> 15 ) ; } else { regs8[ REG_AH ] = -( 1 & regs8[ REG_AL ] >> 7 ) ; } break ; // CWD case 0x1F : if( i_w ) { regs16[ REG_DX ] = -( 1 & *( int16_t * )&( regs16[ REG_AX ] ) >> 15 ) ; } else { regs16[ REG_DX ] = -( 1 & regs16[ REG_AX ] >> 7 ) ; } break ; // CALL FAR imm16:imm16 case 0x20 : i_w = 1 ; // PUSH regs16[ REG_CS ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_CS ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH reg_ip + 5. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&reg_ip + 5 ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; regs16[ REG_CS ] = i_data2 ; reg_ip = i_data0 ; break ; // PUSHF case 0x21 : make_flags() ; // PUSH scratch_uint. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // POPF case 0x22 : i_w = 1 ; regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&scratch_uint ; { uint16_t aux ; aux = regs16[ REG_SS ] ; aux *= 16 ; aux += ( uint16_t ) regs16[ REG_SP ] ; aux -= 2 ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ] ; } op_result = op_source ; *( uint16_t * )&scratch_uint = op_source ; set_flags( op_source ) ; break ; // SAHF case 0x23 : make_flags() ; set_flags( (scratch_uint & 0xFF00 ) + regs8[ REG_AH ] ) ; break ; // LAHF case 0x24 : make_flags() ; regs8[ REG_AH ] = scratch_uint ; break ; // LES|LDS reg, r/m case 0x25 : i_w = 1 ; i_d = 1 ; scratch2_uint = 4 * !i_mod ; if( i_mod < 3 ) { uint16_t localIndex ; uint16_t localAddr ; if( seg_override_en ) { localIndex = seg_override ; } else { localIndex = bios_table_lookup[ scratch2_uint + 3 ][ i_rm ] ; } localAddr = ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint + 1 ][ i_rm ] ] ; localAddr += ( uint16_t ) bios_table_lookup[ scratch2_uint + 2 ][ i_rm ] * i_data1 ; localAddr += ( uint16_t ) regs16[ bios_table_lookup[ scratch2_uint ][ i_rm ] ] ; rm_addr = 16 ; rm_addr *= regs16[ localIndex ] ; rm_addr += localAddr ; } else { rm_addr = ( REGS_BASE + ( 2 * i_rm ) ) ; } op_to_addr = rm_addr ; op_from_addr = ( REGS_BASE + ( 2 * i_reg ) ) ; if( i_d ) { scratch_uint = op_from_addr ; op_from_addr = rm_addr ; op_to_addr = scratch_uint ; } // Execute arithmetic/logic operations. op_source = *( uint16_t * )&mem[ op_from_addr ] ; op_result = op_source ; *( uint16_t * )&mem[ op_to_addr ] = op_source ; op_dest = *( uint16_t * )&mem[ REGS_BASE + stOpcode.extra ] ; op_source = *( uint16_t * )&mem[ rm_addr + 2 ] ; op_result = op_source ; *( uint16_t * )&mem[ REGS_BASE + stOpcode.extra ] = op_source ; break ; // INT 3 case 0x26 : reg_ip++ ; pc_interrupt( 3 ) ; break ; // INT imm8 case 0x27 : reg_ip += 2 ; pc_interrupt( ( uint8_t ) i_data0 ) ; break ; // INTO case 0x28 : reg_ip++ ; if( regs8[ FLAG_OF ] ) { pc_interrupt( 4 ) ; } break ; // AAM case 0x29 : i_data0 &= 0xFF ; if( i_data0 ) { regs8[ REG_AH ] = regs8[ REG_AL ] / i_data0 ; regs8[ REG_AL ] %= i_data0 ; op_result = regs8[ REG_AL ] ; } else // Divide by zero { pc_interrupt( 0 ) ; } break ; // AAD case 0x2A : i_w = 0 ; op_result = 0xFF & ( regs8[ REG_AL ] + i_data0 * regs8[ REG_AH ] ) ; regs16[ REG_AX ] = op_result ; break ; // SALC case 0x2B : regs8[ REG_AL ] = -regs8[ FLAG_CF ] ; break ; // XLAT case 0x2C : regs8[ REG_AL ] = mem[ 16 * regs16[seg_override_en ? seg_override : REG_DS] + (uint16_t)(regs8[ REG_AL ] + regs16[REG_BX]) ] ; break ; // CMC case 0x2D : regs8[ FLAG_CF ] ^= 1 ; break ; // CLC|STC|CLI|STI|CLD|STD case 0x2E : regs8[ stOpcode.extra / 2 ] = stOpcode.extra & 0x01 ; break ; // TEST AL/AX, immed case 0x2F : // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&regs8[ REG_AL ] ; op_source = *( uint16_t * )&i_data0 ; op_result = *( uint16_t * )&regs8[ REG_AL ] & op_source ; } else { op_dest = regs8[ REG_AL ] ; op_source = *( uint8_t * )&i_data0 ; op_result = regs8[ REG_AL ] & op_source ; } break ; // LOCK case 0x30 : break ; // HLT case 0x31 : break ; // Emulator-specific 0F xx opcodes case 0x32 : switch( ( int8_t ) i_data0 ) { // PUTCHAR_AL. case 0x00 : putchar( regs8[ 0 ] ) ; break ; // GET_RTC case 0x01 : { time_t clock_buf ; struct timeb ms_clock ; uint32_t addr ; time( &clock_buf ) ; ftime( &ms_clock ) ; // Convert segment:offset to linear address. addr = 16 ; addr *= regs16[ REG_ES ] ; addr += ( uint16_t ) regs16[ REG_BX ] ; memcpy( &mem[ addr ] , localtime( &clock_buf ) , sizeof( struct tm ) ) ; // Convert segment:offset to linear address. addr = 16 ; addr *= regs16[ REG_ES ] ; addr += ( uint16_t ) ( regs16[ REG_BX ] + 36 ) ; *( int16_t * )&mem[ addr ] = ms_clock.millitm ; } break ; // DISK_READ case 0x02 : // DISK_WRITE case 0x03 : { long seekRet ; seekRet = ~lseek( disk[ regs8[ REG_DL ] ] , *( uint32_t * )&regs16[ REG_BP ] << 9 , 0 ) ; if( seekRet ) { // Convert segment:offset to linear address. uint32_t addr ; addr = 16 ; addr *= regs16[ REG_ES ] ; addr += ( uint16_t ) regs16[ REG_BX ] ; if( ( ( int8_t ) i_data0 ) == 3 ) { regs8[ REG_AL ] = write( disk[ regs8[ REG_DL ] ] , ( mem + addr ) , regs16[ REG_AX ] ) ; } else { regs8[ REG_AL ] = read( disk[ regs8[ REG_DL ] ] , ( mem + addr ) , regs16[ REG_AX ] ) ; } } else { regs8[ REG_AL ] = 0 ; } } break ; } break ; // 80186, NEC V20: ENTER case 0x33 : // PUSH regs16[ REG_BP ]. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_BP ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; scratch_uint = regs16[ REG_SP ] ; i_data2 &= 0x00ff ; scratch2_uint = i_data2 ; if( scratch2_uint > 0 ) { while( scratch2_uint != 1 ) { scratch2_uint-- ; regs16[ REG_BP ] -= 2 ; // PUSH regs16[ REG_BP ]. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_BP ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } // PUSH scratch_uint. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; } regs16[ REG_BP ] = scratch_uint ; regs16[ REG_SP ] -= i_data0 ; break ; // 80186, NEC V20: LEAVE case 0x34 : regs16[ REG_SP ] = regs16[ REG_BP ] ; i_w = 1 ; regs16[ REG_SP ] += 2 ; // Execute arithmetic/logic operations. { uint32_t addr ; op_dest = *( uint16_t * )&regs16[ REG_BP ] ; addr = 16 ; addr *= regs16[ REG_SS ] ; addr += ( uint16_t ) ( regs16[ REG_SP ] - 2 ) ; op_source = *( uint16_t * )&mem[ addr ] ; op_result = op_source ; *( uint16_t * )&regs16[ REG_BP ] = op_source ; } break ; // 80186, NEC V20: PUSHA case 0x35 : // PUSH AX, PUSH CX, PUSH DX, PUSH BX, PUSH SP, PUSH BP, PUSH SI, PUSH DI i_w = 1 ; // PUSH regs16[ REG_AX ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_AX ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_CX ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_CX ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_DX ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_DX ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_BX ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_BX ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; scratch_uint = regs16[ REG_SP ] ; // PUSH scratch_uint. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&scratch_uint ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_BP ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_BP ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_SI ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_SI ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; // PUSH regs16[ REG_DI ]. op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&regs16[ REG_DI ] ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // 80186, NEC V20: POPA case 0x63 : // POP DI, POP SI, POP BP, ADD SP,2, POP BX, POP DX, POP CX, POP AX i_w = 1 ; // POP regs16[ REG_DI ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_DI ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_DI ] = op_source ; // POP regs16[ REG_SI ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_SI ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_SI ] = op_source ; // POP regs16[ REG_BP ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_BP ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_BP ] = op_source ; regs16[ REG_SP ] += 2 ; // POP regs16[ REG_BX ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_BX ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_BX ] = op_source ; // POP regs16[ REG_DX ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_DX ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_DX ] = op_source ; // POP regs16[ REG_CX ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_CX ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_CX ] = op_source ; // POP regs16[ REG_AX ]. regs16[ REG_SP ] += 2 ; op_dest = *( uint16_t * )&regs16[ REG_AX ] ; op_source = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( -2+ regs16[ REG_SP ] ) ] ; op_result = *( uint16_t * )&regs16[ REG_AX ] = op_source ; break ; // 80186: BOUND case 0x37 : // Not implemented. Incompatible with PC/XT hardware. printf( "BOUND\n" ) ; break ; // 80186, NEC V20: PUSH imm16 case 0x38 : // PUSH i_data0. i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&i_data0 ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // 80186, NEC V20: PUSH imm8 case 0x39 : // PUSH ( i_data0 & 0x00FF ) i_w = 1 ; op_dest = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] ; op_source = *( uint16_t * )&i_data0 & 0x00FF ; op_result = *( uint16_t * )&mem[ 16 * regs16[ REG_SS ] + ( uint16_t ) ( --regs16[ REG_SP ] ) ] = op_source ; break ; // 80186 IMUL case 0x3A : // Not implemented. printf( "IMUL at %04X:%04X\n" , regs16[ REG_CS ] , reg_ip ) ; break ; // 80186: INSB INSW case 0x3B : // Loads data from port to the destination ES:DI. // DI is adjusted by the size of the operand and increased if the // Direction Flag is cleared and decreased if the Direction Flag is set. scratch2_uint = regs16[ REG_DX ] ; scratch_uint = ( rep_override_en ) ? ( regs16[REG_CX] ) : ( 1 ) ; while( scratch_uint ) { uint32_t addr ; io_ports[ scratch2_uint ] = Interface.ReadPort( scratch2_uint ) ; if( i_w ) { io_ports[ scratch2_uint + 1 ] = Interface.ReadPort( scratch2_uint + 1 ) ; } // Convert segment:offset to linear address. addr = 16 ; addr *= regs16[ REG_ES ] ; addr += ( uint16_t ) regs16[ REG_DI ] ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&mem[ addr ] ; op_source = *( uint16_t * )&io_ports[ scratch_uint ] ; op_result = *( uint16_t * )&mem[ addr ] = op_source ; } else { op_dest = mem[ addr ] ; op_source = *( uint8_t * )&io_ports[ scratch_uint ] ; op_result = mem[ addr ] = op_source ; } regs16[ REG_DI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; scratch_uint-- ; } if( rep_override_en ) { regs16[ REG_CX ] = 0 ; } break ; // 80186: OUTSB OUTSW case 0x3C : // Transfers a byte or word "src" to the hardware port specified in DX. // The "src" is located at DS:SI and SI is incremented or decremented // by the size dictated by the instruction format. // When the Direction Flag is set SI is decremented, when clear, SI is // incremented. scratch2_uint = regs16[ REG_DX ] ; scratch_uint = ( rep_override_en ) ? ( regs16[ REG_CX ] ) : ( 1 ) ; while( scratch_uint ) { uint32_t addr ; // Convert segment:offset to linear address. addr = 16 ; addr *= regs16[ REG_DS ] ; addr += ( uint16_t ) regs16[ REG_SI ] ; // Execute arithmetic/logic operations. if( i_w ) { op_dest = *( uint16_t * )&io_ports[ scratch2_uint ] ; op_source = *( uint16_t * )&mem[ addr ] ; op_result = *( uint16_t * )&io_ports[ scratch2_uint ] = op_source ; } else { op_dest = io_ports[ scratch2_uint ] ; op_source = *( uint8_t * )&mem[ addr ] ; op_result = io_ports[ scratch2_uint ] = op_source ; } Interface.WritePort( scratch2_uint , io_ports[ scratch2_uint ] ) ; if( i_w ) { Interface.WritePort( scratch2_uint + 1 , io_ports[ scratch2_uint + 1 ] ) ; } regs16[ REG_SI ] -= ( 2 * regs8[ FLAG_DF ] - 1 ) * ( i_w + 1 ) ; scratch_uint-- ; } if( rep_override_en ) { regs16[ REG_CX ] = 0 ; } break ; // 8087 MATH Coprocessor case 0x45 : printf( "8087 coprocessor instruction: 0x%02X\n" , stOpcode.raw_opcode_id ) ; ExitEmulation = true ; break ; // 80286+ case 0x46 : printf( "80286+ only op code: 0x%02X at %04X:%04X\n" , stOpcode.raw_opcode_id , regs16[ REG_CS ] , reg_ip ) ; break ; // 80386+ case 0x47 : printf( "80386+ only op code: 0x%02X at %04X:%04X\n" , stOpcode.raw_opcode_id , regs16[ REG_CS ] , reg_ip ) ; break ; // BAD OP CODE case 0x48 : printf( "Bad op code: %02x at %04X:%04X\n" , stOpcode.raw_opcode_id , regs16[ REG_CS ] , reg_ip ) ; break ; default : printf( "Unknown opcode %02Xh\n" , stOpcode.raw_opcode_id ) ; break ; } // Increment instruction pointer by computed instruction length. Tables in the BIOS binary // help us here. reg_ip += ( i_mod * ( i_mod != 3 ) + 2 * ( !i_mod && i_rm == 6 ) ) * stOpcode.i_mod_size ; reg_ip += bios_table_lookup[ TABLE_BASE_INST_SIZE ][ stOpcode.raw_opcode_id ] ; reg_ip += bios_table_lookup[ TABLE_I_W_SIZE ][ stOpcode.raw_opcode_id ] * ( i_w + 1 ) ; // If instruction needs to update SF, ZF and PF, set them as appropriate if( stOpcode.set_flags_type & FLAGS_UPDATE_SZP ) { // Returns sign bit of an 8-bit or 16-bit operand regs8[ FLAG_SF ] = ( 1 & ( ( i_w ) ? *( int16_t * )&( op_result ) : ( op_result ) ) >> ( 8 * ( i_w + 1 ) - 1 ) ) ; regs8[ FLAG_ZF ] = !op_result ; regs8[ FLAG_PF ] = bios_table_lookup[ TABLE_PARITY_FLAG ][ ( uint8_t ) op_result ] ; // If instruction is an arithmetic or logic operation, also set AF/OF/CF as appropriate. if( stOpcode.set_flags_type & FLAGS_UPDATE_AO_ARITH ) { set_AF_OF_arith() ; } if( stOpcode.set_flags_type & FLAGS_UPDATE_OC_LOGIC ) { set_CF( 0 ) ; set_OF( 0 ) ; } } regs16[ REG_IP ] = reg_ip ; // Update the interface module if( Interface.TimerTick( 4 ) ) { if( Interface.ExitEmulation() ) { ExitEmulation = true ; } else { if( Interface.FDChanged() ) { close( disk[ 1 ] ) ; disk[ 1 ] = open( Interface.GetFDImageFilename() , O_BINARY | O_NOINHERIT | O_RDWR ) ; } if( Interface.Reset() ) { Reset() ; } } } // Application has set trap flag, so fire INT 1 if( trap_flag ) { pc_interrupt( 1 ) ; } trap_flag = regs8[ FLAG_TF ] ; // Check for interrupts triggered by system interfaces int IntNo ; static int InstrSinceInt8 = 0 ; InstrSinceInt8++ ; if( !seg_override_en && !rep_override_en && regs8[ FLAG_IF ] && !regs8[ FLAG_TF ] && Interface.IntPending( IntNo ) ) { if( ( IntNo == 8 ) && ( InstrSinceInt8 < 300 ) ) { //printf("*** Int8 after %d instructions\n", InstrSinceInt8); } else { if( IntNo == 8 ) { InstrSinceInt8 = 0 ; } pc_interrupt( IntNo ) ; regs16[ REG_IP ] = reg_ip ; } } } // for each instruction Interface.Cleanup() ; return( 0 ) ; }
29.175361
320
0.488264
francescosacco
34e769cb264e0dc3f64ca4d707bf0d9bdaf23913
25,834
cpp
C++
test/instruction/instruction.cpp
poundflag/MOS-6502-Emulator-Base
987a6c4e2be137cac751d5575860573e8f29e452
[ "MIT" ]
null
null
null
test/instruction/instruction.cpp
poundflag/MOS-6502-Emulator-Base
987a6c4e2be137cac751d5575860573e8f29e452
[ "MIT" ]
null
null
null
test/instruction/instruction.cpp
poundflag/MOS-6502-Emulator-Base
987a6c4e2be137cac751d5575860573e8f29e452
[ "MIT" ]
null
null
null
#include "../../src/instruction/instruction.h" #include "../../src/alu.h" #include "../../src/bus/buscontroller.h" #include "../../src/bus/model/busdevice.h" #include "../../src/bus/model/ram.h" #include "../../src/register/model/stack.h" #include "../../src/register/registercontroller.h" #include <gtest/gtest.h> class InstructionTest : public ::testing::Test { protected: BusController busController = BusController(); Ram *ram = new Ram(0x10); Ram *stackRam = new Ram(0x100); RegisterController registerController = RegisterController(busController); ALU alu = ALU(registerController); Instruction instr = Instruction(registerController, busController, alu); void SetUp() { ram->addAddress({0x0, 0x10}); busController.addDevice(ram); stackRam->addAddress({0x0100, 0x01FF}); busController.addDevice(stackRam); } }; TEST_F(InstructionTest, LDA) { instr.LDA(0x46); GTEST_ASSERT_EQ(0x46, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, LDAWithZeroFlagTrigger) { instr.LDA(0x0); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, LDAWithNegativeFlagTrigger) { instr.LDA(0x80); GTEST_ASSERT_EQ(0x80, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, LDX) { instr.LDX(0x46); GTEST_ASSERT_EQ(0x46, registerController.getRegisterValue(X)); } TEST_F(InstructionTest, LDXWithZeroFlagTrigger) { instr.LDX(0x0); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, LDXWithNegativeFlagTrigger) { instr.LDX(0x80); GTEST_ASSERT_EQ(0x80, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, LDY) { instr.LDY(0x46); GTEST_ASSERT_EQ(0x46, registerController.getRegisterValue(Y)); } TEST_F(InstructionTest, LDYWithZeroFlagTrigger) { instr.LDY(0x0); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, LDYWithNegativeFlagTrigger) { instr.LDY(0x80); GTEST_ASSERT_EQ(0x80, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, STA) { instr.LDA(0x32); instr.STA(0x0); GTEST_ASSERT_EQ(0x32, busController.read(0)); } TEST_F(InstructionTest, STAWithOutOfRangeAddress) { instr.LDA(0x35); instr.STA(0x1000); GTEST_ASSERT_EQ(0x0, busController.read(0x1000)); } TEST_F(InstructionTest, STX) { instr.LDX(0x32); instr.STX(0x0); GTEST_ASSERT_EQ(0x32, busController.read(0)); } TEST_F(InstructionTest, STXWithOutOfRangeAddress) { instr.LDX(0x35); instr.STX(0x1000); GTEST_ASSERT_EQ(0x0, busController.read(0x1000)); } TEST_F(InstructionTest, STY) { instr.LDY(0x32); instr.STY(0x0); GTEST_ASSERT_EQ(0x32, busController.read(0)); } TEST_F(InstructionTest, STYWithOutOfRangeAddress) { instr.LDY(0x35); instr.STY(0x1000); GTEST_ASSERT_EQ(0x0, busController.read(0x1000)); } TEST_F(InstructionTest, CLC) { registerController.getStatusRegister()->setStatus(Carry, true); instr.CLC(); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, CLD) { registerController.getStatusRegister()->setStatus(DecimalMode, true); instr.CLD(); GTEST_ASSERT_EQ( false, registerController.getStatusRegister()->getStatus(DecimalMode)); } TEST_F(InstructionTest, CLI) { registerController.getStatusRegister()->setStatus(Interrupt, true); instr.CLI(); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Interrupt)); } TEST_F(InstructionTest, CLV) { registerController.getStatusRegister()->setStatus(Overflow, true); instr.CLV(); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Overflow)); } TEST_F(InstructionTest, SEC) { registerController.getStatusRegister()->setStatus(Carry, false); instr.SEC(); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, SED) { registerController.getStatusRegister()->setStatus(DecimalMode, false); instr.SED(); GTEST_ASSERT_EQ( true, registerController.getStatusRegister()->getStatus(DecimalMode)); } TEST_F(InstructionTest, SEI) { registerController.getStatusRegister()->setStatus(Interrupt, false); instr.SEI(); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Interrupt)); } TEST_F(InstructionTest, DECWithNotFlagChanged) { busController.write(1, 0x23); instr.DEC(1); GTEST_ASSERT_EQ(0x22, busController.read(1)); } TEST_F(InstructionTest, DECZeroFlagAffected) { busController.write(1, 0x1); instr.DEC(1); GTEST_ASSERT_EQ(0x0, busController.read(1)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, DECNegativeFlagAffected) { busController.write(1, 0x0); instr.DEC(1); GTEST_ASSERT_EQ(0xFF, busController.read(1)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, DEXWithNotFlagChanged) { registerController.setRegisterValue(X, 0x99); instr.DEX(); GTEST_ASSERT_EQ(0x98, registerController.getRegisterValue(X)); } TEST_F(InstructionTest, DEXZeroFlagAffected) { registerController.setRegisterValue(X, 0x1); instr.DEX(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, DEXNegativeFlagAffected) { registerController.setRegisterValue(X, 0xFF); instr.DEX(); GTEST_ASSERT_EQ(0xFE, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, DEYWithNotFlagChanged) { registerController.setRegisterValue(Y, 0x99); instr.DEY(); GTEST_ASSERT_EQ(0x98, registerController.getRegisterValue(Y)); } TEST_F(InstructionTest, DEYZeroFlagAffected) { registerController.setRegisterValue(Y, 0x1); instr.DEY(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, DEYNegativeFlagAffected) { registerController.setRegisterValue(Y, 0xFF); instr.DEY(); GTEST_ASSERT_EQ(0xFE, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, INCWithNotFlagChanged) { busController.write(1, 0x23); instr.INC(1); GTEST_ASSERT_EQ(0x24, busController.read(1)); } TEST_F(InstructionTest, INCZeroFlagAffected) { busController.write(1, 0xFF); instr.INC(1); GTEST_ASSERT_EQ(0x0, busController.read(1)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, INCNegativeFlagAffected) { busController.write(1, 0xFD); instr.INC(1); GTEST_ASSERT_EQ(0xFE, busController.read(1)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, INXWithNotFlagChanged) { registerController.setRegisterValue(X, 0x98); instr.INX(); GTEST_ASSERT_EQ(0x99, registerController.getRegisterValue(X)); } TEST_F(InstructionTest, INXZeroFlagAffected) { registerController.setRegisterValue(X, 0xFF); instr.INX(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, INXNegativeFlagAffected) { registerController.setRegisterValue(X, 0xFE); instr.INX(); GTEST_ASSERT_EQ(0xFF, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, INYWithNotFlagChanged) { registerController.setRegisterValue(Y, 0x98); instr.INY(); GTEST_ASSERT_EQ(0x99, registerController.getRegisterValue(Y)); } TEST_F(InstructionTest, INYZeroFlagAffected) { registerController.setRegisterValue(Y, 0xFF); instr.INY(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, INYNegativeFlagAffected) { registerController.setRegisterValue(Y, 0xFE); instr.INY(); GTEST_ASSERT_EQ(0xFF, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, ANDWithNotFlagChanged) { registerController.setRegisterValue(A, 0x3); busController.write(1, 0x5); instr.AND(1); GTEST_ASSERT_EQ(0x1, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, ANDZeroFlagAffected) { registerController.setRegisterValue(A, 0x0); busController.write(1, 0x5); instr.AND(1); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, ANDNegativeFlagAffected) { registerController.setRegisterValue(A, 0xFE); busController.write(1, 0xFF); instr.AND(1); GTEST_ASSERT_EQ(0xFE, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, EORWithNotFlagChanged) { registerController.setRegisterValue(A, 0x3); instr.EOR(5); GTEST_ASSERT_EQ(0x6, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, EORZeroFlagAffected) { registerController.setRegisterValue(A, 0x0); instr.EOR(0); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, EORNegativeFlagAffected) { registerController.setRegisterValue(A, 0xF2); instr.EOR(2); GTEST_ASSERT_EQ(0xF0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, ORAWithNotFlagChanged) { registerController.setRegisterValue(A, 0x3); busController.write(1, 0x5); instr.ORA(1); GTEST_ASSERT_EQ(0x7, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, ORAZeroFlagAffected) { registerController.setRegisterValue(A, 0x0); busController.write(1, 0x0); instr.ORA(1); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, ORANegativeFlagAffected) { registerController.setRegisterValue(A, 0xF2); busController.write(1, 0x2); instr.ORA(1); GTEST_ASSERT_EQ(0xF2, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, TAXWithNotFlagChanged) { registerController.setRegisterValue(A, 0x3); registerController.setRegisterValue(X, 0x5); instr.TAX(); GTEST_ASSERT_EQ(0x3, registerController.getRegisterValue(X)); } TEST_F(InstructionTest, TAXZeroFlagAffected) { registerController.setRegisterValue(A, 0x0); registerController.setRegisterValue(X, 0x5); instr.TAX(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, TAXNegativeFlagAffected) { registerController.setRegisterValue(A, 0xF3); registerController.setRegisterValue(X, 0x5); instr.TAX(); GTEST_ASSERT_EQ(0xF3, registerController.getRegisterValue(X)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, TAYWithNotFlagChanged) { registerController.setRegisterValue(A, 0x3); registerController.setRegisterValue(Y, 0x5); instr.TAY(); GTEST_ASSERT_EQ(0x3, registerController.getRegisterValue(Y)); } TEST_F(InstructionTest, TAYZeroFlagAffected) { registerController.setRegisterValue(A, 0x0); registerController.setRegisterValue(Y, 0x5); instr.TAY(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, TAYNegativeFlagAffected) { registerController.setRegisterValue(A, 0xF3); registerController.setRegisterValue(Y, 0x5); instr.TAY(); GTEST_ASSERT_EQ(0xF3, registerController.getRegisterValue(Y)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, TXAWithNotFlagChanged) { registerController.setRegisterValue(X, 0x3); registerController.setRegisterValue(A, 0x5); instr.TXA(); GTEST_ASSERT_EQ(0x3, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, TXAZeroFlagAffected) { registerController.setRegisterValue(X, 0x0); registerController.setRegisterValue(A, 0x5); instr.TXA(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, TXANegativeFlagAffected) { registerController.setRegisterValue(X, 0xF3); registerController.setRegisterValue(A, 0x5); instr.TXA(); GTEST_ASSERT_EQ(0xF3, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, TYAWithNotFlagChanged) { registerController.setRegisterValue(Y, 0x3); registerController.setRegisterValue(A, 0x5); instr.TYA(); GTEST_ASSERT_EQ(0x3, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, TYAZeroFlagAffected) { registerController.setRegisterValue(Y, 0x0); registerController.setRegisterValue(A, 0x5); instr.TYA(); GTEST_ASSERT_EQ(0x0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, TYANegativeFlagAffected) { registerController.setRegisterValue(Y, 0xF3); registerController.setRegisterValue(A, 0x5); instr.TYA(); GTEST_ASSERT_EQ(0xF3, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, TSXWithNotFlagChanged) { registerController.getStack()->push(0x10); registerController.setRegisterValue(X, 0x5); instr.TSX(); GTEST_ASSERT_EQ(0xFE, registerController.getRegisterValue(X)); } TEST_F(InstructionTest, TXSWithNotFlagChanged) { registerController.getStack()->push(0x10); registerController.setRegisterValue(X, 0x5); instr.TXS(); GTEST_ASSERT_EQ(0x0, registerController.getStack()->pull()); } TEST_F(InstructionTest, TXSZeroFlagAffected) { registerController.getStack()->push(0x5); registerController.getStack()->push(0x5); registerController.setRegisterValue(X, 0x0); instr.TXS(); GTEST_ASSERT_EQ(0x0, registerController.getStack()->pull()); } TEST_F(InstructionTest, TXSNegativeFlagAffected) { registerController.getStack()->push(0x5); registerController.setRegisterValue(X, 0xF3); instr.TXS(); GTEST_ASSERT_EQ(0xF3, registerController.getStack()->getValue()); } TEST_F(InstructionTest, PHA) { registerController.setRegisterValue(A, 0x44); instr.PHA(); GTEST_ASSERT_EQ(0x44, registerController.getStack()->pull()); } TEST_F(InstructionTest, PHP) { registerController.getStatusRegister()->Register::setValue(0x20); instr.PHP(); GTEST_ASSERT_EQ(0x30, registerController.getStack()->pull()); } TEST_F(InstructionTest, PLA) { registerController.getStack()->push(0x34); instr.PLA(); GTEST_ASSERT_EQ(0x34, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, PLP) { registerController.getStack()->push(0x34); instr.PLP(); GTEST_ASSERT_EQ(0x34, registerController.getStatusRegister()->getValue()); } TEST_F(InstructionTest, ADCWithSimpleNumbers) { registerController.setRegisterValue(A, 0x3); instr.ADC(0x3); GTEST_ASSERT_EQ(0x6, registerController.getRegisterValue(A)); } TEST_F(InstructionTest, ADCWithSimpleCarryFlagAndOverflow) { registerController.setRegisterValue(A, 0xFF); instr.ADC(0xFF); GTEST_ASSERT_EQ(0xFE, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ADCWithSimpleCarryFlagAndOverflow2) { registerController.setRegisterValue(A, 0xFA); instr.ADC(0x0A); GTEST_ASSERT_EQ(0x04, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ADCWithCarryFlagTrue) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0x2); instr.ADC(0x02); GTEST_ASSERT_EQ(0x05, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ADCWithCarryFlagTrueAndOverflow) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0xFE); instr.ADC(0x0FE); GTEST_ASSERT_EQ(0xFD, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ADCWithCarryFlagTrueAndOverflow2) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0xFF); instr.ADC(0x0FF); GTEST_ASSERT_EQ(0xFF, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ASLMemorySimpleShiftWithTheCarryBeingZeroAndNothingElseSet) { busController.write(0x2, 2); instr.ASL_Memory(0x2); GTEST_ASSERT_EQ(0x4, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ASLMemorySimpleShiftWithTheCarryBeingSetAndZero) { busController.write(0x2, 0x80); instr.ASL_Memory(0x2); GTEST_ASSERT_EQ(0x00, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, ASLMemorySimpleShiftWithNegativeBeingSet) { busController.write(0x2, 0x70); instr.ASL_Memory(0x2); GTEST_ASSERT_EQ(0xE0, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, LSRMemorySimpleShiftWithTheCarryBeingZeroAndNothingElseSet) { busController.write(0x2, 2); instr.LSR_Memory(0x2); GTEST_ASSERT_EQ(0x1, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, LSRMemorySimpleShiftWithTheCarryBeingSetAndZero) { busController.write(0x2, 0x1); instr.LSR_Memory(0x2); GTEST_ASSERT_EQ(0x00, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); } TEST_F(InstructionTest, LSRMemorySimpleShiftWithNegativeBeingZero) { registerController.getStatusRegister()->setStatus(Carry, true); busController.write(0x2, 0xF9); instr.LSR_Memory(0x2); GTEST_ASSERT_EQ(0x7C, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, ROLMemoryWithTheCarryOn) { registerController.getStatusRegister()->setStatus(Carry, true); busController.write(0x2, 0x4); instr.ROL_Memory(0x2); GTEST_ASSERT_EQ(0x9, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ROLMemoryWithTheCarryOff) { registerController.getStatusRegister()->setStatus(Carry, false); busController.write(0x2, 0x4); instr.ROL_Memory(0x2); GTEST_ASSERT_EQ(0x8, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, ROLMemoryWithTheCarryOnAndAnOverflow) { registerController.getStatusRegister()->setStatus(Carry, true); busController.write(0x2, 0xFF); instr.ROL_Memory(0x2); GTEST_ASSERT_EQ(0xFF, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, RORMemoryWithTheCarryOn) { registerController.getStatusRegister()->setStatus(Carry, true); busController.write(0x2, 0x2); instr.ROR_Memory(0x2); GTEST_ASSERT_EQ(0x81, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, RORMemoryWithTheCarryOff) { registerController.getStatusRegister()->setStatus(Carry, false); busController.write(0x2, 0x2); instr.ROR_Memory(0x2); GTEST_ASSERT_EQ(0x1, busController.read(0x2)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, RORMemoryWithTheCarryOnAndAnOverflow) { registerController.getStatusRegister()->setStatus(Carry, true); busController.write(0x2, 0xFF); instr.ROR_Memory(0x2); GTEST_ASSERT_EQ(0xFF, busController.read(0x2)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, SBCWithSimpleNumbersAndCarryOff) { registerController.setRegisterValue(A, 0x6); instr.SBC(0x4); GTEST_ASSERT_EQ(0x1, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, SBCWithSimpleNumbersAndCarryOn) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0x6); instr.SBC(0x4); GTEST_ASSERT_EQ(0x2, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, SBCWithSimpleCarryFlagAndOverflow) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0xD0); instr.SBC(0x70); GTEST_ASSERT_EQ(0x60, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Overflow)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Carry)); } TEST_F(InstructionTest, SBCWithSimpleCarryFlagAndOverflow2) { registerController.getStatusRegister()->setStatus(Carry, true); registerController.setRegisterValue(A, 0x50); instr.SBC(0xB0); GTEST_ASSERT_EQ(0xA0, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Carry)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Overflow)); } TEST_F(InstructionTest, JMP) { registerController.setProgramCounter(0x1234); instr.JMP(0x4321); GTEST_ASSERT_EQ(0x4320, registerController.getProgramCounter()); } // TODO Add branching tests!!! // TODO CMP // TODO JSR TEST_F(InstructionTest, BITWithZeroSet) { busController.write(2, 5); registerController.setRegisterValue(A, 0xA); instr.BIT(2); GTEST_ASSERT_EQ(0xA, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Zero)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Negative)); } TEST_F(InstructionTest, BITWithNegativeAndOverflowSet) { busController.write(2, 0xFF); registerController.setRegisterValue(A, 0xF3); instr.BIT(2); GTEST_ASSERT_EQ(0xF3, registerController.getRegisterValue(A)); GTEST_ASSERT_EQ(false, registerController.getStatusRegister()->getStatus(Zero)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Negative)); GTEST_ASSERT_EQ(true, registerController.getStatusRegister()->getStatus(Overflow)); }
33.902887
80
0.750639
poundflag
34eb2af91a03deafdaa525823baab2ccb0cd85a0
366
cpp
C++
06_algorithms/10_other_algo/05_find.cpp
Gmrakari/STL
1fc90b1c573a140efa695efd5c55e80ad03b7595
[ "MIT" ]
null
null
null
06_algorithms/10_other_algo/05_find.cpp
Gmrakari/STL
1fc90b1c573a140efa695efd5c55e80ad03b7595
[ "MIT" ]
null
null
null
06_algorithms/10_other_algo/05_find.cpp
Gmrakari/STL
1fc90b1c573a140efa695efd5c55e80ad03b7595
[ "MIT" ]
null
null
null
/* * Date:2021-08-20 15:25 * filename:05_find.cpp * */ /* * 根据equality操作符,循序查找[first, last)内的所有元素,找出第一个匹配 * "等同(equality)条件"者,如果找到,就返回一个Inputterator指向该元素, * 否则返回迭代器last * */ template <class Inputerator, class T> Inputerator find(Inputerator first, Inputerator last, const T& value) { while (first != last && *first != value) ++first; return first; }
16.636364
71
0.68306
Gmrakari
34f299e15530bb73ed0cf27e3e1944d2d397f323
947
cpp
C++
605PlaceFlowers.cpp
Bowen-Ding/LeetcodeByCPP
6d043d870631050d9a41e50caa4e9274a357ddca
[ "Apache-2.0" ]
1
2022-01-11T01:32:16.000Z
2022-01-11T01:32:16.000Z
605PlaceFlowers.cpp
Bowen-Ding/LeetcodeByCPP
6d043d870631050d9a41e50caa4e9274a357ddca
[ "Apache-2.0" ]
null
null
null
605PlaceFlowers.cpp
Bowen-Ding/LeetcodeByCPP
6d043d870631050d9a41e50caa4e9274a357ddca
[ "Apache-2.0" ]
null
null
null
#include <bits//stdc++.h> #include <vector> #include <iostream> using namespace std; /* 题目描述: 假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 给你一个整数数组  flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false。 示例 1: 输入:flowerbed = [1,0,0,0,1], n = 1 输出:true 示例 2: 输入:flowerbed = [1,0,0,0,1], n = 2 输出:false */ class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int s = flowerbed.size(), prev = -1, cnt = 0; for (int i = 0; i < s; ++i) { if (flowerbed[i] == 1) { if (prev < 0) { cnt += i / 2; } else { cnt += (i - prev - 2) / 2; } prev = i; } } if (prev < 0) { cnt += (s + 1) / 2; } else { cnt += (s - prev - 1) / 2; } return cnt >= n; } };
22.547619
113
0.463569
Bowen-Ding
34f2de1a5f094e95b806b802a71cf59f615283e4
1,898
cpp
C++
mainwindow.cpp
SqYtCO/Stopwatch
5347f31d830db72e883508bfbb84a7cbc5591fe6
[ "MIT" ]
null
null
null
mainwindow.cpp
SqYtCO/Stopwatch
5347f31d830db72e883508bfbb84a7cbc5591fe6
[ "MIT" ]
null
null
null
mainwindow.cpp
SqYtCO/Stopwatch
5347f31d830db72e883508bfbb84a7cbc5591fe6
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include <qdebug.h> MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { setupGUI(); // on startbutton-click: if stopwatch is not running, start it QObject::connect(&startbutton, &QPushButton::clicked, [this]() { if(!timewidget.isRunning()) timewidget.start(); }); startaction.setShortcuts( { QKeySequence(Qt::CTRL + Qt::Key_S), QKeySequence(Qt::Key_Space) } ); this->addAction(&startaction); QObject::connect(&startaction, &QAction::triggered, [this]() { if(!timewidget.isRunning()) timewidget.start(); }); // on stopbutton-click: if stopwatch is running, stop it QObject::connect(&stopbutton, &QPushButton::clicked, [this]() { if(timewidget.isRunning()) timewidget.stop(); }); stopaction.setShortcuts( { QKeySequence(Qt::CTRL + Qt::Key_P), QKeySequence(Qt::Key_Return) } ); this->addAction(&stopaction); QObject::connect(&stopaction, &QAction::triggered, [this]() { if(timewidget.isRunning()) timewidget.stop(); }); // on resetbutton-click: reset stopwatch QObject::connect(&resetbutton, &QPushButton::clicked, &timewidget, &TimeWidget::reset); resetaction.setShortcuts( { QKeySequence(Qt::CTRL + Qt::Key_R), QKeySequence(Qt::Key_Escape) } ); this->addAction(&resetaction); QObject::connect(&resetaction, &QAction::triggered, &timewidget, &TimeWidget::reset); } void MainWindow::setupGUI() { QWidget* central = new QWidget(this); // setup buttons startbutton.setText(tr("Start (Space)")); startbutton.setToolTip(tr("CTRL+S")); stopbutton.setText(tr("Stop (Return)")); stopbutton.setToolTip(tr("CTRL+P")); resetbutton.setText(tr("Reset (Esc)")); resetbutton.setToolTip(tr("CTRL+R")); // setup layout grid.addWidget(&startbutton, 0, 0); grid.addWidget(&stopbutton, 0, 1); grid.addWidget(&resetbutton, 0, 2); grid.addWidget(&timewidget, 1, 0, 1, 3); // set layout central->setLayout(&grid); this->setCentralWidget(central); }
40.382979
117
0.716017
SqYtCO
34f99f45e716d3c7121353b509b86300845ff493
1,042
cpp
C++
BT-Clipper/Source/DSP/InitPostTone.cpp
landonviator/BT-Clipper
4b6d633e84eadc24df346b21cc8b4d7724fb3770
[ "MIT" ]
null
null
null
BT-Clipper/Source/DSP/InitPostTone.cpp
landonviator/BT-Clipper
4b6d633e84eadc24df346b21cc8b4d7724fb3770
[ "MIT" ]
null
null
null
BT-Clipper/Source/DSP/InitPostTone.cpp
landonviator/BT-Clipper
4b6d633e84eadc24df346b21cc8b4d7724fb3770
[ "MIT" ]
null
null
null
/* ============================================================================== InitPostTone.cpp Created: 23 Jan 2022 7:02:37pm Author: Landon Viator ============================================================================== */ #include "../PluginProcessor.h" void BTClipperAudioProcessor::initPostTone() { postToneModule.setParameter(LV_SVFilter::ParameterId::kType, LV_SVFilter::FilterType::kBandShelf); postToneModule.setParameter(LV_SVFilter::ParameterId::kCutoff, *treeState.getRawParameterValue(postFreqID)); postToneModule.setParameter(LV_SVFilter::ParameterId::kGain, *treeState.getRawParameterValue(postGainID)); auto newQ = juce::jmap(static_cast<float>(*treeState.getRawParameterValue(postQID)), 0.0f, 100.0f, 0.95f, 0.05f); postToneModule.setParameter(LV_SVFilter::ParameterId::kQ, newQ); postToneModule.setParameter(LV_SVFilter::ParameterId::kBypass, *treeState.getRawParameterValue(postPowerID)); postToneModule.setParameter(LV_SVFilter::ParameterId::kClipOutput, true); }
45.304348
117
0.65643
landonviator
5a55eca2957ac308a5b9dd9e7d566407db3d9e55
854
cpp
C++
LeetCode/c++/88_Merge Sorted Array.cpp
Weak-Chicken/Algo_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
1
2018-02-08T23:50:19.000Z
2018-02-08T23:50:19.000Z
LeetCode/c++/88_Merge Sorted Array.cpp
Weak-Chicken/Algo_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
1
2018-04-11T19:08:22.000Z
2018-04-12T19:24:57.000Z
LeetCode/c++/88_Merge Sorted Array.cpp
Weak-Chicken/Cpp_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
null
null
null
class Solution { public: void insert_one_element(vector<int>& nums, int number, int position, int m) { for (int i = m - 1; i >= position; i--) { nums[i + 1] = nums[i]; } nums[position] = number; }; void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if (m == 0) { nums1 = nums2; } else { if (n != 0) { int nums1_pointer = 0; for (int i = 0; i < n; i++) { while ((nums1[nums1_pointer] < nums2[i]) && nums1_pointer < m) nums1_pointer++; insert_one_element(nums1, nums2[i], nums1_pointer, m); m++; } } } } };
24.4
99
0.375878
Weak-Chicken
5a568d7e6075400e599616a86fdfd006648edc71
682
cpp
C++
shell/parser.cpp
amanudde1999/os-concepts
4e3f5d9c2e898e5cf247fea89bb1e845730c1ca5
[ "MIT" ]
null
null
null
shell/parser.cpp
amanudde1999/os-concepts
4e3f5d9c2e898e5cf247fea89bb1e845730c1ca5
[ "MIT" ]
null
null
null
shell/parser.cpp
amanudde1999/os-concepts
4e3f5d9c2e898e5cf247fea89bb1e845730c1ca5
[ "MIT" ]
null
null
null
/** Assignment 1: Processes Name: Amro Amanuddein StudentID: 1572498 Course: CMPUT 379 Fall 2021 */ #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include "parser.h" using namespace std; cmds parse(string cmd_string){ cmds cmd_input; boost::split(cmd_input.cmd_vector, cmd_string, boost::is_any_of(" ")); // Check if there's >, < or & cmd_input.ampersand = cmd_input.cmd_vector[cmd_input.cmd_vector.size()-1] == "&"; cmd_input.greater = cmd_string.find('>') != string::npos; cmd_input.less = cmd_string.find('<') != string::npos; if (cmd_input.ampersand){ cmd_input.cmd_vector.pop_back(); } return cmd_input; }
24.357143
82
0.709677
amanudde1999
5a606d4fc145f0384b71f5c86ba2276e87c363a5
1,524
hpp
C++
include/codegen/include/System/EmptyArray_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/EmptyArray_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/EmptyArray_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: System namespace System { // Autogenerated type: System.EmptyArray`1 template<typename T> class EmptyArray_1 : public ::Il2CppObject { public: // Autogenerated static field getter // Get static field: static public readonly T[] Value static ::Array<T>* _get_Value() { return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Array<T>*>(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<EmptyArray_1<T>*>::get(), "Value")); } // Autogenerated static field setter // Set static field: static public readonly T[] Value static void _set_Value(::Array<T>* value) { THROW_UNLESS(il2cpp_utils::SetFieldValue(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<EmptyArray_1<T>*>::get(), "Value", value)); } // static private System.Void .cctor() // Offset: 0xFFFFFFFF static void _cctor() { THROW_UNLESS(il2cpp_utils::RunMethod(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<EmptyArray_1<T>*>::get(), ".cctor")); } }; // System.EmptyArray`1 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::EmptyArray_1, "System", "EmptyArray`1"); #pragma pack(pop)
42.333333
156
0.690945
Futuremappermydud
5a741631d09960b51a077008587af778b9cebf5e
1,796
cpp
C++
Wallet/UnoSemuxAddrsGroup.cpp
uno-labs/semux-light-core
49972e8ee1cb60f166f9cede847831d3c6411e9f
[ "MIT" ]
1
2020-08-12T05:44:09.000Z
2020-08-12T05:44:09.000Z
Wallet/UnoSemuxAddrsGroup.cpp
uno-labs/semux-light-core
49972e8ee1cb60f166f9cede847831d3c6411e9f
[ "MIT" ]
null
null
null
Wallet/UnoSemuxAddrsGroup.cpp
uno-labs/semux-light-core
49972e8ee1cb60f166f9cede847831d3c6411e9f
[ "MIT" ]
1
2020-06-09T13:20:15.000Z
2020-06-09T13:20:15.000Z
#include "UnoSemuxAddrsGroup.hpp" #include "UnoSemuxWalletUtils.hpp" namespace UnoSemux { UnoSemuxAddrsGroup::UnoSemuxAddrsGroup (GpCryptoKeyFactory::SP aFactory): iFactory(std::move(aFactory)) { } UnoSemuxAddrsGroup::~UnoSemuxAddrsGroup (void) noexcept { Clear(); } void UnoSemuxAddrsGroup::Clear (void) noexcept { iFactory.Clear(); iAddrsList.clear(); } void UnoSemuxAddrsGroup::Set (UnoSemuxAddrsGroup&& aGroup) noexcept { Clear(); iFactory = std::move(aGroup.iFactory); iAddrsList = std::move(aGroup.iAddrsList); aGroup.Clear(); } UnoSemuxAddr::SP UnoSemuxAddrsGroup::GenNext (void) { UnoSemuxAddr::SP addr = UnoSemuxWalletUtils::SNewAddrFromFactory(iFactory.V()); iAddrsList.emplace(addr.VCn().AddrStrHex(), addr); return addr; } void UnoSemuxAddrsGroup::Delete (GpRawPtrCharR aAddrStrHex) { std::string key(ExtractAddrHex(aAddrStrHex)); if (iAddrsList.erase(key) == 0) { THROW_GPE("Addres '"_sv + aAddrStrHex.AsStringView() + "' not found"_sv); } } UnoSemuxAddr::SP UnoSemuxAddrsGroup::Find (GpRawPtrCharR aAddrStrHex) { std::string key(ExtractAddrHex(aAddrStrHex)); auto iter = iAddrsList.find(key); if (iter == iAddrsList.end()) { THROW_GPE("Addres '"_sv + aAddrStrHex.AsStringView() + "' not found"_sv); } return iter->second; } bool UnoSemuxAddrsGroup::IsContainAddr (GpRawPtrCharR aAddrStrHex) const { std::string key(ExtractAddrHex(aAddrStrHex)); return iAddrsList.count(key) > 0; } std::string_view UnoSemuxAddrsGroup::ExtractAddrHex (GpRawPtrCharR aAddrStrHex) const noexcept { if (aAddrStrHex.IsEqualByArgLen("0x"_sv)) { return aAddrStrHex.SubrangeBeginOffset(2_cnt).AsStringView(); } else { return aAddrStrHex.AsStringView(); } } }//namespace UnoSemux
22.734177
95
0.717149
uno-labs
5a78366465e39e122e39bfa8904d8ad99c7708e5
2,440
cpp
C++
src/auto/ThreeShotAutonRoutine.cpp
core2062/NordVPN2021
0e21021f9308441849a4d40cc64478c98d8fcafa
[ "BSD-3-Clause" ]
null
null
null
src/auto/ThreeShotAutonRoutine.cpp
core2062/NordVPN2021
0e21021f9308441849a4d40cc64478c98d8fcafa
[ "BSD-3-Clause" ]
null
null
null
src/auto/ThreeShotAutonRoutine.cpp
core2062/NordVPN2021
0e21021f9308441849a4d40cc64478c98d8fcafa
[ "BSD-3-Clause" ]
null
null
null
#include "ThreeShotAutonRoutine.h" ThreeShotRoutine::ThreeShotRoutine() : COREAuton("Three Shot Routine") {} void ThreeShotRoutine::AddNodes() { driveNode = new Node(7000, new DriveAction(BACKWARD)); shotOneOnNode = new Node(5, new LaunchAction(LAUNCHER_ON)); delayShotOneNode = new Node(shotDelayTime, new DelayAction()); shotOneOffNode = new Node(5, new LaunchAction(LAUNCHER_OFF)); delayOneNode = new Node(delayTime, new DelayAction()); conveyOneOnNode = new Node(5, new ConveyorAction(CONVEYOR_ON)); delayConveyOneNode = new Node(conveyDelayTime, new DelayAction()); conveyOneOffNode = new Node(5, new ConveyorAction(CONVEYOR_OFF)); delayConveyShotOneNode = new Node(conveyToShotDelayTime, new DelayAction()); shotTwoOnNode = new Node(5, new LaunchAction(LAUNCHER_ON)); delayShotTwoNode = new Node(shotDelayTime, new DelayAction()); shotTwoOffNode = new Node(5, new LaunchAction(LAUNCHER_OFF)); delayTwoNode = new Node(delayTime, new DelayAction()); conveyTwoOnNode = new Node(5, new ConveyorAction(CONVEYOR_ON)); delayConveyTwoNode = new Node(conveyDelayTime, new DelayAction()); conveyTwoOffNode = new Node(5, new ConveyorAction(CONVEYOR_OFF)); delayConveyShotTwoNode = new Node(conveyToShotDelayTime, new DelayAction()); shotThreeOnNode = new Node(5, new LaunchAction(LAUNCHER_ON)); delayShotThreeNode = new Node(0.5, new DelayAction()); shotThreeOffNode = new Node(5, new LaunchAction(LAUNCHER_OFF)); AddFirstNode(driveNode); driveNode->AddNext(shotOneOnNode); shotOneOnNode->AddNext(delayShotOneNode); delayShotOneNode->AddNext(shotOneOffNode); shotOneOffNode->AddNext(delayOneNode); delayOneNode->AddNext(conveyOneOnNode); conveyOneOnNode->AddNext(delayConveyOneNode); delayConveyOneNode->AddNext(conveyOneOffNode); conveyOneOffNode->AddNext(delayConveyShotOneNode); delayConveyShotOneNode->AddNext(shotTwoOnNode); shotTwoOnNode->AddNext(delayShotTwoNode); delayShotTwoNode->AddNext(shotTwoOffNode); shotTwoOffNode->AddNext(delayTwoNode); delayTwoNode->AddNext(conveyTwoOnNode); conveyTwoOnNode->AddNext(delayConveyTwoNode); delayConveyTwoNode->AddNext(conveyTwoOffNode); conveyTwoOffNode->AddNext(delayConveyShotTwoNode); delayConveyShotTwoNode->AddNext(shotThreeOnNode); shotThreeOnNode->AddNext(delayShotThreeNode); delayShotThreeNode->AddNext(shotThreeOffNode); }
51.914894
80
0.764754
core2062
5a797dd05adbaf0d6a42440a100f4f516b5d1327
453
cpp
C++
vslib/Event.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
50
2016-03-23T08:04:44.000Z
2022-03-25T05:06:16.000Z
vslib/Event.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
589
2016-04-01T04:09:09.000Z
2022-03-31T00:38:10.000Z
vslib/Event.cpp
vmittal-msft/sonic-sairedis
6baff35880005aee2854fdcde105c4322c28d04f
[ "Apache-2.0" ]
234
2016-03-28T20:59:21.000Z
2022-03-23T09:26:22.000Z
#include "Event.h" #include "swss/logger.h" using namespace saivs; Event::Event( _In_ EventType eventType, _In_ std::shared_ptr<EventPayload> payload): m_eventType(eventType), m_payload(payload) { SWSS_LOG_ENTER(); // empty } EventType Event::getType() const { SWSS_LOG_ENTER(); return m_eventType; } std::shared_ptr<EventPayload> Event::getPayload() const { SWSS_LOG_ENTER(); return m_payload; }
14.612903
55
0.671082
vmittal-msft
5a8004ba9031cc996a0f2e1ffc5222750c8b1eb9
2,179
hpp
C++
tuple/trim.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
tuple/trim.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
tuple/trim.hpp
5cript/mpl14
4c6da6b8bce1f57b0df8c4ef456fe03a61982cad
[ "MIT" ]
null
null
null
#ifndef MPLEX_TUPLE_TUPLE_TRIM_HPP_INCLUDED #define MPLEX_TUPLE_TUPLE_TRIM_HPP_INCLUDED #include <tuple> #include "pop_back.hpp" namespace mplex { template <typename Tuple, typename Predicate, bool Abort = false> struct trim_left { }; template <typename Predicate, typename T, typename... List> struct trim_left <std::tuple <T, List...>, Predicate, false> { using type = if_vt <Predicate::template apply <T>::value, typename trim_left <std::tuple<List...>, Predicate, !Predicate::template apply<T>::value>::type, std::tuple <T, List...>>; }; template <typename Predicate> struct trim_left <std::tuple <>, Predicate, false> { using type = std::tuple <>; }; template <typename Tuple, typename Predicate> struct trim_left <Tuple, Predicate, true> { using type = Tuple; }; template <typename Tuple, typename Predicate> using trim_left_t = typename trim_left <Tuple, Predicate>::type; template <typename Tuple, typename Predicate, bool Abort = false> struct trim_right { // Abort == false using type = if_vt <Predicate::template apply <typename std::tuple_element <std::tuple_size <Tuple>::value - 1, Tuple>::type>::value, typename trim_right <pop_back_t<Tuple>, Predicate>::type, Tuple>; }; template <typename Tuple, typename Predicate> struct trim_right <Tuple, Predicate, true> { using type = Tuple; }; template <typename Predicate> struct trim_right <std::tuple <>, Predicate, false> { using type = std::tuple <>; }; template <typename Tuple, typename Predicate> using trim_right_t = typename trim_right <Tuple, Predicate>::type; template <typename Tuple, typename Predicate> struct trim { using type = trim_right_t <trim_left_t <Tuple, Predicate>, Predicate>; }; template <typename Tuple, typename Predicate> using trim_t = typename trim <Tuple, Predicate>::type; } #endif // MPLEX_TUPLE_TRIM_HPP_INCLUDED
34.046875
142
0.623681
5cript
5a80c63ed2bbebeb465127747f9491cd9eaf0e4c
242
cpp
C++
Lab1/Sheep.cpp
devtedlee/cppStudyProjects
65c7504773a332b32b473058b273fe1356d0b7b5
[ "MIT" ]
null
null
null
Lab1/Sheep.cpp
devtedlee/cppStudyProjects
65c7504773a332b32b473058b273fe1356d0b7b5
[ "MIT" ]
null
null
null
Lab1/Sheep.cpp
devtedlee/cppStudyProjects
65c7504773a332b32b473058b273fe1356d0b7b5
[ "MIT" ]
null
null
null
#include <iostream> #include "Sheep.h" namespace lab1 { Sheep::Sheep(char* name) : Animal(name) , mFurCount(0) { }; Sheep::~Sheep() { } void Sheep::Bark() const { std::cout << Animal::GetName() << ": MEA~" << std::endl; } }
11.52381
58
0.566116
devtedlee
5a856dacd42c9494452c2330b853017ebd142fbf
2,574
cpp
C++
Game/Entity/Player.cpp
BaiKongQue/CSCI-166_AI_Project
81af3d77f6ba595b87f8e7e73caf7b9fc083c592
[ "MIT" ]
null
null
null
Game/Entity/Player.cpp
BaiKongQue/CSCI-166_AI_Project
81af3d77f6ba595b87f8e7e73caf7b9fc083c592
[ "MIT" ]
null
null
null
Game/Entity/Player.cpp
BaiKongQue/CSCI-166_AI_Project
81af3d77f6ba595b87f8e7e73caf7b9fc083c592
[ "MIT" ]
null
null
null
#include "Player.h" float* Player::vk = nullptr; Player::Player(Window* window, std::vector<Entity*>* entities, std::vector<int>* walls, int spawnPos): Person(window, entities, walls, spawnPos, GRID_TYPE::PLAYER, 4, "archer_sprite.png"), arrows(0) { this->LoadVk(); } float Player::GetReward(GRID_TYPE entityType) { switch (entityType) { case GRID_TYPE::GUARD: return 10; break; default: return 0; break; } } std::vector<Entity::State*>* Player::AddStates(int pos) { std::vector<Entity::State*>* states = new std::vector<Entity::State*>(); if (this->arrows > 0 && pos == this->GetPos(this->posX, this->posY)) { for (int i : {-1, 0, 1}) { for (int j : { -1, 0, 1 }) { int x = i + this->posX; int y = j + this->posY; if ( ((i == 0) != (j == 0)) && (x >= 0 && x < this->window->gridSizeX) && (y >= 0 && y < this->window->gridSizeY) && (!this->IsWall(x, y)) ) { Entity* target = nullptr; while (target == nullptr && (x >= 0 && x < this->window->gridSizeX) && (y >= 0 && y < this->window->gridSizeY) && (!this->IsWall(x, y)) ) { for (Entity* entity : *this->entities) { if (entity->type == GRID_TYPE::GUARD && entity->posX == x && entity->posY == y) { target = entity; break; } } x += i; y += j; } if (target != nullptr) { states->push_back(new Entity::State{ STATE::FIRE_ARROW, pos,//(target->GetPos(target->posX, target->posY)), [=]()->void { target->dead = true; this->arrows--; }, [=]()->int { return 10; } }); } } } } } return states; } void Player::OnCollision(Entity* entity) { switch (entity->type) { case GRID_TYPE::ARROW: this->arrows++; entity->dead = true; /*for (int i = 0; i < this->entities->size(); i++) { if (this->entities->at(i) == entity) { this->entities->erase(this->entities->begin() + i); delete entity; return; } }*/ break; case GRID_TYPE::GUARD: this->dead = true; break; } } /*bool Player::guardInSight() { Entity* target = nullptr; while (target == nullptr && (x >= 0 && x < this->window->gridSizeX) && (y >= 0 && y < this->window->gridSizeY) && (!this->IsWall(x, y)) ) { for (Entity* entity : *this->entities) { if (entity->type == GRID_TYPE::GUARD && entity->posX == x && entity->posY == y) { target = entity; break; } } x += i; y += j; } }*/ /*void Player::MakeMove() { if }*/ float* Player::GetVk() { return Player::vk; }
22.778761
102
0.529915
BaiKongQue
5a87c63820d80a41cfcf613c49cf8b4cca24444c
892
cpp
C++
plugins/d3d9/src/state/ffp/sampler/disable.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/d3d9/src/state/ffp/sampler/disable.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/d3d9/src/state/ffp/sampler/disable.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/d3d9/d3dinclude.hpp> #include <sge/d3d9/devicefuncs/set_texture_stage_state.hpp> #include <sge/d3d9/state/ffp/sampler/disable.hpp> #include <sge/renderer/caps/texture_stages.hpp> #include <sge/renderer/texture/stage.hpp> void sge::d3d9::state::ffp::sampler::disable( IDirect3DDevice9 &_device, sge::renderer::texture::stage const _stage, sge::renderer::caps::texture_stages const _stages) { if (_stage.get() >= _stages.get()) return; sge::d3d9::devicefuncs::set_texture_stage_state(_device, _stage, D3DTSS_COLOROP, D3DTOP_DISABLE); sge::d3d9::devicefuncs::set_texture_stage_state(_device, _stage, D3DTSS_ALPHAOP, D3DTOP_DISABLE); }
37.166667
99
0.73991
cpreh
5a8abcfc261da6bac5eff9e3f7749fd21c47c88b
1,760
hpp
C++
src/include/qasioeventdispatcher.hpp
loyio/TPlayNow
eb2bd8652ffbfd68ce71da4ac54ae3949ff471d7
[ "BSD-3-Clause", "MIT" ]
1
2022-03-21T04:04:14.000Z
2022-03-21T04:04:14.000Z
src/include/qasioeventdispatcher.hpp
loyio/TMsgNow
eb2bd8652ffbfd68ce71da4ac54ae3949ff471d7
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/include/qasioeventdispatcher.hpp
loyio/TMsgNow
eb2bd8652ffbfd68ce71da4ac54ae3949ff471d7
[ "BSD-3-Clause", "MIT" ]
null
null
null
#ifndef QASIOEVENTDISPATCHER_HPP #define QASIOEVENTDISPATCHER_HPP #include "QtCore/qabstracteventdispatcher.h" // #include "private/qabstracteventdispatcher_p.h" #include <QAbstractEventDispatcher> /* #include "QtCore/qabstracteventdispatcher.h" #include "QtCore/qlist.h" #include "private/qabstracteventdispatcher_p.h" #include "private/qcore_unix_p.h" #include "private/qpodlist_p.h" #include "QtCore/qvarlengtharray.h" #if !defined(Q_OS_VXWORKS) # include <sys/time.h> # if (!defined(Q_OS_HPUX) || defined(__ia64)) && !defined(Q_OS_NACL) # include <sys/select.h> # endif #endif */ class QAsioEventDispatcherPrivate; namespace boost { namespace asio { class io_service; } } class Q_CORE_EXPORT QAsioEventDispatcher : public QAbstractEventDispatcher { Q_OBJECT Q_DECLARE_PRIVATE(QAsioEventDispatcher) public: explicit QAsioEventDispatcher(boost::asio::io_service &io_service, QObject *parent = 0); ~QAsioEventDispatcher(); bool processEvents(QEventLoop::ProcessEventsFlags flags); bool hasPendingEvents(); void registerSocketNotifier(QSocketNotifier *notifier) Q_DECL_FINAL; void unregisterSocketNotifier(QSocketNotifier *notifier) Q_DECL_FINAL; void registerTimer(int timerId, int interval, Qt::TimerType timerType, QObject *object) Q_DECL_FINAL; bool unregisterTimer(int timerId) Q_DECL_FINAL; bool unregisterTimers(QObject *object) Q_DECL_FINAL; QList<TimerInfo> registeredTimers(QObject *object) const Q_DECL_FINAL; int remainingTime(int timerId) Q_DECL_FINAL; void wakeUp() Q_DECL_FINAL; void interrupt() Q_DECL_FINAL; //TODO: void flush(); protected: QAsioEventDispatcher(QAsioEventDispatcherPrivate &dd, QObject *parent = 0); }; #endif // QASIOEVENTDISPATCHER_HPP
29.333333
105
0.775568
loyio
5a8bfb34ea4efc6c93d93f11074ca2950892bc31
2,014
cpp
C++
Ko-Fi Engine/Source/Texture.cpp
boscobarberesbert/Ko-Fi-Engine
207ef2223f7c317a776cc7ca2da80ce9a2752116
[ "MIT" ]
2
2022-02-17T10:06:57.000Z
2022-02-17T11:57:18.000Z
Ko-Fi Engine/Source/Texture.cpp
boscobarberesbert/game-engine
207ef2223f7c317a776cc7ca2da80ce9a2752116
[ "MIT" ]
null
null
null
Ko-Fi Engine/Source/Texture.cpp
boscobarberesbert/game-engine
207ef2223f7c317a776cc7ca2da80ce9a2752116
[ "MIT" ]
8
2022-01-04T10:45:15.000Z
2022-03-04T16:23:58.000Z
#include "Texture.h" #include "glew.h" #include "stb_image.h" #include "ImGuiAppLog.h" #define CHECKERS_SIZE 32 void Texture::SetUpTexture(std::string path) { if (path.empty()) { GLubyte checkerImage[CHECKERS_SIZE][CHECKERS_SIZE][4]; for (int i = 0; i < CHECKERS_SIZE; i++) { for (int j = 0; j < CHECKERS_SIZE; j++) { int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255; checkerImage[i][j][0] = (GLubyte)c; checkerImage[i][j][1] = (GLubyte)c; checkerImage[i][j][2] = (GLubyte)c; checkerImage[i][j][3] = (GLubyte)255; } } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (textureID == 0) { glGenTextures(1, &textureID); } glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, CHECKERS_SIZE, CHECKERS_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkerImage); return; } this->texturePath = path; unsigned char* pixels = stbi_load(path.c_str(), &this->width, &this->height, &this->nrChannels, STBI_rgb); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (textureID == 0) { glGenTextures(1, &textureID); } glBindTexture(GL_TEXTURE_2D, this->textureID); // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (pixels) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->width, this->height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels); glGenerateMipmap(GL_TEXTURE_2D); } else { appLog->AddLog("%s", "Texture Image not loaded correctly"); } stbi_image_free(pixels); }
31.968254
107
0.723436
boscobarberesbert
5a8d3d9fbf26b8bc627de8106fd0d50434cf46e0
1,524
cpp
C++
src/mkdt_lib/src/registry.cpp
Superlokkus/code
f52cba0c04fc65c0b219ab8e58fdc8144320a039
[ "MIT" ]
null
null
null
src/mkdt_lib/src/registry.cpp
Superlokkus/code
f52cba0c04fc65c0b219ab8e58fdc8144320a039
[ "MIT" ]
null
null
null
src/mkdt_lib/src/registry.cpp
Superlokkus/code
f52cba0c04fc65c0b219ab8e58fdc8144320a039
[ "MIT" ]
null
null
null
/*! @file registry.cpp * */ #include <registry.hpp> void mkdt::registry::register_service(mkdt::service_identifier service_id, std::shared_ptr<mkdt::registry::receiver> service_object, std::function<void(error)> completion_handler) { boost::asio::dispatch(this->io_context_, boost::asio::bind_executor(this->registry_strand_, [=, completion_handler = std::move(completion_handler)]() { const auto new_object_id = this->uuid_gen_(); this->services_.emplace(service_id,new_object_id); this->objects_.emplace(new_object_id, service_object); this->router_.register_service(service_id, std::move(completion_handler), [=] (auto callback) { boost::asio::dispatch(this->io_context_, boost::asio::bind_executor(this->registry_strand_, [=]() { callback(new_object_id); })); }); })); } void mkdt::registry::send_message_to_object(const mkdt::object_identifier &receiver, const std::string &message, std::function<void(error)> handler) { } void mkdt::registry::use_service_interface(mkdt::service_identifier service_id, std::function<void(error, object_identifier)> handler) { this->router_.use_service_interface(service_id, std::move(handler)); }
42.333333
112
0.578084
Superlokkus
5a8fd641261b95736d93fba5af5cdcd623dc534f
16,082
hpp
C++
include/solace/path.hpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
18
2016-05-30T23:46:27.000Z
2022-01-11T18:20:28.000Z
include/solace/path.hpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
4
2017-09-12T13:32:28.000Z
2019-10-21T10:36:18.000Z
include/solace/path.hpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
5
2017-11-24T19:34:06.000Z
2019-10-18T14:24:12.000Z
/* * Copyright 2016 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace: Hierarchical path object * @file solace/path.hpp * @brief Immutable hierarchical Path class ******************************************************************************/ #pragma once #ifndef SOLACE_PATH_HPP #define SOLACE_PATH_HPP #include "solace/string.hpp" #include "solace/array.hpp" #include "solace/result.hpp" #include "solace/error.hpp" #include "solace/vector.hpp" namespace Solace { /** Hierarchical path class - the kind used by File system, but not exactly * Path is an ordered sequence of strings/names that can be represented by a string, * e.g Formattable and Parsable object. * * Examples of Paths (first 3 with the same '/' as a delimiter): * * File system path string: /etc/config.json * * URL path component: /webapp/action/index.html * * Tree element path: <root>/node x/taget_node * * Web host name also a path: www.blah.example.com * * Java package name: org.java.AwesomePackages * * Note: that path object is designed to be immutable, e.g it cannot be changed once created, * It can be appended to / subtracted from - creating a new object (kind of like a linked list). * Being immutable means that any such addition or subtraction will produce a new object. * * Note: Path is an abstraction and is not designed to be compatible with * the underlying filesystem representation of a file path. * Wherever possible file objects can be created from a file system path, * but no direct compatibility is designed. * This also implies that functions line noramalize don't do file system travesal, * but operate on path string components only. */ class Path { public: using value_type = String; using size_type = Array<value_type>::size_type; struct Iterator { Iterator(ArrayView<const value_type> const& p, size_type position) noexcept : _index{position} , _path{p} {} constexpr Iterator(Iterator const& rhs) noexcept = default; constexpr Iterator(Iterator&& rhs) noexcept = default; Iterator& operator= (Iterator const& rhs) noexcept = default; Iterator& operator= (Iterator&& rhs) noexcept { return swap(rhs); } constexpr bool operator!= (Iterator const& other) const noexcept { return (_index != other._index); } constexpr bool operator== (Iterator const& other) const noexcept { return (_index == other._index); } Iterator& operator++ (); StringView operator-> () const; auto operator* () const { return operator ->(); } Iterator& swap(Iterator& rhs) noexcept { std::swap(_index, rhs._index); std::swap(_path, rhs._path); return *this; } constexpr size_type getIndex() const noexcept { return _index; } private: size_type _index; ArrayView<const value_type> _path; }; using const_iterator = Iterator; public: // Static methods /** * Default delimiter used form string representation of the path * Note: might be different from platform delimiter */ static const StringView Delimiter; /** * Root path object */ static const Path Root; /** * Parse a path object from a string. * * @param str A string to parse * @param delim A delimiter used to separate path components * @return Parsed path object * * TODO: Parse family of functions should return Result<Path, ParseError> */ static Result<Path, Error> parse(StringView str, StringView delim = Delimiter); public: // Object construction /** Construct an empty path */ /*constexpr*/ Path() noexcept = default; /** Construct an object by moving content from a given */ /*constexpr*/ Path(Path&& p) noexcept : _components{mv(p._components)} { } public: // Operation Path& swap(Path& rhs) noexcept { _components.swap(rhs._components); return (*this); } /** * Move assignement. * @param rhs An object to move content from. * @return A reference to this. */ Path& operator= (Path&& rhs) noexcept { return swap(rhs); } /** Test if the path is empty. * * Path is empty only when it has no components. * @return True if the path object is empty. */ constexpr bool empty() const noexcept { return _components.empty(); } /** Test if path is not empty. * @return True if this path is not an empty object. */ explicit constexpr operator bool() const { return !empty(); } /** Tests this path for equality with the given object. * @param rhv A path to compare this one to. * @return True if this path is equal to the give */ bool equals(Path const& rhv) const noexcept; /** * Test if the path is absolute. * * Asbolute path is the one that starts with the root. * @return True if the path object represents absolute path */ bool isAbsolute() const noexcept; /** * Test if the path is relative. * * Relative path is the one that doe not starts with the root. * @return True if the path object represents relative path */ bool isRelative() const noexcept; /** * Get the lenght of the string representation of this path. * * @note: To get the number of components, please @see getComponentsCount * @return Size of the string representation of the path in characters. */ String::size_type length(StringView delim = Delimiter) const noexcept; //-------------------------------------------------------------------------- // --- Relational collection operations //-------------------------------------------------------------------------- /** Compares two paths lexicographically. * The comparison is based on the Unicode value * of each character in the strings that make up path parts. * The result is zero if two paths are equal: * exactly when the equals(other) would return true. * * @return The value 0 if the argument string is equal to this string; * @return a value less than 0 if this string is lexicographically less than the string argument; * @return and a value greater than 0 if this string is lexicographically greater than the string argument. */ int compareTo(const Path& other) const; /** Tests if this path starts with the given path. * @param other * @return True, if this path object starts with the given */ bool startsWith(const Path& other) const; /** Tests if this path string representation starts with the string given. * @param str A string to test * @return True, if this path object starts with the given string */ bool startsWith(StringView str) const { // FIXME: Wasteful allocation of string representation return toString().startsWith(str); } /** Tests if this path ends with the given path. * @param other * @return True, if this path object ends with the given */ bool endsWith(Path const& other) const; /** Tests if this path ends with the given string. * @param other * @return True, if this path object ends with the given */ bool endsWith(StringView other) const { // FIXME: Wasteful allocation of string representation return toString().endsWith(other); } /** Determine if the path contains a given subpath. * * @param path The subpath to search for. * @return <b>true</b> if the path contains the subpath, <b>false</b> otherwise. */ bool contains(const Path& path) const; /** Determine if the path string representation contains a given substring. * * @param str The substring to search for. * @return <b>true</b> if the path contains the substring, <b>false</b> otherwise. */ bool contains(StringView str) const { // FIXME: Wasteful allocation of string representation return toString().contains(str); } /** Determine if the path string representation contains a given substring. * * @param str The substring to search for. * @return <b>true</b> if the path contains the substring, <b>false</b> otherwise. */ bool contains(String const& str) const { return contains(str.view()); } /** Returns a path that is this path with redundant name elements eliminated. * Self reference (usually '.') and parent reference (usually '..') are * considered redundunt elements and in most cases can be removed. * * @note The mothod does not consult file system and operates on the string only. * As such it can result in files that don't exist. * * @return path that is this path with redundant name elements eliminated. */ Path normalize() const; // ---- decomposition ---- /** Get parent path or null path if this is the root * @return Parent of this path or null */ Path getParent() const; /** * Returns the name of the object this path leads to * @return The last element of the name sequence */ StringView getBasename() const; /** Get number of components this path includes * @brief getComponentsCount * @return Number of path elements in this path */ constexpr size_type getComponentsCount() const noexcept { return _components.size(); } /** Get n'th component of this path * @param index Index of a path segment * @return Number of path elements in this path */ StringView getComponent(size_type index) const; const_iterator begin() const { return Iterator{_components.view(), 0}; } const_iterator end() const { return Iterator{_components.view(), _components.size()}; } /** Returns sub path of this path * Slice of this path object * @return Sub path of this path */ Path subpath(size_type beginIndex, size_type endIndex) const noexcept; /** @see Iterable::forEach */ template<typename F> std::enable_if_t<isCallable<F, StringView>::value, Path const &> forEach(F&& f) const { for (auto const& i : _components) { f(i.view()); } return *this; } template<typename F> std::enable_if_t<isCallable<F, Path::value_type&&>::value, Path &> forEach(F&& f) && { for (auto& i : _components) { f(mv(i)); } return *this; } /** Get string representation of the path object using give delimiter */ String toString(StringView delim) const; /** * Return string representation of this path * @return String representation of this path */ String toString() const { return toString(Delimiter); } protected: friend Path makePath(Array<String>&& array) noexcept; /** FIXME(abbyssoul): Only temporary here. to be removed * Move-Construct the path object from a collection of String components * @param array A collection of string components forming the path */ /*constexpr*/ Path(Array<String>&& array) noexcept : _components{mv(array)} { // No-op } private: Array<String> _components; }; inline bool operator== (Path const& lhs, Path const& rhv) noexcept { return lhs.equals(rhv); } inline bool operator!= (Path const& lhs, Path const& rhv) noexcept { return !lhs.equals(rhv); } inline void swap(Path& lhs, Path& rhs) noexcept { lhs.swap(rhs); } [[nodiscard]] inline Path makePath(Array<String>&& array) noexcept { return {mv(array)}; } [[nodiscard]] inline Path makePath(Vector<String>&& vec) noexcept { return makePath(vec.toArray()); } /** * Construct the path object from a single string component * * @note The string is is parsed into component, please use Path::parse */ [[nodiscard]] Result<Path, Error> makePath(StringView str); [[nodiscard]] inline auto makePath(String const& str) { return makePath(str.view()); } [[nodiscard]] inline auto makePath(char const* str) { return makePath(StringView{str}); } namespace details { constexpr Path::size_type countPathComponents() noexcept { return 0; } constexpr Path::size_type countPathComponents(StringView) noexcept { return 1; } constexpr Path::size_type countPathComponents(StringLiteral) noexcept { return 1; } constexpr Path::size_type countPathComponents(String const&) noexcept { return 1; } constexpr Path::size_type countPathComponents(String&) noexcept { return 1; } constexpr Path::size_type countPathComponents(char const*) noexcept { return 1; } constexpr Path::size_type countPathComponents(Path const& path) noexcept { return path.getComponentsCount(); } constexpr Path::size_type countPathComponents(Path& path) noexcept { return path.getComponentsCount(); } constexpr Path::size_type countPathComponents(Path&& path) noexcept { return path.getComponentsCount(); } template<typename T, typename...Args> Path::size_type countPathComponents(T&& base, Args&&...args) { return (countPathComponents(fwd<T>(base)) + ... + countPathComponents(fwd<Args>(args))); } inline Result<void, Error> joinComponents(Vector<String>& base, StringView view) { auto r = makeString(view); if (!r) return r.moveError(); base.emplace_back(r.moveResult()); return Ok(); } inline Result<void, Error> joinComponents(Vector<String>& base, String&& str) { base.emplace_back(mv(str)); return Ok(); } inline Result<void, Error> joinComponents(Vector<String>& base, String const& str) { auto maybeDup = makeString(str); if (!maybeDup) return maybeDup.moveError(); base.emplace_back(maybeDup.moveResult()); return Ok(); } inline Result<void, Error> joinComponents(Vector<String>& base, Path&& path) { mv(path).forEach([&base](Path::value_type&& component) { base.emplace_back(mv(component)); }); return Ok(); } inline Result<void, Error> joinComponents(Vector<String>& base, Path const& path) { for (auto component : path) { auto maybeDup = makeString(component); if (!maybeDup) return maybeDup.moveError(); base.emplace_back(maybeDup.moveResult()); } return Ok(); } template <typename...Args> Result<void, Error> joinComponents(Vector<String>& base, StringView view, Args&&...args) { auto r = joinComponents(base, view); if (!r) return r; return joinComponents(base, fwd<Args>(args)...); } template <typename...Args> Result<void, Error> joinComponents(Vector<String>& base, String const& view, Args&&...args) { auto r = joinComponents(base, view); if (!r) return r; return joinComponents(base, fwd<Args>(args)...); } template <typename...Args> Result<void, Error> joinComponents(Vector<String>& base, Path const& path, Args&&...args) { auto r = joinComponents(base, path); if (!r) return r; return joinComponents(base, fwd<Args>(args)...); } template <typename...Args> Result<void, Error> joinComponents(Vector<String>& base, Path&& path, Args&&...args) { auto r = joinComponents(base, mv(path)); if (!r) return r; return joinComponents(base, fwd<Args>(args)...); } } // namespace details template<typename...Args> [[nodiscard]] Result<Path, Error> makePath(Args&&...args) { auto maybeVector = makeVector<Path::value_type>(details::countPathComponents(fwd<Args>(args)...)); if (!maybeVector) { return maybeVector.moveError(); } auto maybeComponents = details::joinComponents(maybeVector.unwrap(), fwd<Args>(args)...); if (!maybeComponents) { return maybeComponents.moveError(); } return Ok(makePath(maybeVector.moveResult())); } } // namespace Solace #endif // SOLACE_PATH_HPP
29.028881
110
0.666148
abbyssoul
5a94661aa1a14f3937875bd68bc8848b1581bf46
707
cpp
C++
src/lib/Bmrk.cpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/Bmrk.cpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/Bmrk.cpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
#include "Bmrk.hpp" #include "Bookmark.hpp" #include "PageDownloader.hpp" #include "PageParser.hpp" #include "Library.hpp" namespace bmrk { Bmrk::Bmrk(PageDownloaderPtr downloader, DatabasePtr db) : downloader_{downloader}, db_{db} { library_.reset(new Library); library_->connect(db); } Future<BookmarkPtr> Bmrk::createBookmarkFromUrl(const String& url) const { return std::async([url, this]() { BookmarkData data; auto page = downloader_->load(url).get(); auto parser = PageParser(page); data.url = url; data.title = parser.getTitle(); return BookmarkPtr(new Bookmark{data}); }); } void Bmrk::add(BookmarkPtr bookmark) { library_->add(bookmark); } } /* bmrk */
22.806452
74
0.691655
alepez
5a95081d9416399eb580dcde143b00bcaec31c77
2,599
hxx
C++
L2CapDev/mobileremotedrv.hxx
nbclark/mobile-remote
d291ec9accc763190646d97e45dad9e07c630973
[ "Apache-2.0" ]
1
2020-12-15T09:48:51.000Z
2020-12-15T09:48:51.000Z
L2CapDev/mobileremotedrv.hxx
nbclark/mobile-remote
d291ec9accc763190646d97e45dad9e07c630973
[ "Apache-2.0" ]
null
null
null
L2CapDev/mobileremotedrv.hxx
nbclark/mobile-remote
d291ec9accc763190646d97e45dad9e07c630973
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. // /** THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Abstract: Windows CE Bluetooth stack layer sample **/ #if ! defined (__l2capdev_HXX__) #define __l2capdev_HXX__ 1 #define L2CAPDEV_IOCTL_L2CAPConnect 1 #define L2CAPDEV_IOCTL_L2CAPAccept 2 #define L2CAPDEV_IOCTL_L2CAPListen 3 #define L2CAPDEV_IOCTL_L2CAPWrite 4 #define L2CAPDEV_IOCTL_L2CAPRead 5 #define L2CAPDEV_IOCTL_L2CAPCloseCID 6 #define L2CAPDEV_IOCTL_L2CAPClosePSM 7 #define L2CAPDEV_IOCTL_L2CAPPing 8 #define L2CAPDEV_IOCTL_L2CAPConfigReq 9 typedef union { struct { // in-parameters BT_ADDR ba; unsigned short usPSM; unsigned short usInMTU; // out-parameters unsigned short usCID; unsigned short usOutMTU; } L2CAPConnect_p; struct { // in-parameters unsigned short usPSM; unsigned short usInMTU; } L2CAPListen_p; struct { // in-parameters unsigned short usPSM; // out-parameters BT_ADDR ba; unsigned short usCID; unsigned short usOutMTU; } L2CAPAccept_p; struct { // in-parameters unsigned short usCID; unsigned int cBuffer; // out-parameters unsigned int cRequired; unsigned char *pBuffer; } L2CAPReadWrite_p; struct { // in-parameters BT_ADDR ba; unsigned int cBufferIn; unsigned char *pBufferIn; // in-out unsigned int cBufferOut; // out-parameters unsigned char *pBufferOut; } L2CAPPing_p; struct { unsigned short usCID; unsigned short usInMTU; unsigned short usOutFlushTO; struct btFLOWSPEC *pOutFlow; int cOptNum; struct btCONFIGEXTENSION **ppExtendedOptions; } L2CAPConfigReq_p; struct { // in-parameters unsigned short us; } L2CAPClose_p; } L2CAPDEVAPICALL; #endif /* __l2capdev_HXX__ */
26.252525
85
0.710273
nbclark
5a9603906dc473d46a438fd3534f15a834fb30b2
1,668
cpp
C++
test/unit-tests/event/drop_event_test.cpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
126
2020-12-05T00:05:56.000Z
2022-03-30T15:15:03.000Z
test/unit-tests/event/drop_event_test.cpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
46
2020-12-27T14:25:22.000Z
2022-01-26T13:58:11.000Z
test/unit-tests/event/drop_event_test.cpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
13
2021-01-20T20:50:18.000Z
2022-03-25T06:59:03.000Z
#include <gtest/gtest.h> #include "events/event.hpp" TEST(DropEvent, Defaults) { cen::drop_event event; ASSERT_GT(event.time(), 0u); ASSERT_EQ(cen::event_type::drop_file, event.type()); } TEST(DropEvent, SetWillFreeFile) { cen::drop_event event; event.set_will_free_file(true); ASSERT_TRUE(event.will_free_file()); event.set_will_free_file(false); ASSERT_FALSE(event.will_free_file()); } TEST(DropEvent, SetFile) { cen::drop_event event; ASSERT_NO_THROW(event.set_file(nullptr)); // This is the only time in the tests that a drop_event should free the file, // check the code coverage reports in order to see if it's freed. event.set_file(static_cast<char*>(SDL_malloc(sizeof(char)))); event.set_will_free_file(true); } TEST(DropEvent, SetWindowId) { cen::drop_event event; constexpr cen::u32 id = 84; event.set_window_id(id); ASSERT_EQ(id, event.window_id()); } TEST(DropEvent, WillFreeFile) { const cen::drop_event event; ASSERT_FALSE(event.will_free_file()); } TEST(DropEvent, File) { char file = '1'; // pretend this is some raw data SDL_DropEvent sdl; sdl.file = &file; // shouldn't be deleted, otherwise we're in trouble const cen::drop_event event{sdl}; ASSERT_TRUE(event.file()); ASSERT_EQ(file, *event.file()); } TEST(DropEvent, WindowId) { SDL_DropEvent sdl{}; sdl.windowID = 32; const cen::drop_event event{sdl}; ASSERT_EQ(sdl.windowID, event.window_id()); } TEST(DropEvent, AsSDLEvent) { const cen::drop_event event; const auto sdl = cen::as_sdl_event(event); ASSERT_EQ(sdl.drop.type, cen::to_underlying(event.type())); ASSERT_EQ(sdl.drop.timestamp, event.time()); }
20.85
79
0.714628
twantonie
5a97e87eb1efd638ccdc8e41c6e3ff1e3bf411c4
211
cpp
C++
src/aimlset.cpp
hoathienvu8x/chatmachine
a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89
[ "Apache-2.0" ]
4
2019-05-01T02:34:17.000Z
2020-12-27T23:29:45.000Z
src/aimlset.cpp
hoathienvu8x/chatmachine
a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89
[ "Apache-2.0" ]
1
2020-03-25T09:14:18.000Z
2020-03-25T09:14:18.000Z
src/aimlset.cpp
hoathienvu8x/chatmachine
a05e9afd2dabe49e4a61ba97fbd07d2fcd041b89
[ "Apache-2.0" ]
11
2019-03-15T07:53:58.000Z
2022-01-08T03:51:21.000Z
#include "aimlset.h" #include "aimltemplateelement.h" using namespace std; using namespace aiml; string Set::name() { return m_sName; } string Set::toString() { return "<set name=\""+m_sName+"\"></set>"; }
15.071429
43
0.677725
hoathienvu8x
5a9a3bc6a067df2104486193ed8c7445b1036b99
54,008
cpp
C++
matrix/EM_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
140
2015-01-02T21:28:55.000Z
2015-12-22T01:25:03.000Z
matrix/EM_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
160
2016-11-07T18:37:33.000Z
2020-03-10T22:57:07.000Z
matrix/EM_vector.cpp
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
25
2016-11-14T04:31:29.000Z
2020-07-28T04:58:44.000Z
/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 <libgen.h> #include <malloc.h> #include <unordered_map> #include <boost/math/common_factor.hpp> #include <boost/format.hpp> #include "safs_file.h" #include "io_request.h" #include "io_interface.h" #include "in_mem_io.h" #include "EM_vector.h" #include "matrix_config.h" #include "mem_worker_thread.h" #include "local_vec_store.h" #include "matrix_store.h" #include "bulk_operate_ext.h" #include "EM_dense_matrix.h" namespace fm { namespace detail { namespace { /* * When we write data to disks, we need to have something to hold the buffer. * This holds the local buffer until the write completes. */ class portion_write_complete: public portion_compute { vec_store::const_ptr store; public: portion_write_complete(vec_store::const_ptr store) { this->store = store; } virtual void run(char *buf, size_t size) { assert(store->get_length() * store->get_entry_size() == size); } }; } class EM_vec_dispatcher: public task_dispatcher { const EM_vec_store &store; off_t portion_idx; pthread_spinlock_t lock; size_t portion_size; public: EM_vec_dispatcher(const EM_vec_store &_store, size_t portion_size = 0): store(_store) { pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE); portion_idx = 0; if (portion_size == 0) this->portion_size = store.get_portion_size(); else this->portion_size = portion_size; } virtual bool issue_task() { pthread_spin_lock(&lock); off_t global_start = portion_idx * portion_size; if ((size_t) global_start >= store.get_length()) { pthread_spin_unlock(&lock); return false; } size_t length = std::min(portion_size, store.get_length() - global_start); portion_idx++; pthread_spin_unlock(&lock); create_vec_task(global_start, length, store); return true; } virtual void create_vec_task(off_t global_start, size_t length, const EM_vec_store &from_vec) = 0; }; class seq_writer { size_t local_buf_size; // In the number of elements off_t merge_end; // In the number of elements local_buf_vec_store::ptr buf; size_t data_size_in_buf; // In the number of elements EM_vec_store::ptr to_vec; public: seq_writer(EM_vec_store::ptr vec, off_t write_start) { this->local_buf_size = matrix_conf.get_write_io_buf_size() / vec->get_type().get_size(); this->to_vec = vec; merge_end = write_start; buf = local_buf_vec_store::ptr(new local_buf_vec_store( -1, local_buf_size, to_vec->get_type(), -1)); data_size_in_buf = 0; } ~seq_writer() { assert(data_size_in_buf == 0); } void flush_buffer_data(bool last); void append(local_vec_store::const_ptr data); }; void seq_writer::flush_buffer_data(bool last) { if (data_size_in_buf == 0) return; if (!last) assert((data_size_in_buf * buf->get_entry_size()) % PAGE_SIZE == 0); else data_size_in_buf = ROUNDUP((data_size_in_buf * buf->get_entry_size()), PAGE_SIZE) / buf->get_entry_size(); buf->resize(data_size_in_buf); const scalar_type &type = buf->get_type(); to_vec->write_portion_async(buf, merge_end); merge_end += data_size_in_buf; if (!last) // The data is written asynchronously, we need to allocate // a new buffer. buf = local_buf_vec_store::ptr(new local_buf_vec_store( -1, local_buf_size, type, -1)); else buf = NULL; data_size_in_buf = 0; } void seq_writer::append(local_vec_store::const_ptr data) { assert(buf); // In the number of elements. off_t off_in_new_data = 0; size_t new_data_size = data->get_length(); // If possible, we want to write data to disks directly // to avoid extra memory copy as below. size_t entry_size = data->get_type().get_size(); long addr = (long) data->get_raw_arr(); if ((data->get_length() * entry_size) % PAGE_SIZE == 0 && (data_size_in_buf * entry_size) % PAGE_SIZE == 0 && addr % PAGE_SIZE == 0) { flush_buffer_data(false); to_vec->write_portion_async(data, merge_end); merge_end += data->get_length(); return; } while (new_data_size > 0) { size_t copy_data_size = std::min(new_data_size, // The size of the available space in the buffer. buf->get_length() - data_size_in_buf); // We always copy the data to the local buffer and write // the local buffer to disks. The reason of doing so is to // make sure the size and offset of data written to disks // are aligned to the I/O block size. memcpy(buf->get(data_size_in_buf), data->get(off_in_new_data), copy_data_size * buf->get_entry_size()); data_size_in_buf += copy_data_size; // Update the amount of data in the incoming data buffer. off_in_new_data += copy_data_size; new_data_size -= copy_data_size; // If the buffer is full, we need to write it out first. if (data_size_in_buf == buf->get_length()) flush_buffer_data(false); } } EM_vec_store::ptr EM_vec_store::create(safs::file_io_factory::shared_ptr factory, const scalar_type &type) { size_t len = factory->get_file_size(); if (len % type.get_size()) { BOOST_LOG_TRIVIAL(error) << "The file has a wrong length for the vector"; return EM_vec_store::ptr(); } io_set::ptr ios(new io_set(factory)); file_holder::ptr holder = file_holder::create(factory->get_name()); return create(holder, ios, len / type.get_size(), type); } EM_vec_store::ptr EM_vec_store::cast(vec_store::ptr vec) { if (vec->is_in_mem()) { BOOST_LOG_TRIVIAL(error) << "Can't cast an in-mem vector to EM_vec_store"; return EM_vec_store::ptr(); } return std::static_pointer_cast<EM_vec_store>(vec); } EM_vec_store::const_ptr EM_vec_store::cast(vec_store::const_ptr vec) { if (vec->is_in_mem()) { BOOST_LOG_TRIVIAL(error) << "Can't cast an in-mem vector to EM_vec_store"; return EM_vec_store::const_ptr(); } return std::static_pointer_cast<const EM_vec_store>(vec); } EM_vec_store::EM_vec_store(file_holder::ptr holder, io_set::ptr ios, size_t len, const scalar_type &type): vec_store(len, type, false) { this->holder = holder; this->ios = ios; this->file_size = type.get_size() * len; } EM_vec_store::EM_vec_store(const EM_vec_store &store): vec_store( store.get_length(), store.get_type(), false) { holder = store.holder; ios = store.ios; file_size = store.file_size; } EM_vec_store::EM_vec_store(size_t length, const scalar_type &type): vec_store( length, type, false) { // TODO I should provide an SAFS file group. holder = file_holder::create_temp("vec", length * type.get_size(), NULL); safs::file_io_factory::shared_ptr factory = safs::create_io_factory( holder->get_name(), safs::REMOTE_ACCESS); ios = io_set::ptr(new io_set(factory)); file_size = length * type.get_size(); } EM_vec_store::~EM_vec_store() { } size_t EM_vec_store::get_reserved_size() const { return file_size / get_type().get_size(); } bool EM_vec_store::reserve(size_t num_eles) { size_t new_size = num_eles * get_type().get_size(); if (new_size <= file_size) return true; // If the vector has data, we don't need to do anything to reserve space // on disks. When we write data to the location behind the end of the file, // the filesystem will automatically allocate space on disks. // The only problem is that the data will be scattered across the disks // if we don't allocate space in advance. safs::safs_file f(safs::get_sys_RAID_conf(), holder->get_name()); // TODO there is a bug if we resize the physical files. // We don't have to physically resize the file. Maybe it's a little slower. #if 0 bool ret = f.resize(new_size); if (!ret) return false; else { file_size = new_size; return true; } #endif file_size = new_size; return true; } bool EM_vec_store::resize(size_t new_length) { if (new_length == get_length()) return true; size_t tot_len = get_reserved_size(); // We don't want to allocate space when shrinking the vector. if (new_length <= tot_len) return vec_store::resize(new_length); size_t old_length = get_length(); size_t real_length = old_length; if (real_length == 0) real_length = 1; for (; real_length < new_length; real_length *= 2); bool ret = reserve(real_length); if (!ret) return false; else return vec_store::resize(new_length); } namespace { class EM_vec_append_dispatcher: public task_dispatcher { std::vector<vec_store::const_ptr>::const_iterator vec_it; std::vector<vec_store::const_ptr>::const_iterator vec_end; seq_writer &writer; size_t portion_size; off_t local_off; public: EM_vec_append_dispatcher(seq_writer &_writer, std::vector<vec_store::const_ptr>::const_iterator vec_start, std::vector<vec_store::const_ptr>::const_iterator vec_end, size_t portion_size): writer(_writer) { this->vec_it = vec_start; this->vec_end = vec_end; this->portion_size = portion_size; this->local_off = 0; } virtual bool issue_task(); }; bool EM_vec_append_dispatcher::issue_task() { if (vec_it == vec_end) { writer.flush_buffer_data(true); return false; } vec_store::const_ptr vec = *vec_it; size_t size; off_t local_curr_off = local_off; if (portion_size >= vec->get_length() - local_off) { size = vec->get_length() - local_off; vec_it++; local_off = 0; } else { size = portion_size; local_off += portion_size; } // TODO we might want to read portion asynchronously. local_vec_store::const_ptr lstore = vec->get_portion(local_curr_off, size); writer.append(lstore); return true; } } bool EM_vec_store::append_async( std::vector<vec_store::const_ptr>::const_iterator vec_start, std::vector<vec_store::const_ptr>::const_iterator vec_end) { size_t entry_size = get_type().get_size(); if ((get_length() * entry_size) % PAGE_SIZE) { BOOST_LOG_TRIVIAL(error) << "The vector needs to have filled the last page"; return false; } size_t tot_size = 0; for (auto it = vec_start; it != vec_end; it++) { auto vec = *it; tot_size += vec->get_length(); if (get_type() != vec->get_type() || (vec->get_length() * entry_size) % PAGE_SIZE || !vec->is_in_mem() || vec->get_num_nodes() > 0) { BOOST_LOG_TRIVIAL(error) << "can't append a vector with different type\n" << "or with the size not aligned with the page size\n" << "or stored on disks or in NUMA memory\n"; return false; } } bool ret = reserve(get_length() + tot_size); if (!ret) { BOOST_LOG_TRIVIAL(error) << "can't reserve space for new appends"; return false; } size_t off = get_length(); for (auto it = vec_start; it != vec_end; it++) { auto vec = *it; // The input vectors might be local vectors. local_vec_store::const_ptr data = std::dynamic_pointer_cast<const local_vec_store>(vec); if (data == NULL) data = vec->get_portion(0, vec->get_length()); assert(((long) data->get_raw_arr()) % PAGE_SIZE == 0); // We need to make sure that the memory in the original input // vector exists until the write completes. portion_compute::ptr compute(new portion_write_complete(vec)); write_portion_async(data, compute, off); off += data->get_length(); } return vec_store::resize(get_length() + tot_size); } bool EM_vec_store::append( std::vector<vec_store::const_ptr>::const_iterator vec_start, std::vector<vec_store::const_ptr>::const_iterator vec_end) { size_t tot_size = 0; for (auto it = vec_start; it != vec_end; it++) { tot_size += (*it)->get_length(); if (get_type() != (*it)->get_type()) { BOOST_LOG_TRIVIAL(error) << "can't append a vector with different type"; return false; } } bool ret = reserve(get_length() + tot_size); if (!ret) { BOOST_LOG_TRIVIAL(error) << "can't reserve space for new appends"; return false; } /* * If the last page that stores the elements in the vector isn't full, * we need to read the last page first. */ // In the number of bytes. off_t off = ROUND(get_length() * get_entry_size(), PAGE_SIZE); size_t size = get_length() * get_entry_size() - off; assert(off % get_entry_size() == 0); seq_writer writer(EM_vec_store::ptr(this, empty_free()), off / get_entry_size()); if (size > 0) { local_vec_store::ptr portion = get_portion(off / get_entry_size(), size / get_entry_size()); writer.append(portion); } size_t portion_size = matrix_conf.get_stream_io_size() / get_type().get_size(); task_dispatcher::ptr dispatcher(new EM_vec_append_dispatcher(writer, vec_start, vec_end, portion_size)); io_worker_task worker(dispatcher, 1); worker.register_EM_obj(this); worker.run(); return vec_store::resize(get_length() + tot_size); } bool EM_vec_store::append(const vec_store &vec) { struct deleter { void operator()(const vec_store *) { } }; std::vector<vec_store::const_ptr> vecs(1); vecs[0] = vec_store::const_ptr(&vec, deleter()); return append(vecs.begin(), vecs.end()); } namespace { class EM_vec_copy_write: public portion_compute { local_buf_vec_store::const_ptr store; EM_vec_store &to_vec; public: EM_vec_copy_write(EM_vec_store &_to_vec): to_vec(_to_vec) { } void set_buf(local_buf_vec_store::const_ptr store) { this->store = store; } virtual void run(char *buf, size_t size) { assert(store); assert(store->get_raw_arr() == buf); assert(store->get_length() * store->get_entry_size() == size); to_vec.write_portion_async(store); } }; class EM_vec_copy_dispatcher: public EM_vec_dispatcher { EM_vec_store &to_vec; public: EM_vec_copy_dispatcher(const EM_vec_store &from_store, EM_vec_store &_to_vec, size_t portion_size): EM_vec_dispatcher( from_store, portion_size), to_vec(_to_vec) { } virtual void create_vec_task(off_t global_start, size_t orig_length, const EM_vec_store &from_vec) { // If the length of the vector isn't aligned with the page size, // the underlying file is extended a little. size_t entry_size = from_vec.get_type().get_size(); assert(round_ele(global_start, PAGE_SIZE, entry_size) == global_start); size_t length = roundup_ele(orig_length, PAGE_SIZE, entry_size); EM_vec_copy_write *compute = new EM_vec_copy_write(to_vec); local_buf_vec_store::ptr buf = from_vec.get_portion_async( global_start, length, portion_compute::ptr(compute)); compute->set_buf(buf); } }; } vec_store::ptr EM_vec_store::deep_copy() const { // TODO we might need to give users the optional to config it. const size_t copy_portion_size = 128 * 1024 * 1024; EM_vec_store::ptr new_vec = EM_vec_store::create(get_length(), get_type()); EM_vec_copy_dispatcher::ptr copy_dispatcher( new EM_vec_copy_dispatcher(*this, *new_vec, copy_portion_size)); // The buffer size is large, we don't need some many async I/Os. io_worker_task sort_worker(copy_dispatcher, 1); sort_worker.register_EM_obj(const_cast<EM_vec_store *>(this)); sort_worker.register_EM_obj(new_vec.get()); sort_worker.run(); return new_vec; } vec_store::ptr EM_vec_store::shallow_copy() { return vec_store::ptr(new EM_vec_store(*this)); } vec_store::const_ptr EM_vec_store::shallow_copy() const { return vec_store::ptr(new EM_vec_store(*this)); } size_t EM_vec_store::get_portion_size() const { // TODO return 1024 * 1024; } local_vec_store::ptr EM_vec_store::get_portion_async(off_t orig_start, size_t orig_size, portion_compute::ptr compute) const { size_t entry_size = get_type().get_size(); off_t start = round_ele(orig_start, PAGE_SIZE, entry_size); size_t size = orig_size + (orig_start - start); size = roundup_ele(size, PAGE_SIZE, entry_size); // TODO fix the bug if `start' and `size' aren't aligned with PAGE_SIZE. safs::io_interface &io = ios->get_curr_io(); local_buf_vec_store::ptr buf(new local_buf_vec_store(start, size, get_type(), -1)); off_t off = start * entry_size; safs::data_loc_t loc(io.get_file_id(), off); safs::io_request req(buf->get_raw_arr(), loc, buf->get_length() * buf->get_entry_size(), READ); static_cast<portion_callback &>(io.get_callback()).add(req, compute); io.access(&req, 1); io.flush_requests(); if (orig_start != start || orig_size != size) buf->expose_sub_vec(orig_start - start, orig_size); return buf; } std::vector<local_vec_store::ptr> EM_vec_store::get_portion_async( const std::vector<std::pair<off_t, size_t> > &locs, portion_compute::ptr compute) const { size_t entry_size = get_type().get_size(); // TODO fix the bug if `locs' aren't aligned with PAGE_SIZE. safs::io_interface &io = ios->get_curr_io(); std::vector<safs::io_request> reqs(locs.size()); std::vector<local_vec_store::ptr> ret_bufs(locs.size()); for (size_t i = 0; i < locs.size(); i++) { off_t start = round_ele(locs[i].first, PAGE_SIZE, entry_size); size_t size = locs[i].second + (locs[i].first - start); size = roundup_ele(size, PAGE_SIZE, entry_size); local_buf_vec_store::ptr buf(new local_buf_vec_store(start, size, get_type(), -1)); off_t off = start * entry_size; safs::data_loc_t loc(io.get_file_id(), off); reqs[i] = safs::io_request(buf->get_raw_arr(), loc, buf->get_length() * buf->get_entry_size(), READ); static_cast<portion_callback &>(io.get_callback()).add(reqs[i], compute); if (locs[i].first != start || locs[i].second != size) buf->expose_sub_vec(locs[i].first - start, locs[i].second); ret_bufs[i] = buf; } io.access(reqs.data(), reqs.size()); io.flush_requests(); return ret_bufs; } bool EM_vec_store::set_portion(std::shared_ptr<const local_vec_store> store, off_t loc) { if (store->get_type() != get_type()) { BOOST_LOG_TRIVIAL(error) << "The input store has a different type"; return false; } if (loc + store->get_length() > get_length()) { BOOST_LOG_TRIVIAL(error) << "out of boundary"; return false; } write_portion_async(store, loc); safs::io_interface &io = ios->get_curr_io(); io.wait4complete(1); return true; } local_vec_store::const_ptr EM_vec_store::get_portion(off_t loc, size_t size) const { return const_cast<EM_vec_store *>(this)->get_portion(loc, size); } local_vec_store::ptr EM_vec_store::get_portion(off_t orig_loc, size_t orig_size) { if (orig_loc + orig_size > get_length()) { BOOST_LOG_TRIVIAL(error) << "get_portion: out of boundary"; return local_vec_store::ptr(); } size_t entry_size = get_type().get_size(); off_t loc = round_ele(orig_loc, PAGE_SIZE, entry_size); size_t size = orig_size + (orig_loc - loc); size = roundup_ele(size, PAGE_SIZE, entry_size); safs::io_interface &io = ios->get_curr_io(); bool ready = false; portion_compute::ptr compute(new sync_read_compute(ready)); local_vec_store::ptr ret = get_portion_async(loc, size, compute); while (!ready) io.wait4complete(1); if (orig_loc != loc || orig_size != size) ret->expose_sub_vec(orig_loc - loc, orig_size); return ret; } void EM_vec_store::write_portion_async(local_vec_store::const_ptr store, portion_compute::ptr compute, off_t off) { off_t start = off; if (start < 0) start = store->get_global_start(); assert(start >= 0); safs::io_interface &io = ios->get_curr_io(); off_t off_in_bytes = start * get_type().get_size(); safs::data_loc_t loc(io.get_file_id(), off_in_bytes); safs::io_request req(const_cast<char *>(store->get_raw_arr()), loc, store->get_length() * store->get_entry_size(), WRITE); static_cast<portion_callback &>(io.get_callback()).add(req, compute); io.access(&req, 1); // TODO I might want to flush requests later. io.flush_requests(); } void EM_vec_store::write_portion_async(local_vec_store::const_ptr store, off_t off) { portion_compute::ptr compute(new portion_write_complete(store)); write_portion_async(store, compute, off); } void EM_vec_store::reset_data() { assert(0); } vec_store::ptr EM_vec_store::sort_with_index() { assert(0); } std::vector<safs::io_interface::ptr> EM_vec_store::create_ios() const { std::vector<safs::io_interface::ptr> ret(1); ret[0] = ios->create_io(); return ret; } ///////////////////////////// Sort the vector ///////////////////////////////// namespace EM_sort_detail { anchor_prio_queue::anchor_prio_queue( const std::vector<local_buf_vec_store::ptr> &anchor_vals, size_t _sort_buf_size, size_t _anchor_gap_size): sort_buf_size( _sort_buf_size), anchor_gap_size(_anchor_gap_size), queue( anchor_ptr_less(anchor_vals.front()->get_type())) { anchor_bufs.resize(anchor_vals.size()); for (size_t i = 0; i < anchor_vals.size(); i++) { anchor_struct anchor; anchor.local_anchors = anchor_vals[i]; anchor.id = i; anchor.curr_off = 0; anchor_bufs[i] = anchor; queue.push(&anchor_bufs[i]); } } off_t anchor_prio_queue::get_anchor_off(const anchor_struct &anchor) const { return anchor.id * sort_buf_size + anchor.curr_off * anchor_gap_size; } /* * By looking into the values in the anchor locations, we can know immediately * the minimal value among the data that hasn't been read. */ scalar_variable::ptr anchor_prio_queue::get_min_frontier() const { if (queue.empty()) return scalar_variable::ptr(); else { local_buf_vec_store::const_ptr local_anchors = queue.top()->local_anchors; const scalar_type &type = local_anchors->get_type(); scalar_variable::ptr var = type.create_scalar(); assert((size_t) queue.top()->curr_off < local_anchors->get_length()); var->set_raw(local_anchors->get(queue.top()->curr_off), type.get_size()); return var; } } /* * Here we pop a set of chunks of data whose values are the potentially * the smallest. */ std::vector<off_t> anchor_prio_queue::pop(size_t size) { std::vector<off_t> chunks; long remaining_size = size; while (remaining_size > 0 && !queue.empty()) { anchor_struct *anchor = queue.top(); assert((size_t) anchor->curr_off < anchor->local_anchors->get_length()); off_t off = get_anchor_off(*anchor); chunks.push_back(off); remaining_size -= anchor_gap_size; queue.pop(); // If there are still anchors left in the partition, we should // update it and put it back to the priority. anchor->curr_off++; if (anchor->local_anchors->get_length() > (size_t) anchor->curr_off) queue.push(anchor); } return chunks; } std::vector<off_t> anchor_prio_queue::fetch_all_first() { std::vector<off_t> chunks; for (size_t i = 0; i < anchor_bufs.size(); i++) { anchor_struct &anchor = anchor_bufs[i]; if (anchor.local_anchors->get_length() > (size_t) anchor.curr_off) { off_t off = get_anchor_off(anchor); chunks.push_back(off); anchor.curr_off++; } } // We have change the anchor structs, now we have reconstruct // the priority queue again. queue = anchor_queue_t(anchor_ptr_less( anchor_bufs.front().local_anchors->get_type())); assert(queue.empty()); for (size_t i = 0; i < anchor_bufs.size(); i++) { anchor_struct *anchor = &anchor_bufs[i]; if (anchor->local_anchors->get_length() > (size_t) anchor->curr_off) queue.push(anchor); } return chunks; } sort_portion_summary::sort_portion_summary(size_t num_sort_bufs, size_t _sort_buf_size, size_t _anchor_gap_size): sort_buf_size( _sort_buf_size), anchor_gap_size(_anchor_gap_size) { anchor_vals.resize(num_sort_bufs); } void sort_portion_summary::add_portion(local_buf_vec_store::const_ptr sorted_buf) { std::vector<off_t> idxs; for (size_t i = 0; i < sorted_buf->get_length(); i += anchor_gap_size) idxs.push_back(i); // assert(idxs.back() < sorted_buf->get_length()); // if ((size_t) idxs.back() != sorted_buf->get_length() - 1) // idxs.push_back(sorted_buf->get_length() - 1); // assert(idxs.back() < sorted_buf->get_length()); off_t idx = sorted_buf->get_global_start() / sort_buf_size; assert(anchor_vals[idx] == NULL); anchor_vals[idx] = sorted_buf->get(idxs); if ((size_t) idx == anchor_vals.size() - 1) assert(sorted_buf->get_length() <= sort_buf_size); else assert(sorted_buf->get_length() == sort_buf_size); } anchor_prio_queue::ptr sort_portion_summary::get_prio_queue() const { return anchor_prio_queue::ptr(new anchor_prio_queue(anchor_vals, sort_buf_size, anchor_gap_size)); } void EM_vec_sort_compute::run(char *buf, size_t size) { num_completed++; if (num_completed == portions.size()) { // Sort each portion in parallel. // Here we rely on OpenMP to sort the data in the buffer in parallel. local_buf_vec_store::ptr sort_buf = portions.front(); std::vector<off_t> orig_offs(sort_buf->get_length()); sort_buf->get_type().get_sorter().sort_with_index( sort_buf->get_raw_arr(), orig_offs.data(), sort_buf->get_length(), false); summary.add_portion(sort_buf); // It might be a sub vector, we should reset its exposed part, so // the size of data written to disks is aligned to the page size. sort_buf->reset_expose(); // Write the sorting result to disks. to_vecs.front()->write_portion_async(sort_buf); for (size_t i = 1; i < portions.size(); i++) { portions[i]->reset_expose(); // If the element size is different in each array, the padding // size might also be different. We should make the elements // in the padding area are mapped to the same locations. size_t off = orig_offs.size(); orig_offs.resize(portions[i]->get_length()); if (off < orig_offs.size()) { for (; off < orig_offs.size(); off++) orig_offs[off] = off; } local_vec_store::ptr shuffle_buf = portions[i]->get(orig_offs); to_vecs[i]->write_portion_async(shuffle_buf, portions[i]->get_global_start()); } } } class EM_vec_sort_dispatcher: public EM_vec_dispatcher { std::shared_ptr<sort_portion_summary> summary; std::vector<EM_vec_store::const_ptr> from_vecs; std::vector<EM_vec_store::ptr> to_vecs; public: typedef std::shared_ptr<EM_vec_sort_dispatcher> ptr; EM_vec_sort_dispatcher(const std::vector<EM_vec_store::const_ptr> &from_vecs, const std::vector<EM_vec_store::ptr> &to_vecs, size_t sort_buf_size, size_t anchor_gap_size); const sort_portion_summary &get_sort_summary() const { return *summary; } virtual void create_vec_task(off_t global_start, size_t length, const EM_vec_store &from_vec); }; EM_vec_sort_dispatcher::EM_vec_sort_dispatcher( const std::vector<EM_vec_store::const_ptr> &from_vecs, const std::vector<EM_vec_store::ptr> &to_vecs, size_t sort_buf_size, size_t anchor_gap_size): EM_vec_dispatcher( *from_vecs.front(), sort_buf_size) { EM_vec_store::const_ptr sort_vec = from_vecs.front(); size_t num_sort_bufs = ceil(((double) sort_vec->get_length()) / sort_buf_size); summary = std::shared_ptr<sort_portion_summary>( new sort_portion_summary(num_sort_bufs, sort_buf_size, anchor_gap_size)); this->from_vecs = from_vecs; this->to_vecs = to_vecs; } void EM_vec_sort_dispatcher::create_vec_task(off_t global_start, size_t orig_length, const EM_vec_store &from_vec) { EM_vec_sort_compute *sort_compute = new EM_vec_sort_compute(to_vecs, *summary); portion_compute::ptr compute(sort_compute); std::vector<local_vec_store::ptr> from_portions(from_vecs.size()); for (size_t i = 0; i < from_portions.size(); i++) { size_t entry_size = from_vecs[i]->get_type().get_size(); assert(round_ele(global_start, PAGE_SIZE, entry_size) == global_start); size_t length = roundup_ele(orig_length, PAGE_SIZE, entry_size); from_portions[i] = from_vecs[i]->get_portion_async( global_start, length, compute); from_portions[i]->expose_sub_vec(0, orig_length); } sort_compute->set_bufs(from_portions); } /////////////////// Merge portions /////////////////////// class EM_vec_merge_dispatcher: public task_dispatcher { std::vector<EM_vec_store::const_ptr> from_vecs; std::vector<local_buf_vec_store::ptr> prev_leftovers; anchor_prio_queue::ptr anchors; size_t sort_buf_size; std::vector<seq_writer> writers; public: EM_vec_merge_dispatcher(const std::vector<EM_vec_store::const_ptr> &from_vecs, const std::vector<EM_vec_store::ptr> &to_vecs, anchor_prio_queue::ptr anchors, size_t sort_buf_size); void set_prev_leftovers( const std::vector<local_buf_vec_store::ptr> &prev_leftovers) { this->prev_leftovers = prev_leftovers; } local_buf_vec_store::const_ptr get_prev_leftover(off_t idx) const { return prev_leftovers[idx]; } seq_writer &get_merge_writer(int idx) { return writers[idx]; } const anchor_prio_queue &get_anchors() const { return *anchors; } virtual bool issue_task(); }; EM_vec_merge_compute::EM_vec_merge_compute( const std::vector<local_buf_vec_store::ptr> &prev_leftovers, EM_vec_merge_dispatcher &_dispatcher): dispatcher(_dispatcher) { stores.resize(prev_leftovers.size()); for (size_t i = 0; i < prev_leftovers.size(); i++) { // If there is a leftover for a vector from the previous merge, // all vectors should have the same number of leftover elements. if (prev_leftovers[0]) { assert(prev_leftovers[i]); assert(prev_leftovers[0]->get_length() == prev_leftovers[i]->get_length()); } if (prev_leftovers[i]) this->stores[i].push_back(prev_leftovers[i]); } num_completed = 0; } void EM_vec_merge_compute::set_bufs(const std::vector<merge_set_t> &bufs) { assert(bufs.size() == stores.size()); num_expected = 0; for (size_t i = 0; i < bufs.size(); i++) { // If all vectors should have the same number of buffers to merge. assert(bufs[0].size() == bufs[i].size()); num_expected += bufs[i].size(); this->stores[i].insert(this->stores[i].end(), bufs[i].begin(), bufs[i].end()); } } EM_vec_merge_dispatcher::EM_vec_merge_dispatcher( const std::vector<EM_vec_store::const_ptr> &from_vecs, const std::vector<EM_vec_store::ptr> &to_vecs, anchor_prio_queue::ptr anchors, size_t _sort_buf_size): sort_buf_size( _sort_buf_size) { this->from_vecs = from_vecs; assert(from_vecs.size() == to_vecs.size()); for (size_t i = 0; i < from_vecs.size(); i++) assert(from_vecs[i]->get_type() == to_vecs[i]->get_type()); this->anchors = anchors; for (size_t i = 0; i < to_vecs.size(); i++) writers.emplace_back(to_vecs[i], 0); prev_leftovers.resize(from_vecs.size()); } bool EM_vec_merge_dispatcher::issue_task() { typedef std::vector<local_buf_vec_store::const_ptr> merge_set_t; size_t leftover = 0; assert(!prev_leftovers.empty()); std::vector<off_t> anchor_locs; size_t anchor_gap_size = anchors->get_anchor_gap_size(); if (prev_leftovers[0]) { leftover = prev_leftovers[0]->get_length(); if (sort_buf_size <= leftover) BOOST_LOG_TRIVIAL(info) << boost::format("leftover (%1%) is larger than sort buf size (%2%)") % leftover % sort_buf_size; size_t pop_size; if (sort_buf_size > leftover) pop_size = sort_buf_size - leftover; else pop_size = anchor_gap_size; anchor_locs = anchors->pop(pop_size); } else { anchor_locs = anchors->fetch_all_first(); size_t fetch_size = anchor_locs.size() * anchor_gap_size; if (fetch_size < sort_buf_size) { std::vector<off_t> more_locs = anchors->pop( sort_buf_size - fetch_size); anchor_locs.insert(anchor_locs.end(), more_locs.begin(), more_locs.end()); } } // If there isn't any data to merge and there isn't leftover from // the previous merge. if (anchor_locs.empty() && prev_leftovers[0] == NULL) { assert(anchors->get_min_frontier() == NULL); assert(leftover == 0); // If there is nothing left to merge and there isn't leftover, we still // need to flush the buffered data. for (size_t i = 0; i < writers.size(); i++) writers[i].flush_buffer_data(true); return false; } else { // Merge the anchors. std::vector<std::pair<off_t, size_t> > data_locs; std::sort(anchor_locs.begin(), anchor_locs.end()); for (size_t i = 0; i < anchor_locs.size(); i++) { size_t num_eles = std::min(anchor_gap_size, from_vecs[0]->get_length() - anchor_locs[i]); size_t off = anchor_locs[i]; // If the anchors are contiguous, we merge them. while (i + 1 < anchor_locs.size() && (size_t) anchor_locs[i + 1] == anchor_locs[i] + anchor_gap_size) { i++; num_eles += std::min(anchor_gap_size, from_vecs[0]->get_length() - anchor_locs[i]); } data_locs.push_back(std::pair<off_t, size_t>(off, num_eles)); } // In this case, we need to read some data from the disks first and then // merge with the data left from the previous merge. if (!data_locs.empty()) { EM_vec_merge_compute *_compute = new EM_vec_merge_compute( prev_leftovers, *this); portion_compute::ptr compute(_compute); std::vector<merge_set_t> merge_sets(from_vecs.size()); for (size_t j = 0; j < from_vecs.size(); j++) { std::vector<local_vec_store::ptr> portions = from_vecs[j]->get_portion_async(data_locs, compute); merge_sets[j].insert(merge_sets[j].end(), portions.begin(), portions.end()); } _compute->set_bufs(merge_sets); } // In this case, we don't need to read data from disks any more. // We only need to write the data left from the previous merge. else { for (size_t i = 0; i < writers.size(); i++) { if (prev_leftovers[i]) writers[i].append(prev_leftovers[i]); // This is the last write. we should flush everything to disks. writers[i].flush_buffer_data(true); // No more leftover. prev_leftovers[i] = NULL; } } return true; } } void EM_vec_merge_compute::run(char *buf, size_t size) { num_completed++; // If all data in the buffers is ready, we should merge all the buffers. if (num_completed == num_expected) { assert(stores.size() > 0); merge_set_t &merge_bufs = stores[0]; // Find the min values among the last elements in the buffers. const scalar_type &type = merge_bufs.front()->get_type(); scalar_variable::ptr min_val = dispatcher.get_anchors().get_min_frontier(); // Breaks the local buffers into two parts. The first part is to // merge with others; we have to keep the second part for further // merging. std::vector<std::pair<const char *, const char *> > merge_data; std::vector<std::pair<const char *, const char *> > leftovers; std::vector<size_t> merge_sizes(merge_bufs.size()); size_t leftover_size = 0; size_t merge_size = 0; local_buf_vec_store::const_ptr prev_leftover = dispatcher.get_prev_leftover(0); agg_operate::const_ptr find_next = type.get_agg_ops().get_find_next(); // We go through all the buffers to be merged and merge elements // that are smaller than `min_val' and keep all elements in the `leftover' // buffer, which have been read from the disks but are larger than // `min_val'. for (size_t i = 0; i < merge_bufs.size(); i++) { size_t entry_size = merge_bufs[i]->get_entry_size(); const size_t tot_len = merge_bufs[i]->get_length(); const char *start = merge_bufs[i]->get_raw_arr(); const char *end = merge_bufs[i]->get_raw_arr() + tot_len * entry_size; off_t leftover_start; if (min_val != NULL) { leftover_start = type.get_stl_algs().lower_bound( start, end, min_val->get_raw()); // lower_bound finds the location so that all elements before // the location have values smaller than `min_val'. Actually, // we can also merge all elements whose value is equal to // `min_val'. if ((size_t) leftover_start < tot_len && min_val->equals(start + leftover_start * entry_size)) { size_t rel_loc; find_next->runAgg(tot_len - leftover_start, start + leftover_start * entry_size, &rel_loc); // There is at least one element with the same value as // `min_val'. assert(rel_loc > 0 && rel_loc <= tot_len - leftover_start); leftover_start += rel_loc; } assert((size_t) leftover_start <= tot_len); } else leftover_start = tot_len; assert((size_t) leftover_start <= tot_len); merge_sizes[i] = leftover_start; merge_size += leftover_start; leftover_size += (tot_len - leftover_start); if (leftover_start > 0) merge_data.push_back(std::pair<const char *, const char *>( merge_bufs[i]->get(0), merge_bufs[i]->get(leftover_start))); if (tot_len - leftover_start) leftovers.push_back(std::pair<const char *, const char *>( merge_bufs[i]->get(leftover_start), merge_bufs[i]->get(tot_len))); } // Here we rely on OpenMP to merge the data in the buffer in parallel. local_buf_vec_store::ptr merge_res(new local_buf_vec_store(-1, merge_size, type, -1)); std::vector<std::pair<int, off_t> > merge_index(merge_size); type.get_sorter().merge_with_index(merge_data, merge_res->get_raw_arr(), merge_size, merge_index); // Write the merge result to disks. dispatcher.get_merge_writer(0).append(merge_res); merge_res = NULL; std::vector<std::pair<int, off_t> > leftover_merge_index(leftover_size); std::vector<local_buf_vec_store::ptr> leftover_bufs(stores.size()); if (leftover_size > 0) { // Keep the leftover and merge them into a single buffer. local_buf_vec_store::ptr leftover_buf = local_buf_vec_store::ptr( new local_buf_vec_store(-1, leftover_size, type, -1)); type.get_sorter().merge_with_index(leftovers, leftover_buf->get_raw_arr(), leftover_size, leftover_merge_index); leftover_bufs[0] = leftover_buf; } // Merge the remaining vectors accordingly. for (size_t i = 1; i < stores.size(); i++) { std::vector<std::pair<const char *, const char *> > merge_data; std::vector<std::pair<const char *, const char *> > leftovers; merge_set_t &set = stores[i]; assert(set.size() == merge_bufs.size()); for (size_t i = 0; i < set.size(); i++) { off_t leftover_start = merge_sizes[i]; assert(set[i]->get_length() == merge_bufs[i]->get_length()); if (leftover_start > 0) merge_data.push_back(std::pair<const char *, const char *>( set[i]->get(0), set[i]->get(leftover_start))); if (set[i]->get_length() - leftover_start) leftovers.push_back(std::pair<const char *, const char *>( set[i]->get(leftover_start), set[i]->get(set[i]->get_length()))); } // Merge the part that can be merged. const scalar_type &type = set.front()->get_type(); merge_res = local_buf_vec_store::ptr(new local_buf_vec_store(-1, merge_size, type, -1)); type.get_sorter().merge(merge_data, merge_index, merge_res->get_raw_arr(), merge_size); dispatcher.get_merge_writer(i).append(merge_res); if (leftover_size > 0) { // Keep the leftover and merge them into a single buffer. local_buf_vec_store::ptr leftover_buf = local_buf_vec_store::ptr( new local_buf_vec_store(-1, leftover_size, type, -1)); type.get_sorter().merge(leftovers, leftover_merge_index, leftover_buf->get_raw_arr(), leftover_size); leftover_bufs[i] = leftover_buf; } } dispatcher.set_prev_leftovers(leftover_bufs); } } /* * The two functions compute the sort buffer size and the anchor gap size * based on the sort buffer size and min I/O size provided by the user. * One version works for a single vector and the other version works for * multiple vectors. * * The anchor gap size should be multiple of the entry sizes of all * vectors as well as multiple of the min I/O size. * The sort buffer size should be multiple of the anchor gap size. */ std::pair<size_t, size_t> cal_sort_buf_size(const scalar_type &type, size_t num_eles) { size_t min_anchor_gap_bytes = 1; // in the number of bytes. min_anchor_gap_bytes = boost::math::lcm(min_anchor_gap_bytes, type.get_size()); min_anchor_gap_bytes = boost::math::lcm(min_anchor_gap_bytes, (size_t) PAGE_SIZE); assert(min_anchor_gap_bytes % type.get_size() == 0); assert(min_anchor_gap_bytes % PAGE_SIZE == 0); // The number of elements between two anchors. size_t min_anchor_gap_size = min_anchor_gap_bytes / type.get_size(); size_t num_anchors = matrix_conf.get_sort_buf_size() / type.get_size() / min_anchor_gap_size; size_t sort_buf_size = num_anchors * min_anchor_gap_size; assert((sort_buf_size * type.get_size()) % PAGE_SIZE == 0); // Find the maximal size of anchor gap size allowed for the sort buffer // size and the vector length. assert(sort_buf_size % min_anchor_gap_size == 0); size_t num_sort_bufs = ceil(((double) num_eles) / sort_buf_size); size_t num_min_anchors = sort_buf_size / min_anchor_gap_size; size_t factor = sort_buf_size / num_sort_bufs / min_anchor_gap_size; for (; factor > 0; factor--) if (num_min_anchors % factor == 0) break; assert(factor != 0); return std::pair<size_t, size_t>(sort_buf_size, min_anchor_gap_size * factor); } std::pair<size_t, size_t> cal_sort_buf_size( const std::vector<const scalar_type *> &types, size_t num_eles) { size_t tot_entry_size = 0; size_t min_anchor_gap_bytes = 1; // in the number of bytes. for (size_t i = 0; i < types.size(); i++) { tot_entry_size += types[i]->get_size(); min_anchor_gap_bytes = boost::math::lcm(min_anchor_gap_bytes, types[i]->get_size()); } min_anchor_gap_bytes = boost::math::lcm(min_anchor_gap_bytes, (size_t) PAGE_SIZE); for (size_t i = 0; i < types.size(); i++) { assert(min_anchor_gap_bytes % types[i]->get_size() == 0); } assert(min_anchor_gap_bytes % PAGE_SIZE == 0); // The number of elements between two anchors. size_t min_anchor_gap_size = min_anchor_gap_bytes / types[0]->get_size(); size_t num_anchors = matrix_conf.get_sort_buf_size() / tot_entry_size / min_anchor_gap_size; size_t sort_buf_size = num_anchors * min_anchor_gap_size; for (size_t i = 0; i < types.size(); i++) assert((sort_buf_size * types[i]->get_size()) % PAGE_SIZE == 0); // Find the maximal size of anchor gap size allowed for the sort buffer // size and the vector length. assert(sort_buf_size % min_anchor_gap_size == 0); size_t num_sort_bufs = ceil(((double) num_eles) / sort_buf_size); size_t num_min_anchors = sort_buf_size / min_anchor_gap_size; size_t factor = sort_buf_size / num_sort_bufs / min_anchor_gap_size; for (; factor > 0; factor--) if (num_min_anchors % factor == 0) break; assert(factor != 0); return std::pair<size_t, size_t>(sort_buf_size, min_anchor_gap_size * factor); } } std::vector<EM_vec_store::ptr> sort( const std::vector<EM_vec_store::const_ptr> &vecs) { assert(vecs.size() > 0); for (size_t i = 1; i < vecs.size(); i++) { if (vecs[i]->get_length() != vecs[0]->get_length()) { BOOST_LOG_TRIVIAL(error) << "Not all vectors have the same length"; return std::vector<EM_vec_store::ptr>(); } } std::vector<const scalar_type *> types(vecs.size()); for (size_t i = 0; i < vecs.size(); i++) types[i] = &vecs[i]->get_type(); std::pair<size_t, size_t> sizes = EM_sort_detail::cal_sort_buf_size(types, vecs.front()->get_length()); size_t sort_buf_size = sizes.first; size_t anchor_gap_size = sizes.second; printf("sort buf size: %ld, anchor gap size: %ld\n", sort_buf_size, anchor_gap_size); for (size_t i = 0; i < vecs.size(); i++) { size_t num_sort_bufs = ceil(((double) vecs[i]->get_length()) / sort_buf_size); // We have to make sure the sort buffer can contain a anchor portion // from each partially sorted buffer. assert(num_sort_bufs * anchor_gap_size <= sort_buf_size); } /* * Divide the vector into multiple large parts and sort each part in parallel. */ std::vector<EM_vec_store::ptr> tmp_vecs(vecs.size()); for (size_t i = 0; i < vecs.size(); i++) tmp_vecs[i] = EM_vec_store::create(vecs[i]->get_length(), vecs[i]->get_type()); EM_sort_detail::EM_vec_sort_dispatcher::ptr sort_dispatcher( new EM_sort_detail::EM_vec_sort_dispatcher(vecs, tmp_vecs, sort_buf_size, anchor_gap_size)); io_worker_task sort_worker(sort_dispatcher, 1); for (size_t i = 0; i < vecs.size(); i++) { sort_worker.register_EM_obj(const_cast<EM_vec_store *>(vecs[i].get())); sort_worker.register_EM_obj(tmp_vecs[i].get()); } sort_worker.run(); /* Merge all parts. * Here we assume that one level of merging is enough and we rely on * OpenMP to parallelize merging. */ std::vector<EM_vec_store::ptr> out_vecs(vecs.size()); for (size_t i = 0; i < vecs.size(); i++) out_vecs[i] = EM_vec_store::create(vecs[i]->get_length(), vecs[i]->get_type()); std::vector<EM_vec_store::const_ptr> tmp_vecs1(tmp_vecs.begin(), tmp_vecs.end()); EM_sort_detail::EM_vec_merge_dispatcher::ptr merge_dispatcher( new EM_sort_detail::EM_vec_merge_dispatcher(tmp_vecs1, out_vecs, sort_dispatcher->get_sort_summary().get_prio_queue(), sort_buf_size)); // TODO let's not use asynchornous I/O for now. io_worker_task merge_worker(merge_dispatcher, 0); for (size_t i = 0; i < vecs.size(); i++) { merge_worker.register_EM_obj(tmp_vecs[i].get()); merge_worker.register_EM_obj(out_vecs[i].get()); } merge_worker.run(); return out_vecs; } void EM_vec_store::sort() { std::pair<size_t, size_t> sizes = EM_sort_detail::cal_sort_buf_size(get_type(), get_length()); size_t sort_buf_size = sizes.first; size_t anchor_gap_size = sizes.second; size_t num_sort_bufs = ceil(((double) get_length()) / sort_buf_size); printf("sort buf size: %ld, anchor gap size: %ld\n", sort_buf_size, anchor_gap_size); // We have to make sure the sort buffer can contain a anchor portion // from each partially sorted buffer. assert(num_sort_bufs * anchor_gap_size <= sort_buf_size); /* * Divide the vector into multiple large parts and sort each part in parallel. */ std::vector<EM_vec_store::const_ptr> in_vecs(1); std::vector<EM_vec_store::ptr> out_vecs(1); in_vecs[0] = EM_vec_store::const_ptr(this, empty_free()); out_vecs[0] = EM_vec_store::ptr(this, empty_free()); EM_sort_detail::EM_vec_sort_dispatcher::ptr sort_dispatcher( new EM_sort_detail::EM_vec_sort_dispatcher(in_vecs, out_vecs, sort_buf_size, anchor_gap_size)); io_worker_task sort_worker(sort_dispatcher, 1); sort_worker.register_EM_obj(this); sort_worker.run(); /* Merge all parts. * Here we assume that one level of merging is enough and we rely on * OpenMP to parallelize merging. */ EM_vec_store::ptr tmp = EM_vec_store::create(get_length(), get_type()); in_vecs[0] = EM_vec_store::const_ptr(this, empty_free()); out_vecs[0] = tmp; EM_sort_detail::EM_vec_merge_dispatcher::ptr merge_dispatcher( new EM_sort_detail::EM_vec_merge_dispatcher(in_vecs, out_vecs, sort_dispatcher->get_sort_summary().get_prio_queue(), sort_buf_size)); // TODO let's not use asynchornous I/O for now. io_worker_task merge_worker(merge_dispatcher, 0); merge_worker.register_EM_obj(this); merge_worker.register_EM_obj(tmp.get()); merge_worker.run(); // In the end, we points to the new file. holder = tmp->holder; ios = tmp->ios; } ////////////////////////// Set data of the vector //////////////////////////// namespace { /* * This class records the summary of the array. It stores three pieces of * information from each portion: the first and last elements in the portion * and a flag that indicates whether the portion is sorted. * This implementation assumes that two levels to test whether an array * is sorted. It is enough for a very large vector. * Although this data structure is shared by all threads, each portion owns * its own elements in the shared vector, so locking isn't needed. */ class issorted_summary { // This stores the elements in the each end of a portion. local_buf_vec_store::ptr ends; // This vector is modified by multiple threads in parallel, so we can't // use a boolean vector, which isn't thread-safe. We should use // thread-safe bitmap. std::vector<int> issorted; size_t portion_size; public: issorted_summary(const EM_vec_store &vec) { size_t num_portions = vec.get_num_portions(); ends = local_vec_store::ptr(new local_buf_vec_store(-1, num_portions * 2, vec.get_type(), -1)); issorted.resize(num_portions); portion_size = vec.get_portion_size(); } void set_portion_result(local_buf_vec_store::const_ptr store) { bool sorted = store->get_type().get_sorter().is_sorted( store->get_raw_arr(), store->get_length(), false); off_t portion_idx = store->get_global_start() / portion_size; assert(portion_idx >= 0 && (size_t) portion_idx < issorted.size()); issorted[portion_idx] = sorted; // Save the elements in each end. assert((size_t) portion_idx * 2 + 1 < ends->get_length()); ends->set_raw(portion_idx * 2, store->get(0)); ends->set_raw(portion_idx * 2 + 1, store->get(store->get_length() - 1)); } bool is_sorted() const { for (size_t i = 0; i < issorted.size(); i++) if (!issorted[i]) return false; bool ret = ends->get_type().get_sorter().is_sorted( ends->get_raw_arr(), ends->get_length(), false); return ret; } }; class EM_vec_issorted_compute: public portion_compute { local_buf_vec_store::const_ptr store; issorted_summary &summary; public: EM_vec_issorted_compute(issorted_summary &_summary): summary(_summary) { } void set_buf(local_buf_vec_store::const_ptr store) { this->store = store; } virtual void run(char *buf, size_t size) { assert(store->get_raw_arr() == buf); summary.set_portion_result(store); } }; } class EM_vec_issorted_dispatcher: public EM_vec_dispatcher { issorted_summary summary; public: typedef std::shared_ptr<EM_vec_issorted_dispatcher> ptr; EM_vec_issorted_dispatcher(const EM_vec_store &store): EM_vec_dispatcher( store), summary(store) { } const issorted_summary &get_summary() const { return summary; } virtual void create_vec_task(off_t global_start, size_t length, const EM_vec_store &from_vec); }; void EM_vec_issorted_dispatcher::create_vec_task(off_t global_start, size_t orig_length, const EM_vec_store &from_vec) { // The vector doesn't necessary have the number of elements to make // the end of the vector aligned with the page size. If it's not, // we should align it. We end up writing more data to the underlying // file. size_t entry_size = from_vec.get_type().get_size(); assert(round_ele(global_start, PAGE_SIZE, entry_size) == global_start); size_t length = roundup_ele(orig_length, PAGE_SIZE, entry_size); EM_vec_issorted_compute *compute = new EM_vec_issorted_compute(summary); local_vec_store::const_ptr portion = from_vec.get_portion_async(global_start, length, portion_compute::ptr(compute)); if (length != orig_length) const_cast<local_vec_store &>(*portion).expose_sub_vec(0, orig_length); compute->set_buf(portion); } bool EM_vec_store::is_sorted() const { mem_thread_pool::ptr threads = mem_thread_pool::get_global_mem_threads(); EM_vec_issorted_dispatcher::ptr dispatcher( new EM_vec_issorted_dispatcher(*this)); for (size_t i = 0; i < threads->get_num_threads(); i++) { io_worker_task *task = new io_worker_task(dispatcher); task->register_EM_obj(const_cast<EM_vec_store *>(this)); threads->process_task(i % threads->get_num_nodes(), task); } threads->wait4complete(); return dispatcher->get_summary().is_sorted(); } ////////////////////////// Set data of the vector //////////////////////////// namespace { class EM_vec_setdata_dispatcher: public EM_vec_dispatcher { const set_vec_operate &op; EM_vec_store &to_vec; public: EM_vec_setdata_dispatcher(EM_vec_store &store, const set_vec_operate &_op): EM_vec_dispatcher(store), op( _op), to_vec(store) { } virtual void create_vec_task(off_t global_start, size_t length, const EM_vec_store &from_vec); }; void EM_vec_setdata_dispatcher::create_vec_task(off_t global_start, size_t orig_length, const EM_vec_store &from_vec) { // The vector doesn't necessary have the number of elements to make // the end of the vector aligned with the page size. If it's not, // we should align it. We end up writing more data to the underlying // file. size_t entry_size = from_vec.get_type().get_size(); assert(round_ele(global_start, PAGE_SIZE, entry_size) == global_start); size_t length = roundup_ele(orig_length, PAGE_SIZE, entry_size); local_buf_vec_store::ptr buf(new local_buf_vec_store( global_start, length, to_vec.get_type(), -1)); if (length != orig_length) buf->expose_sub_vec(0, orig_length); buf->set_data(op); if (length != orig_length) buf->reset_expose(); to_vec.write_portion_async(buf); } } void EM_vec_store::set_data(const set_vec_operate &op) { mem_thread_pool::ptr threads = mem_thread_pool::get_global_mem_threads(); EM_vec_setdata_dispatcher::ptr dispatcher( new EM_vec_setdata_dispatcher(*this, op)); for (size_t i = 0; i < threads->get_num_threads(); i++) { io_worker_task *task = new io_worker_task(dispatcher); task->register_EM_obj(this); threads->process_task(i % threads->get_num_nodes(), task); } threads->wait4complete(); } matrix_store::ptr EM_vec_store::conv2mat(size_t nrow, size_t ncol, bool byrow) { if (nrow > 1 && ncol > 1) { BOOST_LOG_TRIVIAL(error) << "can't convert an EM vector to a multi-row or multi-col matrix"; return matrix_store::ptr(); } // Store the header as the metadata. matrix_layout_t layout = byrow ? matrix_layout_t::L_ROW : matrix_layout_t::L_COL; std::vector<char> header_buf(matrix_header::get_header_size()); new (header_buf.data()) matrix_header(matrix_type::DENSE, get_type().get_size(), nrow, ncol, layout, get_type().get_type()); safs::safs_file f(safs::get_sys_RAID_conf(), holder->get_name()); bool ret = f.set_user_metadata(header_buf); assert(ret); return EM_matrix_store::create(holder, ios, nrow, ncol, layout, get_type()); } bool EM_vec_store::set_persistent(const std::string &name) { if (!holder->set_persistent(name)) return false; // We need to expose the right number of bytes to the user of the file. safs::safs_file f(safs::get_sys_RAID_conf(), name); f.resize(get_length() * get_type().get_size()); // TODO we have to make sure no other threads are accessing the data // in the vector. How can we do that? safs::file_io_factory::shared_ptr factory = safs::create_io_factory( holder->get_name(), safs::REMOTE_ACCESS); ios = io_set::ptr(new io_set(factory)); return true; } } }
33.052632
82
0.717153
kjhyun824
5aa2b4e1a09f787abe920565809de530a007c56c
1,737
cpp
C++
2020-11-20/spam.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
2
2020-12-12T00:02:40.000Z
2021-04-21T19:49:59.000Z
2020-11-20/spam.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
2020-11-20/spam.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> using namespace std; const int NOT_FILLED = 4; typedef char name_t[32]; struct spam_t { int lower, upper; name_t attribute[3]; int get_index(int x) { if (x<lower) return 0; if (x>=upper) return 2; return 1; } }; spam_t spam[110]; struct person_t { name_t name; int attribute[110]; vector<int> adj; }; person_t person[32]; void dfs(int starter, int index) { int messages = person[starter].adj.size(); int attribute = spam[index].get_index(messages); person[starter].attribute[index] = attribute; for(int j : person[starter].adj) { if (person[j].attribute[index] == NOT_FILLED) dfs(j, index); } } int main() { while(true) { int n, m=0; scanf(" %d", &n); if (n==0) break; for(int i=1; i<=n; ++i) { person[i].adj.clear(); while(true) { int x; scanf(" %d", &x); if (x==0) break; person[i].adj.push_back(x); } } while(true) { int starter; scanf(" %d", &starter); if (starter == 0) break; scanf(" %d %d", &spam[m].lower, &spam[m].upper); for(int i=0; i<3; ++i) scanf(" %s", spam[m].attribute[i]); for(int i=1; i<=n; ++i) person[i].attribute[m] = NOT_FILLED; dfs(starter, m); for(int i=1; i<=n; ++i) if (person[i].attribute[m] == NOT_FILLED) person[i].attribute[m] = spam[m].get_index(0); ++m; } for(int i=1; i<=n; ++i) { scanf(" %s", person[i].name); printf("%s: ", person[i].name); for(int j=0; j<m; ++j) { printf("%s ", spam[j].attribute[person[i].attribute[j]]); } printf("\n"); } } return 0; }
21.182927
59
0.518135
pufe
5aa576333644e47f5049aadcb59b2d368157a8bd
2,234
cpp
C++
42.trapping-rain-water.cpp
Broadroad/learnLeetcode
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
[ "Apache-2.0" ]
null
null
null
42.trapping-rain-water.cpp
Broadroad/learnLeetcode
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
[ "Apache-2.0" ]
null
null
null
42.trapping-rain-water.cpp
Broadroad/learnLeetcode
c4af121b3451caa4d53819c5f8c62b38e8e5fb87
[ "Apache-2.0" ]
null
null
null
/* * @lc app=leetcode id=42 lang=cpp * * [42] Trapping Rain Water * * https://leetcode.com/problems/trapping-rain-water/description/ * * algorithms * Hard (45.51%) * Likes: 4858 * Dislikes: 85 * Total Accepted: 378.9K * Total Submissions: 831.6K * Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]' * * Given n non-negative integers representing an elevation map where the width * of each bar is 1, compute how much water it is able to trap after raining. * * * The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. * In this case, 6 units of rain water (blue section) are being trapped. Thanks * Marcos for contributing this image! * * Example: * * * Input: [0,1,0,2,1,0,1,3,2,1,2,1] * Output: 6 * */ // @lc code=start class Solution { public: int trap1(vector<int>& height) { int n = height.size(); if (n <= 2) { return 0; } int ans = 0; for (int i = 0; i < n; i++) { int left = i, right = i; int maxLeft = height[i]; int maxRight = height[i]; while(left > 0) { left--; if (height[left] > maxLeft) { maxLeft = height[left]; } } while (right < n - 1) { right++; if (height[right] > maxRight) { maxRight = height[right]; } } ans += min(maxLeft, maxRight) - height[i]; } return ans; } int trap2(vector<int>& height) { int n = height.size(); if (n <= 2) { return 0; } vector<int> leftMax(n, 0), rightMax(n, 0); leftMax[0] = height[0]; rightMax[n-1] = height[n-1]; int ans = 0; for (int i = 1; i < n; i++) { leftMax[i] = max(height[i], leftMax[i-1]); } for (int i = n - 2; i >= 0; i--) { rightMax[i] = max(height[i], rightMax[i+1]); } for (int i = 1; i < n-1; i++) { ans += min(leftMax[i], rightMax[i]) - height[i]; } return ans; } int trap(vector<int>& height) { } }; // @lc code=end
23.765957
79
0.473142
Broadroad
5aa5ad73325cca8df2ae0828b9cd3fb922212c51
492
hpp
C++
src/VMEffects/TextureBase.hpp
cad420/VMEffects
9f68b2e0e1c1a51b50f5a0383dd9d31c33ab2af0
[ "MIT" ]
null
null
null
src/VMEffects/TextureBase.hpp
cad420/VMEffects
9f68b2e0e1c1a51b50f5a0383dd9d31c33ab2af0
[ "MIT" ]
null
null
null
src/VMEffects/TextureBase.hpp
cad420/VMEffects
9f68b2e0e1c1a51b50f5a0383dd9d31c33ab2af0
[ "MIT" ]
null
null
null
#pragma once #include "DeviceObjectImpl.hpp" #include <VMEffects/ITexture.h> namespace vm { namespace fx { template<typename Interface,typename DeviceType,typename DescType> class TextureBase : public DeviceObject<Interface, DeviceType> { public: TextureBase( IRefCnt *cnt, DeviceType *device,const TextureDesc & desc ) : DeviceObject<Interface, DeviceType>( cnt, device ),m_desc( desc ) {} const DescType & GetDesc()const { return m_desc; } protected: DescType m_desc; }; } }
18.923077
75
0.747967
cad420
5abb97b0f8e52b6cca1923c658f5dcee3de70436
6,955
cpp
C++
Projects/MissionariesAndCannibals/src/MandCEnvironment.cpp
GlobeOfGeek/modern_ai
d2f2e02b89b35cec00021732d57f99e078972342
[ "MIT" ]
5
2016-04-01T02:10:46.000Z
2016-10-24T19:07:07.000Z
Projects/MissionariesAndCannibals/src/MandCEnvironment.cpp
GlobeOfGeek/morris_aima
d2f2e02b89b35cec00021732d57f99e078972342
[ "MIT" ]
null
null
null
Projects/MissionariesAndCannibals/src/MandCEnvironment.cpp
GlobeOfGeek/morris_aima
d2f2e02b89b35cec00021732d57f99e078972342
[ "MIT" ]
null
null
null
#include <json/json.h> #include "MandCEnvironment.h" #include <iostream> #include "MandCEnvironmentState.h" #include <vector> #include "StateNode.h" #include "MandCAction.h" void MandCEnvironment::loadEnvironment(string fileName) { StateNode *initialNode = NULL; MandCEnvironmentState *initialState = new MandCEnvironmentState; initialState->setCannibalsLeft(1); initialState->setCannibalsRight(2); initialState->setMissionariesLeft(3); initialState->setRiverCrossed(false); initialState->setMissionariesRight(0); initialNode = new StateNode(0, initialState, NULL, NULL); expandNode(initialNode); this->goalNode = NULL; this->initialState = new MandCEnvironmentState; //automatically does initial setup this->goalState = new MandCEnvironmentState; this->goalState->setCannibalsLeft(0); this->goalState->setCannibalsRight(3); this->goalState->setMissionariesLeft(0); this->goalState->setMissionariesRight(3); this->goalState->setRiverCrossed(true); initialNode = new StateNode(0, this->initialState, NULL, NULL); //in case the initial node has our goal state, just stop the search before we start. if(initialNode->getState()->compareTo(goalState)==0) { goalNode = new StateNode(0, initialState, NULL, NULL); } else { addToFrontier(initialNode); } } EnvironmentState *MandCEnvironment::readState() { return NULL; } bool MandCEnvironment::add(Entity *e, Location *place) { return false; } Entity *MandCEnvironment::remove(int id) { return NULL; } bool MandCEnvironment::exists(int id) { return false; } std::vector<Entity *> MandCEnvironment::getEntities() { return std::vector<Entity *>(); } Json::Value MandCEnvironment::outputStateToJson(MandCEnvironmentState *state) { Json::Value outputNode; outputNode["cannibals_left"] = state->getCannibalsLeft(); outputNode["cannibals_right"] = state->getCannibalsRight(); outputNode["missionaries_left"] = state->getMissionariesLeft(); outputNode["missionaries_right"] = state->getMissionariesRight(); outputNode["river_crossed"] = state->isRiverCrossed(); return outputNode; } std::string MandCEnvironment::outputToJson() { Json::Value outputRoot; std::string result; //general environment info outputRoot["Environment"]["age"] = (int) getAge(); outputRoot["Environment"]["type"] = "MissionariesAndCannibals"; if(goalNode!=NULL) { outputRoot["Environment"]["found"] = true; outputRoot["Environment"]["solution_path"] = Json::arrayValue; StateNode *currentPathStep = goalNode; int count = 0; while (currentPathStep != NULL) { Json::Value temp; temp["id"] = count; temp["state"] = outputStateToJson(currentPathStep->getState()); outputRoot["Environment"]["solution_path"].append(temp); currentPathStep = currentPathStep->getParent(); count++; } } else { outputRoot["Environment"]["found"] = false; outputRoot["Environment"]["frontier"] = Json::arrayValue; for(std::vector<StateNode *>::iterator current = frontier.begin(); current<frontier.end(); current++) { outputRoot["Environment"]["frontier"].append(outputStateToJson((*current)->getState())); } outputRoot["Environment"]["explored"] = Json::arrayValue; for(std::vector<StateNode *>::iterator current = explored.begin(); current<explored.end(); current++) { outputRoot["Environment"]["explored"].append(outputStateToJson((*current)->getState())); } } result = outputRoot.toStyledString(); return result; } double MandCEnvironment::getPerformanceMeasure() { return 0; } void MandCEnvironment::act() { if (!goalFound()) { if (frontier.empty()) { std::cout << "ERROR NO POSSIBLE SOLUTION " << std::endl; } else { //remove from frontier StateNode *popped = frontier.at(0); frontier.erase(frontier.begin()); //mark as explored addToExplored(popped); //expanding node std::vector<StateNode *> expanded = expandNode(popped); for (StateNode *curr : expanded) { if (!inFrontier(curr) && !inExploredSet(curr)) { if (curr->getState()->compareTo(goalState) == 0) { this->goalNode = curr; } else { addToFrontier(curr); } } } } } } void MandCEnvironment::generate() { } void MandCEnvironment::updateResults() { } void MandCEnvironment::addToFrontier(StateNode *target) { frontier.push_back(target); } void MandCEnvironment::addToExplored(StateNode *target) { explored.push_back(target); } bool MandCEnvironment::goalFound() { bool result = true; if(goalNode==NULL) { result = false; } return result; } std::vector<StateNode *> MandCEnvironment::expandNode(StateNode *target) { std::vector<StateNode *> expanded; //running through each possible action MandCEnvironmentState *expandedState = target->getState()->ship(1,0); StateNode *curr = new StateNode(target->getPathCost()+1,expandedState,target, new MandCAction(1,0)); expanded.push_back(curr); expandedState = target->getState()->ship(0,1); curr = new StateNode(target->getPathCost()+1, expandedState, target, new MandCAction(0,1)); expanded.push_back(curr); expandedState = target->getState()->ship(1,1); curr = new StateNode(target->getPathCost()+1, expandedState, target, new MandCAction(1,1)); expanded.push_back(curr); expandedState = target->getState()->ship(2,0); curr = new StateNode(target->getPathCost()+1, expandedState, target, new MandCAction(2,0)); expanded.push_back(curr); expandedState = target->getState()->ship(0,2); curr = new StateNode(target->getPathCost()+1, expandedState, target, new MandCAction(0,2)); expanded.push_back(curr); for (std::vector<StateNode *>::iterator it = expanded.begin(); it < expanded.end(); it++) { //delete all the invalid nodes that were generated StateNode *node = *it; MandCEnvironmentState *state = node->getState(); if (state == NULL) { //this state must be invalid it = expanded.erase(it); it--; } } return expanded; } bool MandCEnvironment::inFrontier(StateNode *node) { bool result = false; for (StateNode *curr : frontier) { if (curr->compareTo(node) == 0) { result = true; } } return result; } bool MandCEnvironment::inExploredSet(StateNode *node) { bool result = false; for (StateNode *curr : explored) { if (curr->compareTo(node) == 0) { result = true; } } return result; }
32.050691
111
0.641265
GlobeOfGeek
5abe1290174aa54677aff998642aaf5fa1a4145d
923
cpp
C++
src/Sudoku/Slice.cpp
Pafnoutios/libsudoku
9d700716895d46f71e854133a1135ab6047b3f88
[ "MIT" ]
null
null
null
src/Sudoku/Slice.cpp
Pafnoutios/libsudoku
9d700716895d46f71e854133a1135ab6047b3f88
[ "MIT" ]
null
null
null
src/Sudoku/Slice.cpp
Pafnoutios/libsudoku
9d700716895d46f71e854133a1135ab6047b3f88
[ "MIT" ]
null
null
null
#include "Slice.hpp" #include "Cell.hpp" #include <numeric> Sudoku::Slice::Slice(const Size& size) : _possibilities(size[iBlock]) , _members{ size[iBlock], nullptr } { std::iota(_possibilities.begin(), _possibilities.end(), 0); } void Sudoku::Slice::assignMember(int index, Cell& cell) { _members[index] = &cell; } void Sudoku::Slice::eliminatePossibility(int possibility, Cell* source) { _possibilities.erase(std::remove(_possibilities.begin(), _possibilities.end(), possibility), _possibilities.end()); for (auto cell : _members) { if (cell != source) { cell->eliminatePossibility(possibility); } } } std::vector<Sudoku::Cell*> Sudoku::Slice::wherePossible(int i) const { std::vector<Cell*> possibilities; std::copy_if(_members.begin(), _members.end(), std::back_inserter(possibilities), [i](Cell const* cell) { return cell->isPossible(i); }); return possibilities; }
22.512195
117
0.690141
Pafnoutios
5abe7c6e11498dddde9095eadb7b09122c5486ac
601
cpp
C++
LeetCode/c++/985_Sum of Even Numbers After Queries_V2.cpp
Weak-Chicken/Algo_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
1
2018-02-08T23:50:19.000Z
2018-02-08T23:50:19.000Z
LeetCode/c++/985_Sum of Even Numbers After Queries_V2.cpp
Weak-Chicken/Algo_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
1
2018-04-11T19:08:22.000Z
2018-04-12T19:24:57.000Z
LeetCode/c++/985_Sum of Even Numbers After Queries_V2.cpp
Weak-Chicken/Cpp_every_day
0976b5986d6c98cb8370ff4239b4a2485f865253
[ "MIT" ]
null
null
null
class Solution { public: vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) { vector<int>res; int sum = 0; if (A.size() == 0 || queries.size() == 0) return res; for (int i = 0; i < A.size(); i++) if (A[i] % 2 == 0) sum += A[i]; for (int i = 0; i < queries.size(); i++) { if (A[queries[i][1]] % 2 == 0) sum -= A[queries[i][1]]; A[queries[i][1]] += queries[i][0]; if (A[queries[i][1]] % 2 == 0) sum += A[queries[i][1]]; res.push_back(sum); } return res; } };
33.388889
82
0.450915
Weak-Chicken
5ac9475d8d79f9b54b2b0259c5d7bac59840936d
1,271
hpp
C++
include/codegen/include/GlobalNamespace/EnumFlagAttribute.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/EnumFlagAttribute.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/EnumFlagAttribute.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.PropertyAttribute #include "UnityEngine/PropertyAttribute.hpp" // Completed includes // Type namespace: namespace GlobalNamespace { // Autogenerated type: EnumFlagAttribute class EnumFlagAttribute : public UnityEngine::PropertyAttribute { public: // public System.String enumName // Offset: 0x10 ::Il2CppString* enumName; // public System.Void .ctor(System.String name) // Offset: 0xCB04CC static EnumFlagAttribute* New_ctor(::Il2CppString* name); // public System.Void .ctor() // Offset: 0xCB04C4 // Implemented from: UnityEngine.PropertyAttribute // Base method: System.Void PropertyAttribute::.ctor() // Base method: System.Void Attribute::.ctor() // Base method: System.Void Object::.ctor() static EnumFlagAttribute* New_ctor(); }; // EnumFlagAttribute } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::EnumFlagAttribute*, "", "EnumFlagAttribute"); #pragma pack(pop)
37.382353
85
0.693155
Futuremappermydud
5ace5f94900d63f26cc8724172224403cb0b14ea
560
cpp
C++
dev/g++/projects/beaglebone/beagleboneComm/src/beagleboneCommInit.cpp
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/beaglebone/beagleboneComm/src/beagleboneCommInit.cpp
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/beaglebone/beagleboneComm/src/beagleboneCommInit.cpp
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
1
2017-01-27T12:53:50.000Z
2017-01-27T12:53:50.000Z
#include <unistd.h> #include "raspberryCommInit.h" #include "wiringPi.h" namespace raspberryComm { raspberryCommInit * raspberryCommInit::Instance = new raspberryCommInit(); raspberryCommInit::~raspberryCommInit() { delete raspberryCommInit::Instance; raspberryCommInit::Instance = NULL; } raspberryCommInit & raspberryCommInit::getInstance() { return *raspberryCommInit::Instance; } void raspberryCommInit::initialize() { // Initialize the WiringPI library ::wiringPiSetup(); } } // End of namespace raspberryComm
22.4
76
0.728571
YannGarcia
62c597a6f0a1fab651351abcfa196de3a43e6a49
1,579
cpp
C++
src/Apps/RemoteCloudControlServer/main.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Apps/RemoteCloudControlServer/main.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Apps/RemoteCloudControlServer/main.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "RemoteCloudControlServerPch.h" #include <iostream> #include <thread> #include <grpc/grpc.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/status.h> #include <grpc++/stream.h> #include <RemoteCloudControl/remote_cloud_control.grpc.pb.h> #include <cpputil/ConsoleApplicationUtil.h> using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerReader; using grpc::ServerReaderWriter; using grpc::ServerWriter; using grpc::Status; class RemoteCallControlServiceImpl final : public rtp_plus_plus::RemoteCallControlService::Service { public: virtual ::grpc::Status call(::grpc::ServerContext* context, const ::rtp_plus_plus::CalleeInfo* request, ::rtp_plus_plus::Response* response) { // TODO: implement call control LOG(INFO) << "RPC call() invoked: " << request->sip_uri(); return Status::OK; } private: }; void RunServer() { std::string server_address("0.0.0.0:50051"); RemoteCallControlServiceImpl service; ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } int main() { LOG(INFO) << "main"; grpc_init(); LOG(INFO) << "running server"; RunServer(); LOG(INFO) << "shutting down"; grpc_shutdown(); LOG(INFO) << "app complete"; return 0; }
22.884058
142
0.720709
miseri
62c858754f08b5f68ae3fbc352fd415f21bc57dc
3,084
cpp
C++
snark-logic/libs-source/multiprecision/test/test_jacobi.cpp
idealatom/podlodkin-freeton-year-control
6aa96e855fe065c9a75c76da976a87fe2d1668e6
[ "MIT" ]
1
2021-09-14T18:09:38.000Z
2021-09-14T18:09:38.000Z
snark-logic/libs-source/multiprecision/test/test_jacobi.cpp
idealatom/podlodkin-freeton-year-control
6aa96e855fe065c9a75c76da976a87fe2d1668e6
[ "MIT" ]
null
null
null
snark-logic/libs-source/multiprecision/test/test_jacobi.cpp
idealatom/podlodkin-freeton-year-control
6aa96e855fe065c9a75c76da976a87fe2d1668e6
[ "MIT" ]
1
2021-09-15T20:27:27.000Z
2021-09-15T20:27:27.000Z
/////////////////////////////////////////////////////////////// // Copyright 2020 Mikhail Komarov. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt #ifdef _MSC_VER #define _SCL_SECURE_NO_WARNINGS #endif #include "test.hpp" #if !defined(TEST_GMP) && !defined(TEST_TOMMATH) && !defined(TEST_CPP_INT) #define TEST_TOMMATH #define TEST_GMP #define TEST_CPP_INT #ifdef _MSC_VER #pragma message("CAUTION!!: No backend type specified so testing everything.... this will take some time!!") #endif #ifdef __GNUC__ #pragma warning "CAUTION!!: No backend type specified so testing everything.... this will take some time!!" #endif #endif #if defined(TEST_GMP) #include <nil/crypto3/multiprecision/gmp.hpp> #endif #if defined(TEST_TOMMATH) #include <nil/crypto3/multiprecision/tommath.hpp> #endif #if defined(TEST_CPP_INT) #include <nil/crypto3/multiprecision/cpp_int.hpp> #endif #include <nil/crypto3/multiprecision/jacobi.hpp> #include <nil/crypto3/multiprecision/cpp_int/literals.hpp> BOOST_MP_DEFINE_SIZED_CPP_INT_LITERAL(256); template<typename T> void test() { using namespace nil::crypto3::multiprecision; BOOST_CHECK_EQUAL(jacobi(T(5), T(9)), 1); BOOST_CHECK_EQUAL(jacobi(T(1), T(27)), 1); BOOST_CHECK_EQUAL(jacobi(T(2), T(27)), -1); BOOST_CHECK_EQUAL(jacobi(T(3), T(27)), 0); BOOST_CHECK_EQUAL(jacobi(T(4), T(27)), 1); BOOST_CHECK_EQUAL(jacobi(T(506), T(1103)), -1); // new tests from algebra: BOOST_CHECK_EQUAL( jacobi(T(76749407), T("21888242871839275222246405745257275088696311157297823662689037894645226208583")), -1); BOOST_CHECK_EQUAL( jacobi(T(76749407), T("52435875175126190479447740508185965837690552500527637822603658699938581184513")), -1); BOOST_CHECK_EQUAL( jacobi( T(76749407), T("18401471844947097664173251940900308709046483937867715073880837110864239498070802969129867528264353400424" "03298196232503709156245534219589335680638510254027764437882223571969881035804085174863110178951694406403" "43141708939276039764731720833213215559801639066799283898191098079351209268491644339667178604494222971572" "78897105437443828133160276495096341710144889141242401158886206885011341008817780140927978648973063559908" "13408559307626854581748371042304462382047277716284590087959373746400022332313336095224466892979000905491" "1540076476091045996759150349011014772948929626145183545025870323741270110314006814529932451772897")), -1); } int main() { using namespace nil::crypto3::multiprecision; #if defined(TEST_CPP_INT) test<cpp_int>(); constexpr auto a = 0x4931a5f_cppui256; constexpr auto b = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001_cppui256; static_assert(jacobi(a, b) == -1, "jacobi error"); #endif #if defined(TEST_GMP) test<mpz_int>(); #endif #if defined(TEST_TOMMATH) test<tom_int>(); #endif return boost::report_errors(); }
35.045455
120
0.74546
idealatom
62d34292368d8e44dfec1be6fbe80af145bf7687
14,652
cc
C++
lib/evaluate/variable.cc
ibara/f18
5344ef9272f2f46702e96409c8d697b927542e20
[ "Apache-2.0" ]
null
null
null
lib/evaluate/variable.cc
ibara/f18
5344ef9272f2f46702e96409c8d697b927542e20
[ "Apache-2.0" ]
null
null
null
lib/evaluate/variable.cc
ibara/f18
5344ef9272f2f46702e96409c8d697b927542e20
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018, NVIDIA CORPORATION. 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 "variable.h" #include "tools.h" #include "../common/idioms.h" #include "../parser/char-block.h" #include "../parser/characters.h" #include "../parser/message.h" #include "../semantics/symbol.h" #include <ostream> using namespace Fortran::parser::literals; namespace Fortran::evaluate { // Constructors, accessors, mutators Triplet::Triplet(std::optional<Expr<SubscriptInteger>> &&l, std::optional<Expr<SubscriptInteger>> &&u, std::optional<Expr<SubscriptInteger>> &&s) { if (l.has_value()) { lower_ = IndirectSubscriptIntegerExpr::Make(std::move(*l)); } if (u.has_value()) { upper_ = IndirectSubscriptIntegerExpr::Make(std::move(*u)); } if (s.has_value()) { stride_ = IndirectSubscriptIntegerExpr::Make(std::move(*s)); } } std::optional<Expr<SubscriptInteger>> Triplet::lower() const { if (lower_) { return {**lower_}; } return std::nullopt; } std::optional<Expr<SubscriptInteger>> Triplet::upper() const { if (upper_) { return {**upper_}; } return std::nullopt; } std::optional<Expr<SubscriptInteger>> Triplet::stride() const { if (stride_) { return {**stride_}; } return std::nullopt; } CoarrayRef::CoarrayRef(std::vector<const Symbol *> &&c, std::vector<Expr<SubscriptInteger>> &&ss, std::vector<Expr<SubscriptInteger>> &&css) : base_(std::move(c)), subscript_(std::move(ss)), cosubscript_(std::move(css)) { CHECK(!base_.empty()); } CoarrayRef &CoarrayRef::set_stat(Variable<DefaultInteger> &&v) { stat_ = CopyableIndirection<Variable<DefaultInteger>>::Make(std::move(v)); return *this; } CoarrayRef &CoarrayRef::set_team( Variable<DefaultInteger> &&v, bool isTeamNumber) { team_ = CopyableIndirection<Variable<DefaultInteger>>::Make(std::move(v)); teamIsTeamNumber_ = isTeamNumber; return *this; } Substring::Substring(DataRef &&d, std::optional<Expr<SubscriptInteger>> &&f, std::optional<Expr<SubscriptInteger>> &&l) : u_{std::move(d)} { if (f.has_value()) { first_ = IndirectSubscriptIntegerExpr::Make(std::move(*f)); } if (l.has_value()) { last_ = IndirectSubscriptIntegerExpr::Make(std::move(*l)); } } Substring::Substring(std::string &&s, std::optional<Expr<SubscriptInteger>> &&f, std::optional<Expr<SubscriptInteger>> &&l) : u_{std::move(s)} { if (f.has_value()) { first_ = IndirectSubscriptIntegerExpr::Make(std::move(*f)); } if (l.has_value()) { last_ = IndirectSubscriptIntegerExpr::Make(std::move(*l)); } } Expr<SubscriptInteger> Substring::first() const { if (first_.has_value()) { return **first_; } return AsExpr(Constant<SubscriptInteger>{1}); } Expr<SubscriptInteger> Substring::last() const { if (last_.has_value()) { return **last_; } return std::visit( common::visitors{[](const std::string &s) { // std::string::size_type isn't convertible to uint64_t // on Darwin return AsExpr(Constant<SubscriptInteger>{ static_cast<std::uint64_t>(s.size())}); }, [](const DataRef &x) { return x.LEN(); }}, u_); } std::optional<std::string> Substring::Fold(FoldingContext &context) { std::optional<Constant<SubscriptInteger>> lbConst{first().Fold(context)}; if (lbConst.has_value()) { first_ = AsExpr(*lbConst); } std::optional<Constant<SubscriptInteger>> ubConst{last().Fold(context)}; if (ubConst.has_value()) { last_ = AsExpr(*ubConst); } if (auto both{common::AllPresent(std::move(lbConst), std::move(ubConst))}) { std::int64_t lbi{std::get<0>(*both).value.ToInt64()}; std::int64_t ubi{std::get<1>(*both).value.ToInt64()}; if (ubi < lbi) { // These cases are well defined, and they produce zero-length results. u_ = ""s; first_ = AsExpr(Constant<SubscriptInteger>{1}); last_ = AsExpr(Constant<SubscriptInteger>{0}); return {""s}; } if (lbi <= 0) { context.messages.Say( "lower bound on substring (%jd) is less than one"_en_US, static_cast<std::intmax_t>(lbi)); lbi = 1; first_ = AsExpr(Constant<SubscriptInteger>{lbi}); } if (ubi <= 0) { u_ = ""s; last_ = AsExpr(Constant<SubscriptInteger>{0}); return {""s}; } if (std::string * str{std::get_if<std::string>(&u_)}) { std::int64_t len = str->size(); if (ubi > len) { context.messages.Say( "upper bound on substring (%jd) is greater than character length (%jd)"_en_US, static_cast<std::intmax_t>(ubi), static_cast<std::intmax_t>(len)); ubi = len; last_ = AsExpr(Constant<SubscriptInteger>{ubi}); } std::string result{str->substr(lbi - 1, ubi - lbi + 1)}; u_ = result; return {result}; } } return std::nullopt; } // Variable dumping template<typename A> std::ostream &Emit(std::ostream &o, const A &x) { return x.Dump(o); } template<> std::ostream &Emit(std::ostream &o, const std::string &lit) { return o << parser::QuoteCharacterLiteral(lit); } template<typename A> std::ostream &Emit(std::ostream &o, const A *p, const char *kw = nullptr) { if (p != nullptr) { if (kw != nullptr) { o << kw; } Emit(o, *p); } return o; } template<typename A> std::ostream &Emit( std::ostream &o, const std::optional<A> &x, const char *kw = nullptr) { if (x.has_value()) { if (kw != nullptr) { o << kw; } Emit(o, *x); } return o; } template<typename A> std::ostream &Emit(std::ostream &o, const CopyableIndirection<A> &p, const char *kw = nullptr) { if (kw != nullptr) { o << kw; } Emit(o, *p); return o; } template<typename... A> std::ostream &Emit(std::ostream &o, const std::variant<A...> &u) { std::visit([&](const auto &x) { Emit(o, x); }, u); return o; } template<> std::ostream &Emit(std::ostream &o, const Symbol &symbol) { return o << symbol.name().ToString(); } template<> std::ostream &Emit(std::ostream &o, const IntrinsicProcedure &p) { return o << EnumToString(p); } std::ostream &Component::Dump(std::ostream &o) const { base_->Dump(o); return Emit(o << '%', symbol_); } std::ostream &Triplet::Dump(std::ostream &o) const { Emit(o, lower_) << ':'; Emit(o, upper_); if (stride_) { Emit(o << ':', stride_); } return o; } std::ostream &Subscript::Dump(std::ostream &o) const { return Emit(o, u); } std::ostream &ArrayRef::Dump(std::ostream &o) const { Emit(o, u); char separator{'('}; for (const Subscript &ss : subscript) { ss.Dump(o << separator); separator = ','; } return o << ')'; } std::ostream &CoarrayRef::Dump(std::ostream &o) const { for (const Symbol *sym : base_) { Emit(o, *sym); } char separator{'('}; for (const auto &ss : subscript_) { Emit(o << separator, ss); separator = ','; } if (separator == ',') { o << ')'; } separator = '['; for (const auto &css : cosubscript_) { Emit(o << separator, css); separator = ','; } if (stat_.has_value()) { Emit(o << separator, stat_, "STAT="); separator = ','; } if (team_.has_value()) { Emit(o << separator, team_, teamIsTeamNumber_ ? "TEAM_NUMBER=" : "TEAM="); } return o << ']'; } std::ostream &DataRef::Dump(std::ostream &o) const { return Emit(o, u); } std::ostream &Substring::Dump(std::ostream &o) const { Emit(o, u_) << '('; Emit(o, first_) << ':'; return Emit(o, last_); } std::ostream &ComplexPart::Dump(std::ostream &o) const { return complex_.Dump(o) << '%' << EnumToString(part_); } std::ostream &ProcedureDesignator::Dump(std::ostream &o) const { return Emit(o, u); } std::ostream &UntypedFunctionRef::Dump(std::ostream &o) const { Emit(o, proc_); char separator{'('}; for (const auto &arg : arguments_) { Emit(o << separator, arg); separator = ','; } if (separator == '(') { o << '('; } return o << ')'; } std::ostream &SubroutineCall::Dump(std::ostream &o) const { Emit(o, proc_); char separator{'('}; for (const auto &arg : arguments_) { Emit(o << separator, arg); separator = ','; } if (separator == '(') { o << '('; } return o << ')'; } std::ostream &ActualSubroutineArg::Dump(std::ostream &o) const { return Emit(o, u); } std::ostream &Label::Dump(std::ostream &o) const { return o << '*' << std::dec << label; } // LEN() static Expr<SubscriptInteger> SymbolLEN(const Symbol &sym) { return AsExpr(Constant<SubscriptInteger>{0}); // TODO } Expr<SubscriptInteger> Component::LEN() const { return SymbolLEN(symbol()); } Expr<SubscriptInteger> ArrayRef::LEN() const { return std::visit( common::visitors{[](const Symbol *s) { return SymbolLEN(*s); }, [](const Component &x) { return x.LEN(); }}, u); } Expr<SubscriptInteger> CoarrayRef::LEN() const { return SymbolLEN(*base_.back()); } Expr<SubscriptInteger> DataRef::LEN() const { return std::visit( common::visitors{[](const Symbol *s) { return SymbolLEN(*s); }, [](const auto &x) { return x.LEN(); }}, u); } Expr<SubscriptInteger> Substring::LEN() const { return AsExpr( Extremum<SubscriptInteger>{AsExpr(Constant<SubscriptInteger>{0}), last() - first() + AsExpr(Constant<SubscriptInteger>{1})}); } template<typename A> Expr<SubscriptInteger> Designator<A>::LEN() const { return std::visit( common::visitors{[](const Symbol *s) { return SymbolLEN(*s); }, [](const Component &c) { return c.LEN(); }, [](const auto &x) { return x.LEN(); }}, u); } Expr<SubscriptInteger> ProcedureDesignator::LEN() const { return std::visit( common::visitors{[](const Symbol *s) { return SymbolLEN(*s); }, [](const Component &c) { return c.LEN(); }, [](const auto &) { CRASH_NO_CASE; return AsExpr(Constant<SubscriptInteger>{0}); }}, u); } Expr<SubscriptInteger> UntypedFunctionRef::LEN() const { // TODO: the results of the intrinsic functions REPEAT and TRIM have // unpredictable lengths; maybe the concept of LEN() has to become dynamic return proc_.LEN(); } // Rank() int Component::Rank() const { int baseRank{base_->Rank()}; int symbolRank{symbol_->Rank()}; CHECK(baseRank == 0 || symbolRank == 0); return baseRank + symbolRank; } int Subscript::Rank() const { return std::visit(common::visitors{[](const IndirectSubscriptIntegerExpr &x) { int rank{x->Rank()}; CHECK(rank <= 1); return rank; }, [](const Triplet &) { return 1; }}, u); } int ArrayRef::Rank() const { int rank{0}; for (std::size_t j{0}; j < subscript.size(); ++j) { rank += subscript[j].Rank(); } if (std::holds_alternative<const Symbol *>(u)) { return rank; } else { int baseRank{std::get_if<Component>(&u)->Rank()}; CHECK(rank == 0 || baseRank == 0); return baseRank + rank; } } int CoarrayRef::Rank() const { int rank{0}; for (std::size_t j{0}; j < subscript_.size(); ++j) { rank += subscript_[j].Rank(); } return rank; } int DataRef::Rank() const { return std::visit( // g++ 7.2 emits bogus warnings here and below when common::visitors{} // is used with a "const auto &" catch-all member, so a constexpr type // test has to be used instead. [](const auto &x) { if constexpr (std::is_same_v<std::decay_t<decltype(x)>, const Symbol *>) { return x->Rank(); } else { return x.Rank(); } }, u); } int Substring::Rank() const { return std::visit( [](const auto &x) { if constexpr (std::is_same_v<std::decay_t<decltype(x)>, std::string>) { return 0; } else { return x.Rank(); } }, u_); } int ComplexPart::Rank() const { return complex_.Rank(); } int ProcedureDesignator::Rank() const { return std::visit( common::visitors{[](IntrinsicProcedure) { return 0 /*TODO!!*/; }, [](const Symbol *sym) { return sym->Rank(); }, [](const Component &c) { return c.symbol().Rank(); }}, u); } int ActualSubroutineArg::Rank() const { return std::visit(common::visitors{[](const ActualFunctionArg &a) { if (a.has_value()) { return (*a)->Rank(); } else { return 0; } }, [](const Label *) { return 0; }}, u); } // GetSymbol const Symbol *Component::GetSymbol(bool first) const { return base_->GetSymbol(first); } const Symbol *ArrayRef::GetSymbol(bool first) const { return std::visit(common::visitors{[](const Symbol *sym) { return sym; }, [=](const Component &component) { return component.GetSymbol(first); }}, u); } const Symbol *DataRef::GetSymbol(bool first) const { return std::visit(common::visitors{[](const Symbol *sym) { return sym; }, [=](const auto &x) { return x.GetSymbol(first); }}, u); } const Symbol *Substring::GetSymbol(bool first) const { if (const DataRef * dataRef{std::get_if<DataRef>(&u_)}) { return dataRef->GetSymbol(first); } else { return nullptr; // substring of character literal } } const Symbol *ProcedureDesignator::GetSymbol() const { return std::visit(common::visitors{[](const Symbol *sym) { return sym; }, [](const Component &c) { return c.GetSymbol(false); }, [](const auto &) -> const Symbol * { return nullptr; }}, u); } FOR_EACH_CHARACTER_KIND(template class Designator) FOR_EACH_SPECIFIC_TYPE(template struct FunctionRef) } // namespace Fortran::evaluate
29.245509
90
0.589954
ibara
62e0570b5b063f862cfda43d51502080c71915b7
2,716
cpp
C++
src/sctokenoperations.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
1
2020-12-13T16:56:32.000Z
2020-12-13T16:56:32.000Z
src/sctokenoperations.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
null
null
null
src/sctokenoperations.cpp
BryanMorfe/SciCalc
1602c159c48013beb8dee09ff648923f37c69e09
[ "Apache-2.0" ]
null
null
null
#include "include/sctokenoperations.h" #include <QRegularExpression> TokenType SCTokenOperations::tokenType(const QChar &ch) { TokenType type; QHash<QString, SCToken *>::const_iterator it = tokens.find(ch); if (it != tokens.end()) type = it.value()->getType(); else { if (ch.isLetter()) type = partialFunction; else if (ch.isDigit() || ch == '.') type = partialOperand; else type = unknown; } return type; } TokenType SCTokenOperations::tokenType(const QString &str) { TokenType type; QHash<QString, SCToken *>::const_iterator it = tokens.find(str); if (it != tokens.end()) type = it.value()->getType(); else { // check if it's operand /* Valid operands are: * Integers: 5, 6, 7, 5., 7., 3. (with no leading zeroes): [1-9][0-9]*\.? * Floats: .5, .7, 5.2, 5.0, 0.04, (multiple leading zeroes before the decimal point are allowed): [0-9]*\.[0-9]+ */ QRegularExpression regExp("([1-9][0-9]*\\.?)|([0-9]*\\.[0-9]+)"); QRegularExpressionMatch match = regExp.match(str); if (match.hasMatch()) type = operand; else type = unknown; } return type; } SCToken *SCTokenOperations::token(const QString &str) { SCToken *token; QHash<QString, SCToken *>::const_iterator it = tokens.find(str); if (it != tokens.end()) { SCToken *retrievedToken = it.value(); switch (retrievedToken->getType()) { case operand: token = new SCOperand(*static_cast<SCOperand *>(retrievedToken)); break; case binaryOperator: token = new SCBinaryOperator(*static_cast<SCBinaryOperator *>(retrievedToken)); break; case unaryOperator: token = new SCUnaryOperator(*static_cast<SCUnaryOperator *>(retrievedToken)); break; case binaryFunction: token = new SCBinaryFunction(*static_cast<SCBinaryFunction *>(retrievedToken)); break; case unaryFunction: token = new SCUnaryFunction(*static_cast<SCUnaryFunction *>(retrievedToken)); break; case lParenthesis: case rParenthesis: case lBracket: case rBracket: case separator: token = new SCToken(*retrievedToken); break; default: token = nullptr; } } else { TokenType type = tokenType(str); if (type == operand) token = new SCOperand(str, operand, str, str.toDouble()); else token = nullptr; } return token; }
26.368932
121
0.559278
BryanMorfe
62fc517303aacf36d20b8f79731d304af90e8662
896
cpp
C++
source/RegistNodes.cpp
xzrunner/vfxlab
a2a30ee369d1955ceb55353f2dcdafdf1ce2fe37
[ "MIT" ]
null
null
null
source/RegistNodes.cpp
xzrunner/vfxlab
a2a30ee369d1955ceb55353f2dcdafdf1ce2fe37
[ "MIT" ]
null
null
null
source/RegistNodes.cpp
xzrunner/vfxlab
a2a30ee369d1955ceb55353f2dcdafdf1ce2fe37
[ "MIT" ]
null
null
null
#include "vfxlab/RegistNodes.h" #include <ee0/ReflectPropTypes.h> #include <js/RTTR.h> #define REGIST_NODE_RTTI(type, name, prop) \ rttr::registration::class_<vfxlab::node::type>("vfxlab::"#name) \ .constructor<>() \ prop \ ; #define PROP #define REGIST_NODE_RTTI_DEFAULT(type, name) REGIST_NODE_RTTI(type, name, PROP) RTTR_REGISTRATION { // base rttr::registration::class_<vfxlab::Node>("vfxlab::node") .property("name", &vfxlab::Node::GetName, &vfxlab::Node::SetName) ( rttr::metadata(ee0::UIMetaInfoTag(), ee0::UIMetaInfo("Name")) ) ; #define EXE_FILEPATH "vfxlab/node_rttr_gen.h" #define SKIP_FILE_NODE #include "vfxlab/node_regist_cfg.h" #undef SKIP_FILE_NODE #undef EXE_FILEPATH } namespace vfxlab { void nodes_regist_rttr() { } }
20.837209
79
0.613839
xzrunner
1a004aaafd9b8f98cfabbd936ba1728d67e3fb1c
9,827
cc
C++
test/gurka/test_instructions_keep_toward.cc
mixvit/valhalla
65d56caf85103f267452e7b79e49ec66a9bf480e
[ "MIT" ]
1
2019-12-11T13:45:27.000Z
2019-12-11T13:45:27.000Z
test/gurka/test_instructions_keep_toward.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
1
2020-07-29T17:39:33.000Z
2020-08-03T11:07:51.000Z
test/gurka/test_instructions_keep_toward.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
1
2020-11-01T14:49:36.000Z
2020-11-01T14:49:36.000Z
#include "gurka.h" #include <gtest/gtest.h> #if !defined(VALHALLA_SOURCE_DIR) #define VALHALLA_SOURCE_DIR #endif using namespace valhalla; class InstructionsKeepToward : public ::testing::Test { protected: static gurka::map map; static void SetUpTestSuite() { constexpr double gridsize_metres = 1000; const std::string ascii_map = R"( C--D J--K A--B<--G--H--I<--N--O E--F L--M )"; const gurka::ways ways = {{"AB", {{"highway", "motorway"}, {"name", ""}, {"ref", "A1"}}}, {"BC", {{"highway", "motorway"}, {"name", ""}, {"ref", "B1"}, {"destination", "Harrisburg;Lancaster"}, {"destination:ref", "B1"}}}, {"CD", {{"highway", "motorway"}, {"name", ""}, {"ref", "B1"}}}, {"BE", {{"highway", "motorway"}, {"name", ""}, {"ref", "B2"}, {"destination", "Baltimore;Washington"}, {"destination:ref", "B2"}}}, {"EF", {{"highway", "motorway"}, {"name", ""}, {"ref", "B2"}}}, {"BG", {{"highway", "motorway"}, {"name", ""}, {"ref", "B3"}, {"destination", "New York;Philadelphia"}, {"destination:ref", "B3"}}}, {"GH", {{"highway", "motorway"}, {"name", ""}, {"ref", "B3"}}}, {"HI", {{"highway", "motorway"}, {"name", ""}, {"ref", "B3"}}}, {"IJ", {{"highway", "motorway"}, {"name", ""}, {"ref", "C1"}, {"junction:ref", "22A"}, {"destination", "Harrisburg;Lancaster"}, {"destination:ref", "C1"}}}, {"JK", {{"highway", "motorway"}, {"name", ""}, {"ref", "C1"}}}, {"IL", {{"highway", "motorway"}, {"name", ""}, {"ref", "C2"}, {"junction:ref", "22C"}, {"destination", "Baltimore;Washington"}, {"destination:ref", "C2"}}}, {"LM", {{"highway", "motorway"}, {"name", ""}, {"ref", "C2"}}}, {"IN", {{"highway", "motorway"}, {"name", ""}, {"ref", "C3"}, {"junction:ref", "22B"}, {"destination", "New York;Philadelphia"}, {"destination:ref", "C3"}}}, {"NO", {{"highway", "motorway"}, {"name", ""}, {"ref", "C3"}}}}; const auto layout = gurka::detail::map_to_coordinates(ascii_map, gridsize_metres, {5.1079374, 52.0887174}); map = gurka::buildtiles(layout, ways, {}, {}, "test/data/gurka_instructions_keep_toward", {{"mjolnir.admin", {VALHALLA_SOURCE_DIR "test/data/netherlands_admin.sqlite"}}}); } }; gurka::map InstructionsKeepToward::map = {}; /////////////////////////////////////////////////////////////////////////////// // Keep right toward // "4": "Keep <RELATIVE_DIRECTION> toward <TOWARD_SIGN>." TEST_F(InstructionsKeepToward, KeepRightToward) { auto result = gurka::route(map, "A", "F", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayRight, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep right toward instructions gurka::assert::raw:: expect_instructions_at_maneuver_index(result, maneuver_index, "Keep right toward B2/Baltimore/Washington.", "Keep right toward B2.", "Keep right toward B2, Baltimore.", "Continue for 4 kilometers."); } /////////////////////////////////////////////////////////////////////////////// // Keep left toward // "4": "Keep <RELATIVE_DIRECTION> toward <TOWARD_SIGN>." TEST_F(InstructionsKeepToward, KeepLeftToward) { auto result = gurka::route(map, "A", "D", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayLeft, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep left toward instructions gurka::assert::raw:: expect_instructions_at_maneuver_index(result, maneuver_index, "Keep left toward B1/Harrisburg/Lancaster.", "Keep left toward B1.", "Keep left toward B1, Harrisburg.", "Continue for 4 kilometers."); } /////////////////////////////////////////////////////////////////////////////// // Keep straight toward // "4": "Keep <RELATIVE_DIRECTION> toward <TOWARD_SIGN>." TEST_F(InstructionsKeepToward, KeepStraightToward) { auto result = gurka::route(map, "A", "H", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayStraight, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep straight toward instructions gurka::assert::raw:: expect_instructions_at_maneuver_index(result, maneuver_index, "Keep straight toward B3/New York/Philadelphia.", "Keep straight toward B3.", "Keep straight toward B3, New York.", "Continue for 4 kilometers."); } /////////////////////////////////////////////////////////////////////////////// // Keep right to take exit number toward // "5": "Keep <RELATIVE_DIRECTION> to take exit <NUMBER_SIGN> toward <TOWARD_SIGN>.", TEST_F(InstructionsKeepToward, KeepRightExitNumberToward) { auto result = gurka::route(map, "H", "M", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayRight, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep right to take exit number toward instructions gurka::assert::raw::expect_instructions_at_maneuver_index( result, maneuver_index, "Keep right to take exit 22C toward C2/Baltimore/Washington.", "Keep right to take exit 22C.", "Keep right to take exit 22C toward C2, Baltimore.", "Continue for 4 kilometers."); } /////////////////////////////////////////////////////////////////////////////// // Keep left to take exit number toward // "5": "Keep <RELATIVE_DIRECTION> to take exit <NUMBER_SIGN> toward <TOWARD_SIGN>.", TEST_F(InstructionsKeepToward, KeepLeftExitNumberToward) { auto result = gurka::route(map, "H", "K", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayLeft, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep left to take exit number toward instructions gurka::assert::raw::expect_instructions_at_maneuver_index( result, maneuver_index, "Keep left to take exit 22A toward C1/Harrisburg/Lancaster.", "Keep left to take exit 22A.", "Keep left to take exit 22A toward C1, Harrisburg.", "Continue for 4 kilometers."); } /////////////////////////////////////////////////////////////////////////////// // Keep straight to take exit number toward // "5": "Keep <RELATIVE_DIRECTION> to take exit <NUMBER_SIGN> toward <TOWARD_SIGN>.", TEST_F(InstructionsKeepToward, KeepStraightExitNumberToward) { auto result = gurka::route(map, "H", "O", "auto"); // Verify maneuver types gurka::assert::raw::expect_maneuvers(result, {DirectionsLeg_Maneuver_Type_kStart, DirectionsLeg_Maneuver_Type_kStayStraight, DirectionsLeg_Maneuver_Type_kDestination}); int maneuver_index = 1; // Verify the keep straight to take exit number toward instructions gurka::assert::raw::expect_instructions_at_maneuver_index( result, maneuver_index, "Keep straight to take exit 22B toward C3/New York/Philadelphia.", "Keep straight to take exit 22B.", "Keep straight to take exit 22B toward C3, New York.", "Continue for 4 kilometers."); }
48.890547
96
0.47339
mixvit
1a01ed5437304d3d8e5213b54750414c978f5a0d
469
cpp
C++
Prime_in_a_given_range/prime_number_2nd/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
Prime_in_a_given_range/prime_number_2nd/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
Prime_in_a_given_range/prime_number_2nd/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int isPrime(int n) { if(n<2) return 0; else if(n%2==0) return 0; for(int i=3;i*i<=n;i+=2) { if(n%i==0) { return 0; } } return 1; } int main() { int num; cout<<"Enter the num"; cin>>num; if(isPrime(num)) { cout<<"Prime"; } else { cout<<"Not a Prime"; } return 0; }
13.794118
29
0.392324
narendrajethi220
1a054bec5c3e7f0d2a8f3785062f6278d1115ae7
10,743
cc
C++
src/flevent.cc
ComputerNerd/moonfltk
6da77cacb0b158907c5cf9320b9d06ca44dd43c0
[ "MIT" ]
38
2016-06-22T18:39:45.000Z
2021-09-14T00:15:18.000Z
src/flevent.cc
ComputerNerd/moonfltk
6da77cacb0b158907c5cf9320b9d06ca44dd43c0
[ "MIT" ]
23
2018-03-21T13:19:32.000Z
2022-02-15T12:09:23.000Z
src/flevent.cc
ComputerNerd/moonfltk
6da77cacb0b158907c5cf9320b9d06ca44dd43c0
[ "MIT" ]
9
2016-06-23T11:44:29.000Z
2022-02-05T09:08:49.000Z
/* The MIT License (MIT) * * Copyright (c) 2016 Stefano Trettel * * Software repository: MoonFLTK, https://github.com/stetre/moonfltk * * 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 "internal.h" /*----------------------------------------------------------------------* | Handlers | *----------------------------------------------------------------------*/ /* Event handler -------------------------------------------------------*/ static int EvRef = LUA_NOREF; static lua_State *EvState = NULL; static int EventHandler(int event) { #define L EvState if(pushvalue(L, EvRef) != LUA_TFUNCTION) return unexpected(L); push_Event(L, event); if(lua_pcall(L, 1, 1, 0) != LUA_OK) return unexpected(L); return checkboolean(L, -1); #undef L } static int Handler(lua_State *L) /* only 1 handler (multiplex it in Lua) */ { if(EvRef != LUA_NOREF) { Fl::remove_handler(EventHandler); unreference(L, EvRef); EvState = NULL; } if(lua_isnoneornil(L, 1)) return 0; if(!lua_isfunction(L, 1)) return luaL_argerror(L, 1, "function expected"); reference(L, EvRef, 1); EvState = L; Fl::add_handler(EventHandler); return 0; } #if 0 /* System event handler ------------------------------------------------*/ static int SysRef = LUA_NOREF; static lua_State *SysState = NULL; static int SystemHandler(void *event, void *data) { #define L SysState (void)data; if(pushvalue(L, SysRef) != LUA_TFUNCTION) return unexpected(L); // push_Event(L, event); @@ how to pass an XEvent ?! if(lua_pcall(L, 1, 1, 0) != LUA_OK) return unexpected(L); return checkboolean(L, -1); #undef L } static int System_handler(lua_State *L) /* only 1 handler (multiplex it in Lua) */ { if(SysRef != LUA_NOREF) { Fl::remove_system_handler(SystemHandler); unreference(L, SysRef); SysState = NULL; } if(lua_isnoneornil(L, 1)) return 0; if(!lua_isfunction(L, 1)) return luaL_argerror(L, 1, "function expected"); reference(L, SysRef, 1); SysState = L; Fl::add_system_handler(SystemHandler, NULL); return 0; } #endif /* Event dispatch ------------------------------------------------------*/ //typedef int (*Fl_Event_Dispatch)(int event, Fl_Window *w); //static void Fl::event_dispatch(Fl_Event_Dispatch d) //static Fl_Event_Dispatch Fl::event_dispatch() static int Event_dispatch(lua_State *L) //@@ { (void)L; return 0; } /*----------------------------------------------------------------------* | Functions | *----------------------------------------------------------------------*/ // FUNC_GETSET_POINTER(Widget, Fl::focus, Focus) static int Focus(lua_State *L) { if(lua_isnone(L, 1)) { Fl_Widget *v = Fl::focus(); if(!v) return 0; // Focus widget could be one belonging to FTLK unknown to // lua (e.g. scaling factor display for FLTK 1.4), therefore // push_...IfValid pushes nil for unknown widgets. return push_WidgetIfValid(L, v); } Fl_Widget *v = check_Widget(L, 1); Fl::focus(v); return 0; } FUNC_GETSET_POINTER(Widget, Fl::belowmouse, Belowmouse) #if 0 static int Compose(lua_State *L) { int del; lua_pushboolean(L, Fl::compose(del)); lua_pushinteger(L, del); return 2; } FUNC_VOID_VOID(Fl::compose_reset, Compose_reset) #endif FUNC_VOID_VOID(Fl::disable_im, Disable_im) FUNC_VOID_VOID(Fl::enable_im, Enable_im) static int Event(lua_State *L) { int e = Fl::event(); if(!e) return 0; push_Event(L, e); return 1; } FUNC_BOOLEAN_VOID(Fl::event_alt, Event_alt) static int Event_button(lua_State *L) { int b = Fl::event_button(); if(!b) return 0; push_Mouse_Button(L, b); return 1; } FUNC_BOOLEAN_VOID(Fl::event_button1, Event_button1) FUNC_BOOLEAN_VOID(Fl::event_button2, Event_button2) FUNC_BOOLEAN_VOID(Fl::event_button3, Event_button3) static int Event_buttons(lua_State *L) //@@ tutti e 7 o solo i primi 3? { int val = Fl::event_buttons(); for(int n = 1; n < 4; n++) lua_pushboolean(L, val & FL_BUTTON(n)); return 3; } FUNC_GETSET_INT(Fl::event_clicks, Event_clicks) static int Event_clipboard(lua_State *L) { const char *t = Fl::event_clipboard_type(); if(!t) return 0; if(strcmp(t,Fl::clipboard_image) != 0) return 0; Fl_Image *p = (Fl_Image*)Fl::event_clipboard(); if(!p) return 0; DBG_CREATE(Image, p); newuserdata(L, p, MT_Image); return 1; } static int Event_clipboard_type(lua_State *L) { const char *t = Fl::event_clipboard_type(); DBG("clipboard type = '%s'\n", t ? t : "none"); if(!t) return 0; lua_pushstring(L, t); return 1; } FUNC_BOOLEAN_VOID(Fl::event_command, Event_command) FUNC_BOOLEAN_VOID(Fl::event_ctrl, Event_ctrl) FUNC_INT_VOID(Fl::event_dx, Event_dx) FUNC_INT_VOID(Fl::event_dy, Event_dy) FUNC_GETSET_POINTER(Widget, Fl::pushed, Pushed) #if 0 //@@ uhm.... what if the pushed widget was not created by MoonFLTK? //static Fl_Widget * Fl::pushed() //static void Fl::pushed(Fl_Widget *) #endif static int Event_text(lua_State *L) { const char *t = Fl::event_text(); if(!t) return 0; lua_pushstring(L, t); return 1; } static int Event_key(lua_State *L) { if(lua_isnone(L, 1)) { int key = Fl::event_key(); if(key==0) return 0; push_Key(L, key); return 1; } int key = check_Key(L, 1); lua_pushboolean(L, Fl::event_key(key)); return 1; } static int Event_inside(lua_State *L) { int rc; if(lua_type(L, 1) == LUA_TNUMBER) { int x = luaL_checkinteger(L, 1); int y = luaL_checkinteger(L, 2); int w = luaL_checkinteger(L, 3); int h = luaL_checkinteger(L, 4); rc = Fl::event_inside(x, y, w, h); } else rc = Fl::event_inside(check_Widget(L, 1)); lua_pushboolean(L, rc); return 1; } FUNC_GETSET_BOOLEAN(Fl::event_is_click, Event_is_click) FUNC_INT_VOID(Fl::event_length, Event_length) FUNC_BOOLEAN_VOID(Fl::event_shift, Event_shift) static int Event_state(lua_State *L) { if(lua_isnone(L, 1)) return push_Modifiers(L, Fl::event_state()); lua_pushboolean(L, Fl::event_state(check_Modifiers(L, 1))); return 1; } FUNC_INT_VOID(Fl::event_x, Event_x) FUNC_INT_VOID(Fl::event_x_root, Event_x_root) FUNC_INT_VOID(Fl::event_y, Event_y) FUNC_INT_VOID(Fl::event_y_root, Event_y_root) #if 0 //static int Fl::event_original_key() //@@ static int Event_original_key(lua_State *L) { (void)L; return 0; } #endif static int Get_key(lua_State *L) { int key = check_Key(L, 1); lua_pushboolean(L, Fl::get_key(key)); return 1; } static int Get_mouse(lua_State *L) { int x, y; Fl::get_mouse(x, y); lua_pushinteger(L, x); lua_pushinteger(L, y); return 2; } #if 0 //static int Fl::handle(int, Fl_Window *) static int Handle(lua_State *L) //@@ { (void)L; return 0; } //static int Fl::handle_(int, Fl_Window *) static int Handle_(lua_State *L) //@@ { (void)L; return 0; } #endif static int Test_shortcut(lua_State *L) { int sc = check_Shortcut(L, 1); lua_pushboolean(L, Fl::test_shortcut(sc)); return 1; } /*------------------------------------------------------------------------------* | Registration | *------------------------------------------------------------------------------*/ static const struct luaL_Reg Functions[] = { { "belowmouse", Belowmouse }, // { "compose", Compose }, // { "compose_reset", Compose_reset }, { "disable_im", Disable_im }, { "enable_im", Enable_im }, { "event", Event }, { "event_alt", Event_alt }, { "event_button", Event_button }, { "event_button1", Event_button1 }, { "event_button2", Event_button2 }, { "event_button3", Event_button3 }, { "event_buttons", Event_buttons }, { "event_clicks", Event_clicks }, { "event_clipboard", Event_clipboard }, { "event_clipboard_type", Event_clipboard_type }, { "event_command", Event_command }, { "event_ctrl", Event_ctrl }, { "event_dx", Event_dx }, { "event_dy", Event_dy }, { "event_inside", Event_inside }, { "event_is_click", Event_is_click }, { "event_key", Event_key }, { "event_length", Event_length }, // { "event_original_key", Event_original_key }, { "event_shift", Event_shift }, { "event_state", Event_state }, { "event_text", Event_text }, { "event_x", Event_x }, { "event_x_root", Event_x_root }, { "event_y", Event_y }, { "event_y_root", Event_y_root }, { "focus", Focus }, { "get_key", Get_key }, { "get_mouse", Get_mouse }, // { "handle", Handle }, // { "handle_", Handle_ }, { "pushed", Pushed }, { "test_shortcut", Test_shortcut }, /* handlers */ { "handler", Handler }, // { "system_handler", System_handler }, { "event_dispatch", Event_dispatch }, { NULL, NULL } /* sentinel */ }; void moonfltk_open_FlEvent(lua_State *L) { luaL_setfuncs(L, Functions, 0); }
27.335878
82
0.577213
ComputerNerd
1a103e9e3241b455e7d47b41619b73db878694f5
10,516
cpp
C++
src/engine/World.cpp
vaeinoe/lvs
9d37b8f1008012f5fe616d0ef5be124142a6e178
[ "Unlicense" ]
null
null
null
src/engine/World.cpp
vaeinoe/lvs
9d37b8f1008012f5fe616d0ef5be124142a6e178
[ "Unlicense" ]
null
null
null
src/engine/World.cpp
vaeinoe/lvs
9d37b8f1008012f5fe616d0ef5be124142a6e178
[ "Unlicense" ]
null
null
null
/* * World.cpp * Leavs * * Created by Väinö Ala-Härkönen on 10/27/12. * Copyright 2012 Lumeet. All rights reserved. * */ #include "World.h" #include "Tile.h" #include "LVSEngine.h" #include "TileLevel.h" using namespace ci; void World::setup( Configuration *config, const Vec2i newSize ) { rnd.seed(time(0)); mConfig = config; size = new Vec2i( newSize.x, newSize.y ); solverTimer = mConfig->solverDelayFrames; selectedTile = NULL; reset(); } // Clears and reinits all tiles void World::reset() { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ (*t)->shutdown(); delete (*t); } tiles.clear(); tiles.reserve( size->x * size->y ); for (int x = 0; x < size->x; x++) { for (int y = 0; y < size->y; y++) { int type = rndTileType(); Tile *tile = new Tile(); tile->setup(mConfig, Vec2i( x, y ), type, false); tiles.push_back(tile); } } // If there's at least one match already, try another tile combination if (resolveTiles(false) == true) { reset(); } } void World::pause() { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ (*t)->pause(); } } void World::resume() { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ (*t)->resume(); } } // Shrink and fade out all tiles in the end of the game void World::shrink() { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ (*t)->shrink(); } } // Update all tiles' size modifiers and active status void World::update( const Vec2i *mouseLoc, const float *freqData, const int dataSize ) { int size = tiles.size(); int binsPerTile = dataSize / size; int n = 0; float dataSizef = (float)dataSize; for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ Vec2f pos = (*t)->getScreenPositionVector(); Vec2i dir = pos - (*mouseLoc); float modifier = 0; for (int i = 0; i < binsPerTile; i++) { int bin = n * binsPerTile + i; // How does this I don't even float mod = math<float>::clamp( freqData[ bin ] * ( bin / dataSizef ) * ( math<float>::log( ( dataSizef - (float)bin ) ) ), 0.0f, 2.0f ); modifier += mod; } (*t)->update(!mConfig->engine->dragging, dir.length(), modifier); n++; } solverTimer--; if (solverTimer == 0) { resolveTiles(true); solverTimer = mConfig->solverDelayFrames; } } // Returns the coordinate of tile's immediate neighbour to direction dir (lengths ignored) inline Vec2i World::neighbourCoord(Vec2i pos, Vec2i dir) { // N + S same for both alignments if (dir.x == 0) { if (dir.y < 0) { return Vec2i(pos.x, pos.y - 2); } else if (dir.y > 0) { return Vec2i(pos.x, pos.y + 2); } else { return Vec2i(pos.x, pos.y); } } Vec2i ret = Vec2i(0,0); if (dir.y < 0) { ret.y = pos.y - 1; } else if (dir.y > 0) { ret.y = pos.y + 1; } else { return Vec2i(pos.x, pos.y); } // No neighbouring tiles left & right if (dir.x > 0) { ret.x = pos.x; } else { ret.x = pos.x - 1; } // Even & odd rows handle this differently if (pos.y % 2 == 1) { ret.x += 1; } return ret; /* EVEN x y NE: +0 -1 NW: -1, -1 SE: +0, +1 SW: -1, +1 */ /* ODD x y NE: +1 -1 NW: +0 -1 SE: +1 +1 SW: +0 +1 */ } // Run resolver on all tiles bool World::resolveTiles(const bool act) { bool hits = false; for (int x = 0; x < size->x; x++) { for (int y = 2; y < size->y - 2; y++) { bool result = resolveTile(x, y, act); if (result == true) hits = true; } } return hits; } // Resolve the area around tile x, y - if act false, // doesn't kill tiles or update score bool World::resolveTile(int x, int y, bool act) { Vec2i pos = Vec2i(x, y); int tileIdx = tileIndex(pos); if (!tiles[tileIdx]->selectable()) { return false; } // These are enough for hit int reqTiles[] = { tileIndex(neighbourCoord(pos, Vec2i(0, 1))), tileIndex(neighbourCoord(pos, Vec2i(0, -1))) }; int bonusTiles[3]; Vec2i curr = neighbourCoord(pos, Vec2i(0, 1)); for (int i = 0; i < 3; i++) { curr = neighbourCoord(curr, Vec2i(0, 1)); bonusTiles[i] = tileIndex(curr); } // These give extra points int hextraTiles[] = { tileIndex(neighbourCoord(pos, Vec2i(1, 1))), tileIndex(neighbourCoord(pos, Vec2i(1, -1))), tileIndex(neighbourCoord(pos, Vec2i(-1, 1))), tileIndex(neighbourCoord(pos, Vec2i(-1, -1))) }; int type = tiles[tileIdx]->type; int reqHit = true; for (int i = 0; i < 2; i++) { if (reqTiles[i] >= tiles.size() || reqTiles[i] < 0 || !tiles[reqTiles[i]]->selectable() || tiles[reqTiles[i]]->type != type) { reqHit = false; break; } } if (!reqHit) return false; int hextraHit = true; for (int i = 0; i < 4; i++) { if (hextraTiles[i] >= tiles.size() || hextraTiles[i] < 0 || !tiles[hextraTiles[i]]->selectable() || tiles[hextraTiles[i]]->type != type) { hextraHit = false; break; } } if (act) { tiles[tileIdx]->kill(); int mult = 2; if (hextraHit) mult = 4; if (reqHit) { for (int i = 0; i < 2; i++) { tiles[reqTiles[i]]->kill(mult); } } if (hextraHit) { for (int i = 0; i < 4; i++) { tiles[hextraTiles[i]]->kill(mult); } } else { // Resolve bonus tiles if no hex hit for (int i = 0; i < 3; i++) { if (bonusTiles[i] < tiles.size() && bonusTiles[i] > 0 && tiles[bonusTiles[i]]->selectable() && tiles[bonusTiles[i]]->type == type) { tiles[bonusTiles[i]]->kill(mult + (2 * (i+1))); } else { break; } } } } return true; } void World::draw() { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ (*t)->draw(); } } // Returns a tile hit under the cursor inline Tile* World::getTileAt( Vec2i mouseLoc ) { for( vector<Tile*>::iterator t = tiles.begin(); t != tiles.end(); ++t ){ Vec2f pos = (*t)->getScreenPositionVector(); Vec2i dir = pos - mouseLoc; if (dir.length() < (0.95 * mConfig->tileSize)) return (*t); } return NULL; } // Toggles "surround" highlight for all the neigbouring tiles of tile inline void World::setSurrounding( Tile *tile, bool value ) { Vec2i pos; pos.x = tile->pos->x; pos.y = tile->pos->y; int neighbours[] = { tileIndex(neighbourCoord(pos, Vec2i(0, 1))), tileIndex(neighbourCoord(pos, Vec2i(0, -1))), tileIndex(neighbourCoord(pos, Vec2i(1, 1))), tileIndex(neighbourCoord(pos, Vec2i(1, -1))), tileIndex(neighbourCoord(pos, Vec2i(-1, 1))), tileIndex(neighbourCoord(pos, Vec2i(-1, -1))) }; for (int i = 0; i < 6; i++) { if (neighbours[i] < tiles.size() && neighbours[i] > 0) { tiles[neighbours[i]]->setSurrounding(value); } } } // Deselect + swap if required void World::deselectTile( const Vec2i mouseLoc ) { if (selectedTile) { selectedTile->toggleSelected(); setSurrounding(selectedTile, false); Tile *hover = getTileAt( mouseLoc ); if (hover && areNeighbours(selectedTile, hover) && selectedTile->selectable() && hover->selectable()) { swapTiles(hover, selectedTile); } selectedTile = NULL; } } // Selects a new tile and marks the surrounding tiles as highlighted void World::selectTile( const Vec2i mouseLoc ) { if (selectedTile) { selectedTile->toggleSelected(); selectedTile = NULL; } Tile *hover = getTileAt( mouseLoc ); if (hover && hover->selectable()) { hover->toggleSelected(); selectedTile = hover; setSurrounding(hover, true); } } // Returns true if tile1 != tile2 and tiles are neighbours on the grid bool World::areNeighbours ( Tile *tile1, Tile *tile2 ) { int x1 = tile1->pos->x; int x2 = tile2->pos->x; int y1 = tile1->pos->y; int y2 = tile2->pos->y; // A tile is not its own neighbour if (x1 == x2 && y1 == y2) return false; int y_dist = abs(y1 - y2); int x_dist = abs(x1 - x2); // Tiles are not neighbours if they have same y (interleaved y axis) // or are too far from each other in either axis if (y_dist == 0 || y_dist > 2 || x_dist > 1) return false; // Tiles are always neighbours if x value is the same and difference in y < 3 if (x1 == x2) return true; // Rules for even / odd tiles if (y_dist == 1) { bool even_y = y1 % 2 == 1; if (even_y && x1 - x2 == -1) return true; if (!even_y && x1 - x2 == 1) return true; } // No match return false; } // Swaps two tiles void World::swapTiles( Tile *tile1, Tile *tile2 ) { Vec2i pos1, pos2; pos1.x = tile1->pos->x; pos1.y = tile1->pos->y; pos2.x = tile2->pos->x; pos2.y = tile2->pos->y; Tile *tileTmp = tile1; tiles[tileIndex(pos1.x, pos1.y)] = tile2; tiles[tileIndex(pos2.x, pos2.y)] = tileTmp; tile1->moveTo(pos2); tile2->moveTo(pos1); mConfig->levels[tile1->type]->addScore(-1); mConfig->levels[tile2->type]->addScore(-1); } int World::rndTileType() { return rnd.nextInt(mConfig->numTileTypes); } inline int World::tileIndex(int x, int y) { if (x < 0 || y < 0) return -1; if (x >= size->x || y >= size->y) return -1; return ((x * size->y) + y); } inline int World::tileIndex(Vec2i pos) { if (pos.x < 0 || pos.y < 0) return -1; if (pos.x >= size->x || pos.y >= size->y) return -1; return ((pos.x * size->y) + pos.y); } void World::shutdown() { tiles.clear(); }
27.60105
149
0.52073
vaeinoe
1a121ab5d7faeae9a52642f84fafc8afbf700e98
1,626
cc
C++
interview/slice_window.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
interview/slice_window.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
interview/slice_window.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <set> using namespace std; /* * 给定一个数组array,给定一个正整数w * 假设数组的大小大于w * 输出数组中所有连续w个数的最大值和最小值的差的最大的绝对值。 * 也就是,对于连续的w个数,其中有最大值和最小值,计算最大值和最小值的差的绝对值, * 需要输出所有连续w个数的最大的绝对值。 * * 举例 * 数组 1 4 3 4 2 6 * w = 3 * * 总共有四组连续的3个数 * 1 4 3 * 4 3 4 * 3 4 2 * 4 2 6 * 每组中的最大值和最小值以及最大值和最小值的差的绝对值分别为 * 最大值 最小值 差的绝对值 * 4 1 3 * 4 3 1 * 4 2 2 * 6 2 4 * 那么,输出就是 4,表示差的绝对值的最大值。 */ static int absminus(int x, int y) { return x > y ? x - y : y - x; } int slice_windows(vector<int> vi, int w) { int min, max, maxabs; std::set<int> si; for (auto x : vi) cout << x << " "; cout << endl; if (vi.size() < 0 || vi.size() < w || w < 1) return -1; maxabs = 0; si.insert(vi.begin(), vi.begin() + w); for (auto x : si) cout << x << " "; cout << endl; int left = vi[0]; min = *si.begin(); max = *(si.rbegin()); maxabs = absminus(min, max); cout << "min: " << min << ", max:" << max << ", maxabs: " << maxabs << endl; for(int i = w; i < vi.size(); i++) { si.erase(left); if (si.size() < w-1) si.insert(left); si.insert(vi[i]); left = vi[i - w + 1]; int lmin = *si.begin(); int lmax = *(si.rbegin()); int lmaxabs = absminus(lmin, lmax); cout << "lmin: " << lmin << ", lmax:" << lmax << ", lmaxabs: " << lmaxabs << endl; if (lmaxabs > maxabs) { min = lmin; max = lmax; maxabs = lmaxabs; } for (auto x : si) cout << x << " "; cout << endl; cout << "min: " << min << ", max:" << max << ", maxabs: " << maxabs << endl; } } int test() { vector<int> vi {1,4,3,4,2,6}; slice_windows(vi, 3); } int main() { test(); }
16.762887
84
0.528905
sczzq
1a12e2fea02ae0855fbe1ff6e52a5e9fb1f7dab8
9,244
cpp
C++
oneflow/core/framework/tensor_pool.cpp
shihan-ma/oneflow
1705ec0859aefb4ff07a29ae4255fab70c67464b
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/tensor_pool.cpp
shihan-ma/oneflow
1705ec0859aefb4ff07a29ae4255fab70c67464b
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/tensor_pool.cpp
shihan-ma/oneflow
1705ec0859aefb4ff07a29ae4255fab70c67464b
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow 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 "oneflow/core/eager/local_call_opkernel_phy_instr_operand.h" #include "oneflow/core/framework/tensor_pool.h" #include "oneflow/user/kernels/stateful_local_opkernel.h" namespace oneflow { namespace vm { class LocalCallOpKernelPhyInstrOperand; } namespace one { DTRTensorPool::DTRTensorPool() { num_recomputation_ = 0; num_eviction_ = 0; num_destruction_ = 0; // candidates_ = std::set<std::weak_ptr<vm::DTREagerBlobObject>>(); candidates_ = std::vector<std::weak_ptr<vm::DTREagerBlobObject>>(); start_time_ = std::chrono::steady_clock::now(); total_memory_bytes_ = 0; } namespace { void printInfo(const std::shared_ptr<vm::DTREagerBlobObject>& debo) { double mem = debo->BlobBodyBytes() * 1. / 1024 / 1024; const std::string& compute_op = debo->compute_op()->shared_opkernel()->user_op_conf_->op_type_name(); auto fa = debo->node->parent(); std::cout << "is_in_memory: " << static_cast<bool>(debo->is_in_memory()) << ", is pinned: " << (debo->num_pinned()) << ", is evictable: " << (debo->is_evictable()) << ", compute op: " << compute_op << ", shape: " << debo->mut_blob_desc()->shape() << ", memory: " << mem << "MB" << ", ebo address: " << debo.get() << ", blob dptr: " << debo->blob().dptr() << ", tensor buffer dptr: " << static_cast<const void*>(debo->tensor_buffer()->blob_dptr()) << ", node->compute_time(): " << debo->node->compute_time() << ", node: " << debo->node // << ", data_type: " << debo->mut_blob_desc()->data_type() << std::endl; } } // namespace Maybe<vm::DTREagerBlobObject*> DTRTensorPool::find_best_tensor() { double min_cost = -1; vm::DTREagerBlobObject* best(nullptr); int evict_object_id = -1; if (oneflow::DTRDebugEnabled()) { std::cout << "Finding best tensor to evict..." << std::endl; } int id = 0; double tensor_pool_mem = 0.; for (const auto& object : candidates_) { if (auto shared_object = object.lock()) { double cur_cost = -1; if (static_cast<bool>(shared_object->compute_op()) && !shared_object->is_pinned() && (shared_object->is_evictable()) && shared_object->is_in_memory()) { cur_cost = JUST(shared_object->cost()); // cur_cost = JUST(shared_object->reverse_cost()); if (min_cost < 0 || min_cost > cur_cost) { best = shared_object.get(); min_cost = cur_cost; evict_object_id = id; } if (oneflow::DTRDebugLevel() >= 2) { std::cout << "id " << id << ", "; printInfo(shared_object); } } if (oneflow::DTRDebugEnabled()) { // copy op in lenet/alexnet model is always to copy parameters // from cpu to gpu during model.to('cuda') // copying from cpu to gpu uses cuda h2d memory pool, unrelated // to the cuda memory pool dtr uses. double mem = shared_object->BlobBodyBytes() * 1. / 1024 / 1024; const std::string& compute_op = shared_object->compute_op()->shared_opkernel()->user_op_conf_->op_type_name(); if (shared_object->is_in_memory() && compute_op != "copy") { tensor_pool_mem += mem; } } } else { JUST(display()); std::cout << "Unable to lock candidates in tensor pool: " << id << ", is_expired: " << object.expired() << std::endl; } id++; } if (oneflow::DTRDebugEnabled()) { std::cout << "pool mem is " << tensor_pool_mem << "MB" << std::endl; const auto pd = best->parent_depth(); const auto cd = best->child_depth(); std::cout << "Evict " << evict_object_id << "th object, depth is " << pd << "+" << cd << "=" << (pd + cd) << ", cost is " << min_cost << ", compute op is " << (best ? best->compute_op()->shared_opkernel()->op_type_name() : "null") << ", addr is " << best << std::endl; } num_eviction_++; return best; } Maybe<bool> DTRTensorPool::find_best_tensor_and_evict() { auto* best = JUST(find_best_tensor()); if (best == nullptr) { return false; } JUST(best->evict()); JUST(update_after_evict(best)); return true; } Maybe<void> DTRTensorPool::insert(std::shared_ptr<vm::DTREagerBlobObject> blob_object, size_t thres) { CHECK_NOTNULL_OR_RETURN(blob_object); CHECK_EQ_OR_RETURN(thres, 0); // if ((blob_object->is_evictable()) && (blob_object->memory() > thres)) { if (true) { // // for set version // candidates_.insert(blob_object); // for vector version for (const auto& object : candidates_) { if (object.lock() == blob_object) { return Maybe<void>::Ok(); } } candidates_.emplace_back(blob_object); } return Maybe<void>::Ok(); } Maybe<void> DTRTensorPool::clear() { auto object = candidates_.begin(); while (object != candidates_.end()) { if (object->lock().get() == nullptr) { if (oneflow::DTRDebugEnabled()) { // std::cout << "Erase nullptr candidates from tensor_pool." << std::endl; } candidates_.erase(object); num_destruction_++; return Maybe<void>::Ok(); } ++object; } return Maybe<void>::Ok(); } double DTRTensorPool::duration() { auto t2 = std::chrono::steady_clock::now(); // time in seconds std::chrono::duration<double> time_span = t2 - start_time_; // // time in milli // std::chrono::duration<double ,std::milli> time_span = t2 - start_time_; return time_span.count(); } Maybe<void> DTRTensorPool::display2() { std::cout << "===== Info of current tensor pool =====" << std::endl; std::cout << "Number of candidates: " << candidates_.size() << std::endl; int id = 0; float total_mem = 0; float pinned_mem = 0; for (const auto& object : candidates_) { if (auto shared_object = object.lock()) { if (shared_object->is_in_memory()) { std::cout << "id " << id << ", "; printInfo(shared_object); total_mem += shared_object->BlobBodyBytes() * 1. / 1024 / 1024; if (shared_object->is_pinned()) { pinned_mem += shared_object->BlobBodyBytes() * 1. / 1024 / 1024; } } } id++; } std::cout << "Total memory: " << total_mem << "MB" << std::endl; std::cout << "Pinned memory: " << pinned_mem << "MB" << std::endl; return Maybe<void>::Ok(); } Maybe<void> DTRTensorPool::display() { std::cout << "===== Info of current tensor pool =====" << std::endl; std::cout << "Number of candidates: " << candidates_.size() << std::endl; return Maybe<void>::Ok(); } // Disjoint Node Set void DTRTensorPool::merge(std::shared_ptr<vm::DisjNode>& x, std::shared_ptr<vm::DisjNode>& y) { auto&& parent_x = find_father(x); auto&& parent_y = find_father(y); if (parent_x.get() == parent_y.get()) { return; } parent_y->set_compute_time(parent_y->compute_time() + parent_x->compute_time()); parent_x->set_parent(parent_y); } std::shared_ptr<vm::DisjNode> DTRTensorPool::find_father(std::shared_ptr<vm::DisjNode>& x) { if (x->is_root()) { return x; } else { auto fa = x->parent(); auto&& y = find_father(fa); x->set_parent(y); return y; } } void DTRTensorPool::update_after_recompute(vm::DTREagerBlobObject* obj) { auto&& fa = find_father(obj->node); fa->set_compute_time(fa->compute_time() - obj->node->compute_time()); obj->reset_node(obj->compute_time()); obj->reset_pesudo_node(); } Maybe<void> DTRTensorPool::update_after_evict(vm::DTREagerBlobObject* obj) { auto* operand = obj->compute_op(); const auto& inputs = operand->inputs(); const auto& outputs = operand->outputs(); for (int i = 0; i < inputs.size(); ++i) { if (auto tmp = inputs[i].lock()) { auto dtr_blob_object = dynamic_cast<vm::DTREagerBlobObject*>(tmp.get()); CHECK_NOTNULL_OR_RETURN(dtr_blob_object); // condition: obj!=dtr_blob_object - avoids self-merge due to inplace op if (!dtr_blob_object->is_in_memory() && obj != dtr_blob_object) { merge(dtr_blob_object->node, obj->node); } } } for (int i = 0; i < outputs.size(); ++i) { if (auto tmp = outputs[i].lock()) { auto dtr_blob_object = dynamic_cast<vm::DTREagerBlobObject*>(tmp.get()); CHECK_NOTNULL_OR_RETURN(dtr_blob_object); if (!dtr_blob_object->is_in_memory() && obj!= dtr_blob_object) { merge(obj->node, dtr_blob_object->node); } } } obj->reset_pesudo_node(); return Maybe<void>::Ok(); } void DTRTensorPool::set_total_memory(size_t mem) { total_memory_bytes_ = mem; } size_t DTRTensorPool::get_total_memory() { return total_memory_bytes_; } } // namespace one } // namespace oneflow
35.282443
113
0.625054
shihan-ma
1a135edc31e2f9ca47c8e5438f74ddb832858a50
7,057
cpp
C++
example/ccana/source/pyfunc.cpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
example/ccana/source/pyfunc.cpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
example/ccana/source/pyfunc.cpp
goroyabu/anlpy
2d5d65b898d31d69f990e973cbfdbabd8cb0a15c
[ "MIT" ]
null
null
null
/** @file pyfunc.cpp @date 2020/05/06 @author goroyabu @detail Automatically generated by make_anlpy_project.sh 1.0.0 **/ #include "ProjectCone3D.hpp" #include "IterateCone3D.hpp" #include "Extract2Photon.hpp" #include "Project2Photon3D.hpp" #include "Iterate2Photon3D.hpp" #include "PETimager.hpp" #include "ProjectConeETCC.hpp" #include "FilterComptree.hpp" #include "ProjectComptree.hpp" #include <pybind11/pybind11.h> PYBIND11_MODULE(ccana, m) { m.attr("__name__") = "ccana"; m.doc() = R"pbdoc( ccana Documentation ----------------------- )pbdoc"; pybind11::class_<anl::VANL_Module>(m, "VANL_Module", pybind11::module_local()); pybind11::class_<ProjectCone3D, anl::VANL_Module>(m, "ProjectCone3D") .def(pybind11::init<>()) .def("SetParameter", &ProjectCone3D::set_parameter<int>) .def("SetParameter", &ProjectCone3D::set_parameter<double>) .def("SetParameter", &ProjectCone3D::set_parameter<bool>) .def("SetParameter", &ProjectCone3D::set_parameter<std::string>) .def("DefineParameter", &ProjectCone3D::define_parameter<int>) .def("DefineParameter", &ProjectCone3D::define_parameter<double>) .def("DefineParameter", &ProjectCone3D::define_parameter<bool>) .def("DefineParameter", &ProjectCone3D::define_parameter<std::string>) .def("ShowParameter", &ProjectCone3D::show_parameters); pybind11::class_<IterateCone3D, anl::VANL_Module>(m, "IterateCone3D") .def(pybind11::init<>()) .def("SetParameter", &IterateCone3D::set_parameter<int>) .def("SetParameter", &IterateCone3D::set_parameter<double>) .def("SetParameter", &IterateCone3D::set_parameter<bool>) .def("SetParameter", &IterateCone3D::set_parameter<std::string>) .def("DefineParameter", &IterateCone3D::define_parameter<int>) .def("DefineParameter", &IterateCone3D::define_parameter<double>) .def("DefineParameter", &IterateCone3D::define_parameter<bool>) .def("DefineParameter", &IterateCone3D::define_parameter<std::string>) .def("ShowParameter", &IterateCone3D::show_parameters); pybind11::class_<Extract2Photon, anl::VANL_Module>(m, "Extract2Photon") .def(pybind11::init<>()) .def("SetParameter", &Extract2Photon::set_parameter<int>) .def("SetParameter", &Extract2Photon::set_parameter<double>) .def("SetParameter", &Extract2Photon::set_parameter<bool>) .def("SetParameter", &Extract2Photon::set_parameter<std::string>) .def("DefineParameter", &Extract2Photon::define_parameter<int>) .def("DefineParameter", &Extract2Photon::define_parameter<double>) .def("DefineParameter", &Extract2Photon::define_parameter<bool>) .def("DefineParameter", &Extract2Photon::define_parameter<std::string>) .def("ShowParameter", &Extract2Photon::show_parameters); pybind11::class_<Project2Photon3D, anl::VANL_Module>(m, "Project2Photon3D") .def(pybind11::init<>()) .def("SetParameter", &Project2Photon3D::set_parameter<int>) .def("SetParameter", &Project2Photon3D::set_parameter<double>) .def("SetParameter", &Project2Photon3D::set_parameter<bool>) .def("SetParameter", &Project2Photon3D::set_parameter<std::string>) .def("DefineParameter", &Project2Photon3D::define_parameter<int>) .def("DefineParameter", &Project2Photon3D::define_parameter<double>) .def("DefineParameter", &Project2Photon3D::define_parameter<bool>) .def("DefineParameter", &Project2Photon3D::define_parameter<std::string>) .def("ShowParameter", &Project2Photon3D::show_parameters); pybind11::class_<Iterate2Photon3D, anl::VANL_Module>(m, "Iterate2Photon3D") .def(pybind11::init<>()) .def("SetParameter", &Iterate2Photon3D::set_parameter<int>) .def("SetParameter", &Iterate2Photon3D::set_parameter<double>) .def("SetParameter", &Iterate2Photon3D::set_parameter<bool>) .def("SetParameter", &Iterate2Photon3D::set_parameter<std::string>) .def("DefineParameter", &Iterate2Photon3D::define_parameter<int>) .def("DefineParameter", &Iterate2Photon3D::define_parameter<double>) .def("DefineParameter", &Iterate2Photon3D::define_parameter<bool>) .def("DefineParameter", &Iterate2Photon3D::define_parameter<std::string>) .def("ShowParameter", &Iterate2Photon3D::show_parameters); pybind11::class_<PETimager, anl::VANL_Module>(m, "PETimager") .def(pybind11::init<>()) .def("SetParameter", &PETimager::set_parameter<int>) .def("SetParameter", &PETimager::set_parameter<double>) .def("SetParameter", &PETimager::set_parameter<bool>) .def("SetParameter", &PETimager::set_parameter<std::string>) .def("DefineParameter", &PETimager::define_parameter<int>) .def("DefineParameter", &PETimager::define_parameter<double>) .def("DefineParameter", &PETimager::define_parameter<bool>) .def("DefineParameter", &PETimager::define_parameter<std::string>) .def("ShowParameter", &PETimager::show_parameters); pybind11::class_<ProjectConeETCC, anl::VANL_Module>(m, "ProjectConeETCC") .def(pybind11::init<>()) .def("SetParameter", &ProjectConeETCC::set_parameter<int>) .def("SetParameter", &ProjectConeETCC::set_parameter<double>) .def("SetParameter", &ProjectConeETCC::set_parameter<bool>) .def("SetParameter", &ProjectConeETCC::set_parameter<std::string>) .def("DefineParameter", &ProjectConeETCC::define_parameter<int>) .def("DefineParameter", &ProjectConeETCC::define_parameter<double>) .def("DefineParameter", &ProjectConeETCC::define_parameter<bool>) .def("DefineParameter", &ProjectConeETCC::define_parameter<std::string>) .def("ShowParameter", &ProjectConeETCC::show_parameters); pybind11::class_<FilterComptree, anl::VANL_Module>(m, "FilterComptree") .def(pybind11::init<>()) .def("SetParameter", &FilterComptree::set_parameter<int>) .def("SetParameter", &FilterComptree::set_parameter<double>) .def("SetParameter", &FilterComptree::set_parameter<bool>) .def("SetParameter", &FilterComptree::set_parameter<std::string>) .def("DefineParameter", &FilterComptree::define_parameter<int>) .def("DefineParameter", &FilterComptree::define_parameter<double>) .def("DefineParameter", &FilterComptree::define_parameter<bool>) .def("DefineParameter", &FilterComptree::define_parameter<std::string>) .def("ShowParameter", &FilterComptree::show_parameters); pybind11::class_<ProjectComptree, anl::VANL_Module>(m, "ProjectComptree") .def(pybind11::init<>()) .def("SetParameter", &ProjectComptree::set_parameter<int>) .def("SetParameter", &ProjectComptree::set_parameter<double>) .def("SetParameter", &ProjectComptree::set_parameter<bool>) .def("SetParameter", &ProjectComptree::set_parameter<std::string>) .def("DefineParameter", &ProjectComptree::define_parameter<int>) .def("DefineParameter", &ProjectComptree::define_parameter<double>) .def("DefineParameter", &ProjectComptree::define_parameter<bool>) .def("DefineParameter", &ProjectComptree::define_parameter<std::string>) .def("ShowParameter", &ProjectComptree::show_parameters); #ifdef VERSION_INFO m.attr("__version__") = VERSION_INFO; #else m.attr("__version__") = "dev"; #endif }
48.668966
83
0.738841
goroyabu
1a1f918e9d0f00e54705b9fdbb05cb24e0112a3b
1,709
cpp
C++
lib/core/barf_filoc.cpp
vdods/barf
5c943ddbd6a0a7624645158b0c85994431dde269
[ "Apache-2.0" ]
1
2021-01-16T00:55:45.000Z
2021-01-16T00:55:45.000Z
lib/core/barf_filoc.cpp
vdods/barf
5c943ddbd6a0a7624645158b0c85994431dde269
[ "Apache-2.0" ]
null
null
null
lib/core/barf_filoc.cpp
vdods/barf
5c943ddbd6a0a7624645158b0c85994431dde269
[ "Apache-2.0" ]
null
null
null
// 2006.02.11 - Copyright Victor Dods - Licensed under Apache 2.0 #include "barf_filoc.hpp" #include <sstream> #include "barf_message.hpp" #include "barf_path.hpp" #include "barf_util.hpp" namespace Barf { FiLoc const FiLoc::ms_invalid; string FiLoc::AsString () const { assert(this != &ms_invalid && "can't use FiLoc::ms_invalid in this manner"); assert(IsValid()); ostringstream out; out << m_filename; if (m_line_number > 0) out << ":" << m_line_number; return out.str(); } string FiLoc::LineDirectiveString (string const &relative_to_path) const { assert(this != &ms_invalid && "do not use this on a FiLoc without a line number"); assert(IsValid()); string line_directive_path; if (!relative_to_path.empty()) try { line_directive_path = Path(m_filename).make_absolute().relative_to(relative_to_path).as_string(); } catch (std::exception const &e) { EmitWarning(string("caught exception while trying to generate #line directive path \"" + m_filename + "\" relative to path \"" + relative_to_path + "\"; exception was \"") + e.what() + "\""); line_directive_path = FilenamePortion(m_filename); } else line_directive_path = FilenamePortion(m_filename); ostringstream out; out << "#line " << m_line_number << " \"" << line_directive_path << "\""; return out.str(); } void FiLoc::IncrementLineNumber (Uint32 by_value) { assert(m_line_number > 0 && "don't use this on non-line-number-using FiLocs"); m_line_number += by_value; } ostream &operator << (ostream &stream, FiLoc const &filoc) { return stream << filoc.AsString(); } } // end of namespace Barf
28.483333
203
0.65828
vdods
1a26c978aaeee71576e873ab6ff0e05ae1159aaa
11,886
cpp
C++
sourcecode/client/nsclient/src/goproxy.cpp
nosngame/nosn
76dc0525aa9a5baf6aca7d2c18c75b79a1d31e28
[ "Unlicense" ]
4
2019-12-04T13:06:52.000Z
2021-09-24T04:45:53.000Z
sourcecode/client/nsclient/src/goproxy.cpp
nosngame/nosn
76dc0525aa9a5baf6aca7d2c18c75b79a1d31e28
[ "Unlicense" ]
null
null
null
sourcecode/client/nsclient/src/goproxy.cpp
nosngame/nosn
76dc0525aa9a5baf6aca7d2c18c75b79a1d31e28
[ "Unlicense" ]
null
null
null
#include "precomplie.h" namespace NSProxy { CNSMap< int, CGoProxyObject* > gGoProxyObject; CNSLuaStack& CNSGoProxy::marshal( CNSLuaStack& luaStack ) const { NSClient::gpLuaStack = &luaStack; // key 为第一个对象的名称,value为数据代理 if ( NSClient::gGoLoadProc( mFileName.getBuffer( ), mParentID, mType ) == false ) NSException( NSClient::gGoGetLastError( ) ); return luaStack; } const CNSLuaStack& CNSGoProxy::unmarshal( const CNSLuaStack& luaStack ) { return luaStack; } static int invokeMethod( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyComponent* proxyComp = NULL; luaStack >> proxyComp; if ( proxyComp == NULL ) NSException( _UTF8( "组件方法调用错误" ) ); CNSOctetsStream stream; while ( luaStack.isEnd( ) == false ) luaStack >> stream; int dataType = EDataType::TYPE_NONE; void* buf = NULL; if ( NSClient::gGoInvoke( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, stream.begin( ), stream.length( ), buf, dataType ) == false ) NSException( NSClient::gGoGetLastError( ) ); if ( dataType == EDataType::TYPE_BOOLEAN ) luaStack << *(bool*) buf; else if ( dataType == EDataType::TYPE_CHAR ) luaStack << *(char*) buf; else if ( dataType == EDataType::TYPE_UCHAR ) luaStack << *(unsigned char*) buf; else if ( dataType == EDataType::TYPE_SHORT ) luaStack << *(short*) buf; else if ( dataType == EDataType::TYPE_USHORT ) luaStack << *(unsigned short*) buf; else if ( dataType == EDataType::TYPE_INT ) luaStack << *(int*) buf; else if ( dataType == EDataType::TYPE_UINT ) luaStack << *(unsigned int*) buf; else if ( dataType == EDataType::TYPE_INT64 ) luaStack << ( double ) *(long long*) buf; else if ( dataType == EDataType::TYPE_UINT64 ) luaStack << ( double ) *( unsigned long long* ) buf; else if ( dataType == EDataType::TYPE_FLOAT ) luaStack << ( double ) *(float*) buf; else if ( dataType == EDataType::TYPE_DOUBLE ) luaStack << ( double ) *(double*) buf; else if ( dataType == EDataType::TYPE_STRING ) { static CNSString value; value = (char*) buf; luaStack << value; } DECLARE_END_PROTECTED } static int destroy( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyObject* proxy = NULL; luaStack >> proxy; if ( proxy == NULL ) NSException( _UTF8( "destroy方法调用错误" ) ); // 销毁unity对象 if ( NSClient::gGoDestroyProc( proxy->mInstanceID ) == false ) NSException( NSClient::gGoGetLastError( ) ); // 销毁组件的lua事件函数 HLISTINDEX beginIndex = proxy->mUIProxyComp.getHead( ); for ( ; beginIndex != NULL; proxy->mUIProxyComp.getNext( beginIndex ) ) { NSProxy::CGoProxyComponent* proxyComp = proxy->mUIProxyComp.getValue( beginIndex ); if ( proxyComp->onEventFunc.isValid( ) == true ) luaStack.clearFunc( proxyComp->onEventFunc ); proxyComp->cleanUpRef( ); delete proxyComp; } // 清理所有引用 proxy->cleanUpRef( ); // 删除对象 HMAPINDEX mapIndex = gGoProxyObject.findNode( proxy->mInstanceID ); if ( mapIndex != NULL ) { NSProxy::CGoProxyObject* proxyObjectRef = gGoProxyObject.getValueEx( mapIndex ); delete proxyObjectRef; gGoProxyObject.eraseNode( mapIndex ); } DECLARE_END_PROTECTED } static int proxyGetField( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyComponent* proxyComp = NULL; luaStack >> proxyComp; static CNSString fieldName; luaStack >> fieldName; bool isMethod = false; if ( NSClient::gGoQueryMethod( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, isMethod ) == false ) NSException( NSClient::gGoGetLastError( ) ); if ( isMethod == true ) { lua_pushcfunction( lua, invokeMethod ); return 1; } int dataType = EDataType::TYPE_NONE; void* buf = NULL; if ( NSClient::gGoGetValue( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, buf, dataType ) == false ) NSException( NSClient::gGoGetLastError( ) ); if ( dataType == EDataType::TYPE_BOOLEAN ) luaStack << *(bool*) buf; else if ( dataType == EDataType::TYPE_CHAR ) luaStack << *(char*) buf; else if ( dataType == EDataType::TYPE_UCHAR ) luaStack << *(unsigned char*) buf; else if ( dataType == EDataType::TYPE_SHORT ) luaStack << *(short*) buf; else if ( dataType == EDataType::TYPE_USHORT ) luaStack << *(unsigned short*) buf; else if ( dataType == EDataType::TYPE_INT ) luaStack << *(int*) buf; else if ( dataType == EDataType::TYPE_UINT ) luaStack << *(unsigned int*) buf; else if ( dataType == EDataType::TYPE_INT64 ) luaStack << ( double ) *(long long*) buf; else if ( dataType == EDataType::TYPE_UINT64 ) luaStack << ( double ) *( unsigned long long* ) buf; else if ( dataType == EDataType::TYPE_FLOAT ) luaStack << ( double ) *(float*) buf; else if ( dataType == EDataType::TYPE_DOUBLE ) luaStack << ( double ) *(double*) buf; else if ( dataType == EDataType::TYPE_STRING ) { static CNSString value; value = (char*) buf; luaStack << value; } DECLARE_END_PROTECTED } static int proxySetField( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyComponent* proxyComp = NULL; luaStack >> proxyComp; static CNSString fieldName; luaStack >> fieldName; int type = lua_type( lua, 3 ); if ( type == LUA_TNUMBER ) { double value; luaStack >> value; if ( NSClient::gGoSetValue( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, &value, EDataType::TYPE_DOUBLE ) == false ) NSException( NSClient::gGoGetLastError( ) ); } else if ( type == LUA_TBOOLEAN ) { bool value; luaStack >> value; if ( NSClient::gGoSetValue( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, &value, EDataType::TYPE_BOOLEAN ) == false ) NSException( NSClient::gGoGetLastError( ) ); } else if ( type == LUA_TSTRING ) { static CNSString value; luaStack >> value; if ( NSClient::gGoSetValue( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, (char*) value.getBuffer( ), EDataType::TYPE_STRING ) == false ) NSException( NSClient::gGoGetLastError( ) ); } else if ( type == LUA_TFUNCTION ) { CNSLuaFunction func( __FUNCTION__ ); luaStack >> func; if ( func.isValid( ) == false ) NSException( _UTF8( "函数[proxySetField]参数3 不是一个lua函数" ) ) proxyComp->onEventFunc = func; if ( NSClient::gGoSetValue( proxyComp->mProxyObject->mType, proxyComp->mProxyObject->mInstanceID, proxyComp->mCompName, fieldName, NULL, EDataType::TYPE_NONE ) == false ) NSException( NSClient::gGoGetLastError( ) ); } DECLARE_END_PROTECTED } static int proxyGetComponent( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyObject* proxy = NULL; luaStack >> proxy; static CNSString compName; luaStack >> compName; // 对象方法写在这里 if ( compName == "destroy" ) { lua_pushcfunction( lua, destroy ); return 1; } if ( compName == "id" ) { lua_pushinteger( lua, proxy->mInstanceID ); return 1; } if ( compName == "layer" ) { const char* layer = NULL; if ( NSClient::gGoGetLayer( proxy->mType, proxy->mInstanceID, layer ) == false ) NSException( NSClient::gGoGetLastError( ) ); static CNSString value; value = (char*) layer; luaStack << value; return 1; } if ( compName == "tag" ) { const char* tag = NULL; if ( NSClient::gGoGetTag( proxy->mType, proxy->mInstanceID, tag ) == false ) NSException( NSClient::gGoGetLastError( ) ); static CNSString value; value = (char*) tag; luaStack << value; return 1; } CGoProxyComponent** goCompRef = NULL; CGoProxyComponent* goComp = NULL; goCompRef = proxy->mUIProxyComp.get( compName ); if ( goCompRef != NULL ) goComp = *goCompRef; // 如果组件不存在,代理层添加 // 脚本不能主动添加组件,是不是考虑加一个对象方法添加组件? if ( goComp == NULL ) { goComp = new CGoProxyComponent( compName, proxy ); proxy->mUIProxyComp.insert( compName, goComp ); } luaStack << goComp; DECLARE_END_PROTECTED } static int proxySetComponent( lua_State* lua ) { DECLARE_BEGIN_PROTECTED CGoProxyObject* proxy = NULL; luaStack >> proxy; static CNSString compName; luaStack >> compName; if ( compName == "layer" ) { static CNSString layerName; luaStack >> layerName; if ( NSClient::gGoSetLayer( proxy->mType, proxy->mInstanceID, layerName.getBuffer( ) ) == false ) NSException( NSClient::gGoGetLastError( ) ); return 0; } if ( compName == "tag" ) { static CNSString tagName; luaStack >> tagName; if ( NSClient::gGoSetTag( proxy->mType, proxy->mInstanceID, tagName.getBuffer( ) ) == false ) NSException( NSClient::gGoGetLastError( ) ); return 0; } DECLARE_END_PROTECTED } void CGoProxyObject::pushUserData( CNSLuaStack& luaStack, CGoProxyObject* ref ) { luaStack.setIndexFunc( NSProxy::proxyGetComponent ); luaStack.setNewIndexFunc( NSProxy::proxySetComponent ); static CNSVector< const luaL_Reg* > reg; luaStack.pushNSWeakRef( ref, "nsGoProxy", reg ); } void CGoProxyObject::popUserData( const CNSLuaStack& luaStack, CGoProxyObject*& ref ) { ref = (CGoProxyObject*) luaStack.popNSWeakRef( "nsGoProxy" ); } void CGoProxyComponent::pushUserData( CNSLuaStack& luaStack, CGoProxyComponent* ref ) { luaStack.setIndexFunc( proxyGetField ); luaStack.setNewIndexFunc( proxySetField ); static CNSVector< const luaL_Reg* > reg; luaStack.pushNSWeakRef( ref, "nsGoProxyComponent", reg ); } void CGoProxyComponent::popUserData( const CNSLuaStack& luaStack, CGoProxyComponent*& ref ) { ref = (CGoProxyComponent*) luaStack.popNSWeakRef( "nsGoProxyComponent" ); } } void nsCreateGoProxy( int type, int instanceID, const char* objName ) { CNSLuaStack& luaStack = *NSClient::gpLuaStack; NSProxy::CGoProxyObject* goProxyObject = new NSProxy::CGoProxyObject( type, instanceID, objName ); luaStack.pushField( objName, goProxyObject ); NSProxy::gGoProxyObject.insert( instanceID, goProxyObject ); } void nsSetGoLoadProc( FGoLoadProc loadProc ) { NSClient::gGoLoadProc = loadProc; } void nsSetGoDestroyProc( FGoDestroyProc destroyProc ) { NSClient::gGoDestroyProc = destroyProc; } void nsSetGoSetProc( FGoSetValue setProc ) { NSClient::gGoSetValue = setProc; } void nsSetGoGetProc( FGoGetValue getProc ) { NSClient::gGoGetValue = getProc; } void nsSetGoGetLayer( FGoGetLayer getLayer ) { NSClient::gGoGetLayer = getLayer; } void nsSetGoGetTag( FGoGetTag getTag ) { NSClient::gGoGetTag = getTag; } void nsSetGoSetLayer( FGoSetLayer setLayer ) { NSClient::gGoSetLayer = setLayer; } void nsSetGoSetTag( FGoSetTag setTag ) { NSClient::gGoSetTag = setTag; } void nsSetGoQueryMethod( FGoQueryMethod queryMethod ) { NSClient::gGoQueryMethod = queryMethod; } void nsSetGoInvoke( FGoInvoke invoke ) { NSClient::gGoInvoke = invoke; } void nsSetGoGetLastError( FGoGetLastError lastErrorProc ) { NSClient::gGoGetLastError = lastErrorProc; } void nsGoFireEvent( int instanceID, const char* compName ) { try { NSProxy::CGoProxyObject** proxyObjectRef = NSProxy::gGoProxyObject.get( instanceID ); if ( proxyObjectRef == NULL ) return; NSProxy::CGoProxyObject* uiProxyObject = *proxyObjectRef; NSProxy::CGoProxyComponent** nsCompRef = uiProxyObject->mUIProxyComp.get( compName ); if ( nsCompRef == NULL ) return; NSProxy::CGoProxyComponent* nsComp = *nsCompRef; CNSLuaStack& luaStack = CNSLuaStack::getLuaStack( ); if ( nsComp->onEventFunc.isValid( ) == false ) return; luaStack.preCall( nsComp->onEventFunc ); luaStack << uiProxyObject; luaStack.call( ); } catch ( CNSException& e ) { NSLog::exception( _UTF8( "函数[nsGoFireEvent]发生异常\n错误描述: \n\t%s\nC++调用堆栈: \n%s" ), e.mErrorDesc, NSBase::NSFunction::getStackInfo( ).getBuffer( ) ); } }
28.099291
197
0.692075
nosngame
1a2a1882902e20ae5b55c42b5824338bd5b618ef
2,982
cpp
C++
zodiacgraph/edgegrouppair.cpp
IEEM-HsKA/Automotive-Security-Threat-Modelling-Tool
e3b2ea5a188b11aaa4bb329edcc0d3d1b47ae07b
[ "MIT" ]
1
2021-12-08T13:27:22.000Z
2021-12-08T13:27:22.000Z
zodiacgraph/edgegrouppair.cpp
IEEM-HsKA/Automotive-Security-Threat-Modelling-Tool
e3b2ea5a188b11aaa4bb329edcc0d3d1b47ae07b
[ "MIT" ]
null
null
null
zodiacgraph/edgegrouppair.cpp
IEEM-HsKA/Automotive-Security-Threat-Modelling-Tool
e3b2ea5a188b11aaa4bb329edcc0d3d1b47ae07b
[ "MIT" ]
null
null
null
#include "edgegrouppair.h" #include <QGraphicsScene> #include <QSet> #include "edgegroup.h" #include "labeltextfactory.h" #include "node.h" #include "plugedge.h" #include "scene.h" #include "straightdoubleedge.h" namespace zodiac { EdgeGroupPair::EdgeGroupPair(Scene *scene, Node *nodeA, Node *nodeB) : EdgeGroupInterface(), m_scene(scene), m_firstGroup(new EdgeGroup(scene, nodeA, nodeB, this)), m_secondGroup(new EdgeGroup(scene, nodeB, nodeA, this)), m_edge(new StraightDoubleEdge(m_scene, this, nodeA, nodeB)) { // upon creation, the PlugEdge creating the first EdgeGroup is still bent and // visible. m_edge->setVisible(false); } EdgeGroupPair::~EdgeGroupPair() { // delete the groups delete m_firstGroup; delete m_secondGroup; m_firstGroup = nullptr; m_secondGroup = nullptr; // As EdgeGroupPairs are always deleted before the rest of the QGraphicsView, // this also work on shutdown // delete the double edge m_edge->getFromNode()->removeStraightEdge(m_edge); m_edge->getToNode()->removeStraightEdge(m_edge); m_scene->removeItem(m_edge); delete m_edge; // valgrind seems to mind a call to deleteLater() here... I've // read it's not real but this works also m_edge = nullptr; } bool EdgeGroupPair::isEmpty() const { return ((m_firstGroup->getEdgeCount() == 0) && (m_secondGroup->getEdgeCount() == 0)); } void EdgeGroupPair::updateDoubleEdgeVisibility() { // return early, if any of the two group edges is not visible if (!m_firstGroup->isVisible() || !m_secondGroup->isVisible()) { return; } // if both are visible, hide them and show the double edge in their place m_firstGroup->setVisibility(false); m_secondGroup->setVisibility(false); m_edge->setVisible(true); } void EdgeGroupPair::hideDoubleEdge() { // hide the double edge m_edge->setVisible(false); // let the edge groups determine by themselves if they need to become visible // or not m_firstGroup->updateVisibility(); m_secondGroup->updateVisibility(); } void EdgeGroupPair::updateLabel() { m_edge->updateLabel(); } QString EdgeGroupPair::getLabelText() { LabelTextFactory firstLabelGroup(m_firstGroup->getEdges()); LabelTextFactory secondLabelGroup(m_secondGroup->getEdges()); int maxNameLength = qMax(firstLabelGroup.getMaxNameLength(), secondLabelGroup.getMaxNameLength()); int labelCount = firstLabelGroup.getLabelCount() + secondLabelGroup.getLabelCount() + 1; QStringList labelStrings; labelStrings.reserve(labelCount); labelStrings << firstLabelGroup.produceLabel(maxNameLength); labelStrings << LabelTextFactory::getHorizontalLine(maxNameLength); labelStrings << secondLabelGroup.produceLabel(maxNameLength); return labelStrings.join(LabelTextFactory::getNewlineChar()); } void EdgeGroupPair::updateStyle() { m_edge->updateStyle(); m_firstGroup->updateStyle(); m_secondGroup->updateStyle(); } } // namespace zodiac
30.428571
79
0.728706
IEEM-HsKA
1a2c186186b06f127a7c4507d7f6435f264df189
333
cpp
C++
definitions/patches/aspell/FreeBSD/patch-prog__checker_string.cpp
VerKnowSys/sofin-definitions
9ca5a00fda2acd510e59d39b50bd74c930edcc26
[ "BSD-2-Clause" ]
1
2021-12-07T12:36:18.000Z
2021-12-07T12:36:18.000Z
definitions/patches/aspell/FreeBSD/patch-prog__checker_string.cpp
VerKnowSys/sofin-definitions
9ca5a00fda2acd510e59d39b50bd74c930edcc26
[ "BSD-2-Clause" ]
1
2019-01-10T15:36:52.000Z
2019-01-10T15:36:53.000Z
definitions/patches/aspell/FreeBSD/patch-prog__checker_string.cpp
VerKnowSys/sofin-definitions
9ca5a00fda2acd510e59d39b50bd74c930edcc26
[ "BSD-2-Clause" ]
null
null
null
--- prog/checker_string.cpp.orig Thu Jul 17 19:39:02 2003 +++ prog/checker_string.cpp Thu Jul 17 19:39:09 2003 @@ -4,6 +4,7 @@ // license along with this library if you did not you can find // it at http://www.gnu.org/. +#include <assert.h> #include "checker_string.hpp" #include "speller.hpp" #include "document_checker.hpp"
30.272727
63
0.696697
VerKnowSys
1a2fc46c2a343865fa8a7168cc966fcfdd154606
5,917
cpp
C++
Project/zoolib/HTTP/Content.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
13
2015-01-28T21:05:09.000Z
2021-11-03T22:21:11.000Z
Project/zoolib/HTTP/Content.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
null
null
null
Project/zoolib/HTTP/Content.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
4
2018-11-16T08:33:33.000Z
2021-12-11T19:40:46.000Z
// Copyright (c) 2014 Andrew Green. MIT License. http://www.zoolib.org #include "zoolib/HTTP/Content.h" #include "zoolib/Chan_XX_Limited.h" #include "zoolib/ChanW_Bin_More.h" #include "zoolib/Memory.h" #include "zoolib/MIME.h" #include "zoolib/Util_Chan.h" #include "zoolib/Util_string.h" namespace ZooLib { namespace HTTP { using std::max; using std::min; // ================================================================================================= #pragma mark - Helpers (anonymous) namespace { // anonymous } // anonymous namespace // ================================================================================================= #pragma mark - HTTP::ChanR_Bin_Chunked static uint64 spReadChunkSize(const ChanR_Bin& iChanR) { uint64 result = 0; for (;;) { ZQ<byte> theQ = sQRead(iChanR); if (not theQ) return 0; int theXDigit = 0; if (*theQ >= '0' && *theQ <= '9') { theXDigit = *theQ - '0'; } else if (*theQ >= 'a' && *theQ <= 'f') { theXDigit = *theQ - 'a' + 10; } else if (*theQ >= 'A' && *theQ <= 'F') { theXDigit = *theQ - 'A' + 10; } else { if (*theQ != '\n') { // Skip everything till we hit a LF sSkip_Until<byte>(iChanR, byte('\n')); } break; } result = (result << 4) + theXDigit; } return result; } ChanR_Bin_Chunked::ChanR_Bin_Chunked(const ChanR_Bin& iChanR) : fChanR(iChanR) { fChunkSize = spReadChunkSize(fChanR); fHitEnd = fChunkSize == 0; } ChanR_Bin_Chunked::~ChanR_Bin_Chunked() {} size_t ChanR_Bin_Chunked::Read(byte* oDest, size_t iCount) { byte* localDest = oDest; while (iCount && !fHitEnd) { if (fChunkSize == 0) { // Read and discard the CRLF at the end of the chunk. const uint64 countSkipped = sSkip(fChanR, 2); if (countSkipped == 2) fChunkSize = spReadChunkSize(fChanR); if (fChunkSize == 0) fHitEnd = true; } else { const size_t countRead = sRead(fChanR, localDest, std::min<size_t>(iCount, sClamped(fChunkSize))); if (countRead == 0) fHitEnd = true; localDest += countRead; iCount -= countRead; fChunkSize -= countRead; } } return localDest - oDest; } size_t ChanR_Bin_Chunked::Readable() { return min<size_t>(sClamped(fChunkSize), sReadable(fChanR)); } // ================================================================================================= #pragma mark - HTTP::ChanW_Bin_Chunked ChanW_Bin_Chunked::ChanW_Bin_Chunked(size_t iBufferSize, const ChanW_Bin& iChanW) : fChanW(iChanW), fBuffer(max(size_t(64), iBufferSize), 0), fBufferUsed(0) {} ChanW_Bin_Chunked::ChanW_Bin_Chunked(const ChanW_Bin& iChanW) : fChanW(iChanW), fBuffer(1024, 0), fBufferUsed(0) {} ChanW_Bin_Chunked::~ChanW_Bin_Chunked() { try { this->pFlush(); // Terminating zero-length chunk sEWrite(fChanW, "0\r\n"); // There's supposed to be an additional CRLF at the end of all the data, // after any trailer entity headers. sEWrite(fChanW, "\r\n"); } catch (...) {} } size_t ChanW_Bin_Chunked::Write(const byte* iSource, size_t iCount) { const uint8* localSource = reinterpret_cast<const uint8*>(iSource); while (iCount) { if (fBufferUsed + iCount >= fBuffer.size()) { // The data would overflow the buffer, so we can write the // buffer content (if any) plus this new stuff. sEWritef(fChanW, "%X\r\n", fBufferUsed + iCount); // Hmmm. Do we allow an end of stream exception to propogate? sEWrite(fChanW, &fBuffer[0], fBufferUsed); fBufferUsed = 0; sEWrite(fChanW, localSource, iCount); sEWrite(fChanW, "\r\n"); localSource += iCount; iCount = 0; } else { size_t countToCopy = min(iCount, size_t(fBuffer.size() - fBufferUsed)); sMemCopy(&fBuffer[0] + fBufferUsed, localSource, countToCopy); fBufferUsed += countToCopy; iCount -= countToCopy; localSource += countToCopy; } } return localSource - reinterpret_cast<const uint8*>(iSource); } void ChanW_Bin_Chunked::Flush() { this->pFlush(); sFlush(fChanW); } void ChanW_Bin_Chunked::pFlush() { if (const size_t bufferUsed = fBufferUsed) { fBufferUsed = 0; sEWritef(fChanW, "%X\r\n", bufferUsed); sEWrite(fChanW, &fBuffer[0], bufferUsed); sEWrite(fChanW, "\r\n"); } } // ================================================================================================= #pragma mark - HTTP::sMakeContentChanner static ZP<ChannerR_Bin> spMakeChanner_Transfer( const Map& iHeader, const ZP<ChannerR_Bin>& iChannerR) { // According to the spec, if content is chunked, content-length must be ignored. // I've seen some pages being returned with transfer-encoding "chunked, chunked", which // is either a mistake, or is nested chunking. I'm assuming the former for now. if (Util_string::sContainsi(sGetString0(iHeader.Get("transfer-encoding")), "chunked")) return sChanner_Channer_T<ChanR_Bin_Chunked>(iChannerR); if (ZQ<int64> contentLength = iHeader.QGet<int64>("content-length")) return sChanner_Channer_T<ChanR_XX_Limited<ChanR_Bin>>(iChannerR, *contentLength); return iChannerR; } ZP<ChannerR_Bin> sMakeContentChanner(const Map& iHeader, ZP<ChannerR_Bin> iChannerR) { iChannerR = spMakeChanner_Transfer(iHeader, iChannerR); // We could/should look for gzip Content-Encoding, and wrap a decoding filter around it. return iChannerR; } ZP<ChannerR_Bin> sMakeContentChanner( const std::string& iMethod, int iResponseCode, const Map& iHeader, const ZP<ChannerR_Bin>& iChannerR) { if (iMethod == "HEAD") { return sChanner_T<ChanR_XX_Null<byte>>(); } if (iMethod == "GET" && iResponseCode == 304) { // RFC 2616, section 10.3.5. // "The 304 response MUST NOT contain a message-body, and thus is // always terminated by the first empty line after the header fields." return sChanner_T<ChanR_XX_Null<byte>>(); } return sMakeContentChanner(iHeader, iChannerR); } } // namespace HTTP } // namespace ZooLib
25.072034
100
0.63495
ElectricMagic
1a31771161fe8f3544d44b68218306582a1f152d
352
hpp
C++
src/triangle.hpp
tsoding/ray-tracer
c8d189cc53445cae56bfb5e4f76926b93d0e67d5
[ "MIT" ]
16
2016-05-25T10:33:41.000Z
2019-09-02T22:09:00.000Z
src/triangle.hpp
tsoding/ray-tracer
c8d189cc53445cae56bfb5e4f76926b93d0e67d5
[ "MIT" ]
67
2018-07-16T10:34:20.000Z
2018-10-23T16:02:43.000Z
src/triangle.hpp
tsoding/ray-tracer
c8d189cc53445cae56bfb5e4f76926b93d0e67d5
[ "MIT" ]
5
2018-07-31T19:09:08.000Z
2018-08-21T21:31:44.000Z
#ifndef TRIANGLE_HPP_ #define TRIANGLE_HPP_ #include "vec.hpp" #include "wall.hpp" // TODO(#65): support for triangle meshes from obj files struct Triangle { v3f v1, v2, v3; }; plane plane_of_triangle(const Triangle &triangle); bool ray_hits_triangle(const Triangle &triangle, const v3f &ray); #endif // TRIANGLE_HPP_
18.526316
56
0.693182
tsoding
1a33ad5d47add3d5ac5bafec0e805dc293c93e3c
4,446
cpp
C++
Snake/server/src/Server.cpp
BMZE/RVR-FinalProject
c9ee0fc65f159c329f831ba16b2aec72bda2fc75
[ "MIT" ]
null
null
null
Snake/server/src/Server.cpp
BMZE/RVR-FinalProject
c9ee0fc65f159c329f831ba16b2aec72bda2fc75
[ "MIT" ]
null
null
null
Snake/server/src/Server.cpp
BMZE/RVR-FinalProject
c9ee0fc65f159c329f831ba16b2aec72bda2fc75
[ "MIT" ]
null
null
null
#include "Server.h" #include <string> #include <unistd.h> #include <string.h> #include <iostream> #include <pthread.h> #include "Message.h" #include "Socket.h" #include "InputInfo.h" #include "ServerGame.h" #pragma region STATIC ATTRIBUTES ServerGame* Server::_game = nullptr; volatile bool Server::_inputRegistered = false; InputInfo* Server::_playersInput = nullptr; volatile bool Server::_gameEnd = false; #pragma endregion Server::Server(const char * s, const char * p) { _socket = new Socket(s, p); _socket->Bind(); _clients.reserve(MAX_PLAYERS); _playersInput = new InputInfo[MAX_PLAYERS]; } //Receives and processes messages from clients void Server::ProcessMessages() { std::cout << "Snake server is running\n" << "Waiting for players to join\n"; int playersReady = 0; int inputRecv = 0; while(true) //receive messages { Socket* client; Message msg; _socket->recv(msg, client); switch(msg._type) { case Message::LOGIN: if(_clients.size() < MAX_PLAYERS) //add player { _clients.push_back(client); std::cout << "Player " << _clients.size() << " joined the game\n"; Message ms(Message::INIT); //notify client to init game and send player id ms._player = (_clients.size() - 1) + '0'; //client is last player to join _socket->send(ms, *client); if(_gameEnd) _gameEnd = false; //game thread can run } else { //TODO: send message to stop game as player can't join std::cout << "Maximum number of players reached\n"; } break; case Message::READY: playersReady++; if(playersReady == MAX_PLAYERS) //ready to start game { CreateGameThread(); //Thread to run game SendToClients(Message(Message::START)); std::cout << "Game ready\n"; } break; case Message::INPUT: inputRecv++; _playersInput[(msg._player-'0')] = InputInfo(msg._inputInfo); if(inputRecv == MAX_PLAYERS) //game update can be run { inputRecv = 0; _inputRegistered = true; } //std::cout << "Input received\n"; break; case Message::LOGOUT: for(int i = 0; i < _clients.size(); i++) //delete player from saved clients { if(*_clients[i] == *client) { _clients.erase(_clients.begin() + i); int id = (msg._player - '0') + 1; std::cout << "Player " << id << " exited game" << std::endl; break; } } _gameEnd = true; playersReady = 0; inputRecv = 0; break; } } } //Sends a message to all clients connected to the server void Server::SendToClients(Message msg) { for(Socket* sock: _clients) { _socket->send(msg, *sock); } } //Creates and sets the thread that runs the game on the server void Server::CreateGameThread() { pthread_t gameThread; //thread pthread_attr_t attr; _game = new ServerGame(this); _game->Init(); //initialize game before setting thread pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); int res = pthread_create(&gameThread, &attr, RunGame, NULL); if(res != 0) std::cout << "Error, Thread was not created\n"; } //Thread function that runs the game server side void* Server::RunGame(void*) { /// *** FOR TEST: COMMENT PLAYER LOST CONDITION *** /// while (!_gameEnd && !_game->PlayerLost()) { if(_inputRegistered) { _inputRegistered = false; _game->SetInputInfo(_playersInput); _game->Update(); } } pthread_exit(NULL); } Server::~Server() { if(_game != nullptr) { delete _game; _game = nullptr; } delete _socket; _socket = nullptr; delete [] _playersInput; }
27.7875
95
0.523842
BMZE
1a369174ac4ebb2de07ca544bc39389415e4b708
57
cpp
C++
frame.cpp
spiroyster/frend
24012ca09df82fc3bb11e84dfa3526b6f3c3c251
[ "BSD-2-Clause" ]
null
null
null
frame.cpp
spiroyster/frend
24012ca09df82fc3bb11e84dfa3526b6f3c3c251
[ "BSD-2-Clause" ]
null
null
null
frame.cpp
spiroyster/frend
24012ca09df82fc3bb11e84dfa3526b6f3c3c251
[ "BSD-2-Clause" ]
null
null
null
#include "frend.hpp" namespace frend { }
6.333333
21
0.508772
spiroyster
1a3888f4f6e76123a8e7d1a33c44460adb94630f
2,929
cpp
C++
Chapter_1_Introduction/Adhoc_Problems/vjudge_UVA-10388_snap.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_1_Introduction/Adhoc_Problems/vjudge_UVA-10388_snap.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_1_Introduction/Adhoc_Problems/vjudge_UVA-10388_snap.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
// UVa 10388 Snap // Use basic deque operations and the random() function to simulate a card game // Annoying presentation errors from printing extra newline chars. Also remember to clean up data structures between test cases! // Time: O(1) since limited by 1000 moves, Memory: O(N) where N is the number of cards in the game #include <bits/stdc++.h> using namespace std; deque<char> jane_down, jane_up, john_down, john_up; int T; int main(){ cin >> T; for(int tc = 0; tc< T; tc++){ // Parse Input string temp; cin >> temp; for (auto c: temp){ jane_down.push_back(c); } cin >> temp; for (auto c: temp){ john_down.push_back(c); } // Perform Simuation bool finished = false; for (int move=1; move<= 1000; move++){ jane_up.push_front(jane_down.front()); jane_down.pop_front(); john_up.push_front(john_down.front()); john_down.pop_front(); if (john_up.front() == jane_up.front()){ bool jane_winner = !(random()/141%2); if (jane_winner){ while(!john_up.empty()){ jane_up.push_front(john_up.back()); john_up.pop_back(); } cout << "Snap! for Jane: "; for (auto i:jane_up) cout << i; cout << endl; } else{ while(!jane_up.empty()){ john_up.push_front(jane_up.back()); jane_up.pop_back(); } cout << "Snap! for John: "; for (auto i:john_up) cout << i; cout << endl; } } if (jane_down.empty() && jane_up.empty()){ cout << "John wins." << endl; finished = true; break; } if (john_down.empty() && john_up.empty()){ cout << "Jane wins." << endl; finished = true; break; } if(jane_down.empty()){ while(!jane_up.empty()){ jane_down.push_front(jane_up.front()); jane_up.pop_front(); } } if(john_down.empty()){ while(!john_up.empty()){ john_down.push_front(john_up.front()); john_up.pop_front(); } } } if (!finished){ cout << "Keeps going and going ..." << endl; } if (tc != T-1) cout << endl; // Clean up jane_down.clear(); jane_up.clear(); john_down.clear(); john_up.clear(); } return 0; }
29
128
0.435302
BrandonTang89
1a38ac714f0267e3740415ec76da25f163f7978e
1,345
cpp
C++
cppcheck/data/c_files/398.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/398.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/398.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context, GURL site_url) { // Don't lock to origin in --single-process mode, since this mode puts // cross-site pages into the same process. if (RenderProcessHost::run_renderer_in_process()) return false; if (!DoesSiteRequireDedicatedProcess(browser_context, site_url)) return false; // Guest processes cannot be locked to their site because guests always have // a fixed SiteInstance. The site of GURLs a guest loads doesn't match that // SiteInstance. So we skip locking the guest process to the site. // TODO(ncarter): Remove this exclusion once we can make origin lock per // RenderFrame routing id. if (site_url.SchemeIs(content::kGuestScheme)) return false; // TODO(creis, nick) https://crbug.com/510588 Chrome UI pages use the same // site (chrome://chrome), so they can't be locked because the site being // loaded doesn't match the SiteInstance. if (site_url.SchemeIs(content::kChromeUIScheme)) return false; // TODO(creis, nick): Until we can handle sites with effective URLs at the // call sites of ChildProcessSecurityPolicy::CanAccessDataForOrigin, we // must give the embedder a chance to exempt some sites to avoid process // kills. if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context, site_url)) { return false; } return true; }
38.428571
76
0.769517
awsm-research